# Phase 0 WASM hello-world.
#
# Only built when the Emscripten toolchain is active (see the root
# CMakeLists.txt — it early-returns into this subdir when EMSCRIPTEN is set).
# Rule R5: this target must never become a Phase 1 dependency.

if(NOT EMSCRIPTEN)
    message(FATAL_ERROR
        "wasm/CMakeLists.txt requires the Emscripten toolchain. "
        "Use: cmake --preset wasm  (after activating emsdk).")
endif()

add_executable(hello hello.cpp)

# Emit an ES6 module so Node 20+ and modern browsers can `import` it directly.
# Suffix .mjs is what tells emcc to emit an ES module; the matching .wasm is
# produced alongside it.
set_target_properties(hello PROPERTIES
    OUTPUT_NAME "hello"
    SUFFIX ".mjs"
    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)

# Emscripten link flags. Keep this list short — every flag added here is a
# Phase 0 commitment the frontend dev will inherit.
target_link_options(hello PRIVATE
    "-sMODULARIZE=1"
    "-sEXPORT_ES6=1"
    "-sENVIRONMENT=node,web"
    # Functions callable from JS via ccall/cwrap. Underscore-prefix is the
    # C symbol name emscripten exposes.
    "-sEXPORTED_FUNCTIONS=['_add','_hello_version']"
    "-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap']"
    # Engine blueprint §6.3: real PDFs can exceed the default heap.
    "-sALLOW_MEMORY_GROWTH=1"
)

target_compile_features(hello PRIVATE cxx_std_23)

message(STATUS "WASM hello-world configured")
message(STATUS "  Output ............... ${CMAKE_BINARY_DIR}/bin/hello.mjs (+ hello.wasm)")
