@ignifx/editor-host 0.0.0-stage → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/client.d.ts +21 -0
- package/dist/error-codes.d.ts +44 -0
- package/dist/error-codes.d.ts.map +1 -0
- package/dist/error-codes.js +46 -0
- package/dist/error-codes.js.map +1 -0
- package/dist/index.d.ts +2628 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6236 -0
- package/dist/index.js.map +1 -0
- package/dist/vite.d.ts +245 -0
- package/dist/vite.d.ts.map +1 -0
- package/dist/vite.js +432 -0
- package/dist/vite.js.map +1 -0
- package/package.json +83 -3
- package/skills/editor-host/SKILL.md +350 -0
- package/README.md +0 -3
package/dist/vite.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../src/vite/errors.ts","../src/vite/modules.ts","../src/vite/plugin.ts"],"sourcesContent":["/**\n * The error the Vite plugin throws.\n *\n * @remarks\n * The plugin runs in the dev server's Node process, where loading `@ignifx/core` (and through it\n * Babylon Lite) to throw its `IgnifxError` would be pure cost. Like `@ignifx/vite-plugin`'s own\n * error, it carries the same registered `IGX-####` codes the page half throws.\n */\n\nimport type { EditorHostErrorCode } from \"../error-codes.js\";\n\n/**\n * The error every `@ignifx/editor-host/vite` API throws for a misconfiguration\n * (`CONSTITUTION.md` §3.9).\n *\n * @beta\n */\nexport class EditorHostPluginError extends Error {\n /** The stable diagnostic code for this failure. */\n readonly code: EditorHostErrorCode;\n\n /**\n * Creates a plugin error.\n *\n * @param code - The stable `IGX-####` code for the failure.\n * @param message - An actionable description of what went wrong and how to fix it.\n */\n constructor(code: EditorHostErrorCode, message: string) {\n super(message);\n this.name = \"EditorHostPluginError\";\n this.code = code;\n }\n}\n","/**\n * The page and the two modules the plugin generates: the scene view's HTML entry, the module that\n * page runs, and `virtual:ignifx/editor`, the play view's controls.\n */\n\nimport {\n ASSET_CHANGED_EVENT,\n IGNIFX_CONFIG_DEFINE_KEY,\n MANIFEST_MODULE_ID,\n SCRIPTS_MODULE_ID,\n} from \"@ignifx/vite-plugin\";\nimport { EditorHostErrorCode } from \"../error-codes.js\";\nimport { EditorHostPluginError } from \"./errors.js\";\n\n/**\n * The path the scene view is served at, below the dev server's `base`.\n *\n * @beta\n */\nexport const EDITOR_PAGE_PATH = \"/__ignifx_editor__/\";\n\n/**\n * The module a game imports to hand its app to the editor's play controls.\n *\n * @example\n * ```ts\n * import { attachEditorPlayControls } from \"virtual:ignifx/editor\";\n *\n * attachEditorPlayControls(app);\n * ```\n *\n * @beta\n */\nexport const EDITOR_MODULE_ID = \"virtual:ignifx/editor\";\n\n/**\n * The resolved id of {@link EDITOR_MODULE_ID}. The `\\0` prefix marks it as owned by a plugin.\n *\n * @beta\n */\nexport const RESOLVED_EDITOR_MODULE_ID: string = `\\0${EDITOR_MODULE_ID}`;\n\n/**\n * The module the scene view's page runs. Only the generated page imports it.\n *\n * @beta\n */\nexport const EDITOR_ENTRY_MODULE_ID = \"virtual:ignifx/editor-host-entry\";\n\n/**\n * The resolved id of {@link EDITOR_ENTRY_MODULE_ID}.\n *\n * @beta\n */\nexport const RESOLVED_EDITOR_ENTRY_MODULE_ID: string = `\\0${EDITOR_ENTRY_MODULE_ID}`;\n\n/**\n * The function `virtual:ignifx/editor` exports. It takes the game's app and returns a function that\n * detaches the controls; in a production build it does nothing.\n *\n * @beta\n */\nexport const EDITOR_PLAY_CONTROLS_EXPORT = \"attachEditorPlayControls\";\n\n/**\n * The module the scene view imports the project's extensions from, unless the plugin is told\n * otherwise. It exports `extensions()`, which returns the list `main.ts` passes to `createApp`.\n *\n * @beta\n */\nexport const DEFAULT_EXTENSIONS_MODULE = \"/src/extensions.ts\";\n\n/**\n * The `id` of the scene view's canvas.\n *\n * @beta\n */\nexport const EDITOR_CANVAS_ID = \"ignifx-editor-view\";\n\n/** The package the generated modules import the host from, resolved from the project's root. */\nconst HOST_PACKAGE = \"@ignifx/editor-host\";\n\n/**\n * Options accepted by {@link editorEntryModuleSource}.\n *\n * @beta\n */\nexport interface EditorEntryModuleOptions {\n /** The origin the editor is served from. */\n readonly editorOrigin: string;\n /** The root-absolute path of the project's extensions module, or `null` when it has none. */\n readonly extensionsModule: string | null;\n /** A scene address to load before the app starts, or `null`. */\n readonly bootScene: string | null;\n /** The project's `@ignifx/core` version, or `null` when it could not be read. */\n readonly engineVersion: string | null;\n /** Milliseconds between heartbeats, or `null` for the host's default. */\n readonly heartbeatIntervalMs: number | null;\n}\n\n/**\n * Options accepted by {@link playControlsModuleSource}.\n *\n * @beta\n */\nexport interface PlayControlsModuleOptions {\n /** The origin the editor is served from. */\n readonly editorOrigin: string;\n /** The project's `@ignifx/core` version, or `null` when it could not be read. */\n readonly engineVersion: string | null;\n /** Milliseconds between heartbeats, or `null` for the host's default. */\n readonly heartbeatIntervalMs: number | null;\n /**\n * Emit the development module. `false` emits the production no-op, which imports nothing and has\n * no `import.meta.hot` reference.\n */\n readonly hot: boolean;\n}\n\n/**\n * Turns the `extensions` option into the root-absolute path the generated module imports.\n *\n * @param path - The path as configured, relative to the Vite root or already root-absolute.\n * @returns The root-absolute path, for example `\"/src/extensions.ts\"`.\n * @throws EditorHostPluginError `IGX-1803` when the path is empty or leaves the root with `..`.\n *\n * @beta\n */\nexport function normalizeExtensionsModule(path: string): string {\n const trimmed = path.startsWith(\"./\") ? path.slice(2) : path;\n if (trimmed === \"\" || trimmed === \"/\" || trimmed.split(\"/\").some((segment) => segment === \"..\")) {\n throw new EditorHostPluginError(\n EditorHostErrorCode.invalidOption,\n `The \"extensions\" option must name a module inside the Vite root, for example \"src/extensions.ts\"; got \"${path}\".`,\n );\n }\n return trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n}\n\n/**\n * The fields shared by both generated calls, as source text.\n *\n * @param engineVersion - The version to report, or `null`.\n * @param heartbeatIntervalMs - The heartbeat period, or `null`.\n * @returns Zero, one, or two `key: value,` lines.\n */\nfunction reportingLines(engineVersion: string | null, heartbeatIntervalMs: number | null): readonly string[] {\n return [\n ...(engineVersion === null ? [] : [` engineVersion: ${JSON.stringify(engineVersion)},`]),\n ...(heartbeatIntervalMs === null ? [] : [` heartbeatIntervalMs: ${JSON.stringify(heartbeatIntervalMs)},`]),\n ];\n}\n\n/**\n * Generates the module the scene view's page runs.\n *\n * @remarks\n * The module is the only code with an import-time effect: it creates the host. The package itself\n * creates nothing when imported (`CONSTITUTION.md` §3.5). Every import is resolved from the\n * project's root, so the host, the scripts, and the extensions share the project's one copy of\n * `@ignifx/core`. It hands every `ignifx:asset-changed` event to `host.assetChanged`, which\n * reloads the asset in place; the `import.meta.hot` calls are written out literally, because Vite\n * finds them by reading the source.\n *\n * @param options - The editor origin, the project's extensions module, and the reporting options.\n * @returns The ES module source.\n *\n * @beta\n */\nexport function editorEntryModuleSource(options: EditorEntryModuleOptions): string {\n const { extensionsModule } = options;\n return [\n `import { startEditorHost } from ${JSON.stringify(HOST_PACKAGE)};`,\n `import { manifest } from ${JSON.stringify(MANIFEST_MODULE_ID)};`,\n `import { acceptHotReload, scripts } from ${JSON.stringify(SCRIPTS_MODULE_ID)};`,\n ...(extensionsModule === null ? [] : [`import { extensions } from ${JSON.stringify(extensionsModule)};`]),\n \"\",\n \"const host = await startEditorHost({\",\n ` editorOrigin: ${JSON.stringify(options.editorOrigin)},`,\n ' hostKind: \"scene\",',\n ` canvas: document.getElementById(${JSON.stringify(EDITOR_CANVAS_ID)}),`,\n ` settings: ${IGNIFX_CONFIG_DEFINE_KEY},`,\n \" assets: { manifest },\",\n ` extensions: ${extensionsModule === null ? \"[]\" : \"extensions()\"},`,\n \" scripts,\",\n ` bootScene: ${JSON.stringify(options.bootScene)},`,\n ...reportingLines(options.engineVersion, options.heartbeatIntervalMs),\n \"});\",\n \"acceptHotReload(host.app);\",\n \"if (import.meta.hot) {\",\n ` import.meta.hot.on(${JSON.stringify(ASSET_CHANGED_EVENT)}, (change) => {`,\n \" void host.assetChanged(change);\",\n \" });\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Generates the scene view's HTML page, before Vite's own `transformIndexHtml` adds its client.\n *\n * @returns The HTML document.\n *\n * @beta\n */\nexport function editorPageHtml(): string {\n return [\n \"<!doctype html>\",\n '<html lang=\"en\">',\n \" <head>\",\n ' <meta charset=\"utf-8\" />',\n ' <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />',\n \" <title>ignifx editor host</title>\",\n \" <style>\",\n \" html, body { margin: 0; height: 100%; overflow: hidden; background: #000; }\",\n ` #${EDITOR_CANVAS_ID} { display: block; width: 100%; height: 100%; }`,\n \" </style>\",\n \" </head>\",\n \" <body>\",\n ` <canvas id=\"${EDITOR_CANVAS_ID}\"></canvas>`,\n ` <script type=\"module\" src=\"/@id/${EDITOR_ENTRY_MODULE_ID}\"></script>`,\n \" </body>\",\n \"</html>\",\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Generates `virtual:ignifx/editor`.\n *\n * @remarks\n * In development, the module listens for the editor's connect message as soon as it is evaluated,\n * which is before the game's `main.ts` runs, and keeps the port\n * (`listenForEditorPlayControls`); `attachEditorPlayControls(app)` then starts the play controls on\n * it, so the editor's first connect message is never lost to `await createApp(...)`. Vite replacing\n * the module stops both. The `import.meta.hot` calls are written out literally because Vite\n * finds them by reading the source, not by running it. In a production build the export is an empty\n * function, the same shape as `acceptHotReload` from `virtual:ignifx/scripts`, so the game's\n * `main.ts` builds either way and ships no editor code.\n *\n * @param options - The editor origin, the reporting options, and whether to emit the development module.\n * @returns The ES module source.\n *\n * @beta\n */\nexport function playControlsModuleSource(options: PlayControlsModuleOptions): string {\n if (!options.hot) {\n return [`export function ${EDITOR_PLAY_CONTROLS_EXPORT}() {`, \" return () => {};\", \"}\", \"\"].join(\"\\n\");\n }\n return [\n `import { listenForEditorPlayControls } from ${JSON.stringify(HOST_PACKAGE)};`,\n \"\",\n \"// Listens now, before main.ts awaits createApp, so the editor's first port is kept.\",\n \"const connector = listenForEditorPlayControls({\",\n ` editorOrigin: ${JSON.stringify(options.editorOrigin)},`,\n ...reportingLines(options.engineVersion, options.heartbeatIntervalMs),\n \"});\",\n \"if (import.meta.hot) {\",\n \" import.meta.hot.dispose(() => {\",\n \" connector.dispose();\",\n \" });\",\n \"}\",\n \"\",\n `export function ${EDITOR_PLAY_CONTROLS_EXPORT}(app) {`,\n \" const controls = connector.attach(app);\",\n \" return () => {\",\n \" controls.dispose();\",\n \" };\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n}\n","/**\n * The editor host's Vite plugin: the scene view's page on the project's own dev server, and\n * `virtual:ignifx/editor` for the play view (`docs/architecture/17-editor-host.md` §3).\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join, resolve } from \"node:path\";\nimport { EditorHostErrorCode, isEditorOrigin } from \"../error-codes.js\";\nimport { EditorHostPluginError } from \"./errors.js\";\nimport {\n DEFAULT_EXTENSIONS_MODULE,\n EDITOR_ENTRY_MODULE_ID,\n EDITOR_MODULE_ID,\n EDITOR_PAGE_PATH,\n editorEntryModuleSource,\n editorPageHtml,\n normalizeExtensionsModule,\n playControlsModuleSource,\n RESOLVED_EDITOR_ENTRY_MODULE_ID,\n RESOLVED_EDITOR_MODULE_ID,\n} from \"./modules.js\";\nimport type { ConfigEnv, Plugin, ViteDevServer } from \"vite\";\n\n/**\n * Options accepted by {@link editorHostPlugin}.\n *\n * @beta\n */\nexport interface EditorHostPluginOptions {\n /**\n * The origin the editor is served from, for example `\"ignifx://app\"` when packaged or\n * `\"http://localhost:5173\"` while the editor itself runs from a dev server. Only this origin may\n * frame either view in `vite dev`, and only it can hand either view a port.\n */\n readonly editorOrigin: string;\n /**\n * The project's extensions module, relative to the Vite root. It exports `extensions()`, which\n * returns the list `main.ts` passes to `createApp`. When the file does not exist the scene view\n * runs with no extensions. Defaults to `\"/src/extensions.ts\"`.\n */\n readonly extensions?: string;\n /** A scene address the scene view loads before it starts. Defaults to none. */\n readonly bootScene?: string | null;\n /** Milliseconds between heartbeats in both views. Defaults to the host's `1000`. */\n readonly heartbeatIntervalMs?: number;\n}\n\n/** The plugin names, as they appear in Vite's logs. */\nconst PAGE_PLUGIN_NAME = \"ignifx-editor-host\";\nconst PLAY_PLUGIN_NAME = \"ignifx-editor-host:play-controls\";\n\n/** What Vite crawls for dependencies when `optimizeDeps.entries` is not set. */\nconst DEFAULT_OPTIMIZE_ENTRIES = \"**/*.html\";\n\n/**\n * Reads the version of the project's own `@ignifx/core`.\n *\n * @param root - The Vite root.\n * @returns The version, or `null` when the project does not resolve `@ignifx/core`.\n *\n * @beta\n */\nexport function readProjectEngineVersion(root: string): string | null {\n try {\n const requireFromProject = createRequire(join(root, \"package.json\"));\n const manifest: unknown = JSON.parse(readFileSync(requireFromProject.resolve(\"@ignifx/core/package.json\"), \"utf8\"));\n if (typeof manifest === \"object\" && manifest !== null && \"version\" in manifest) {\n return typeof manifest.version === \"string\" ? manifest.version : null;\n }\n return null;\n } catch {\n // An unresolvable core is reported by the host as core's own `VERSION`, not as a failure here.\n return null;\n }\n}\n\n/**\n * Checks the options and applies their defaults.\n *\n * @param options - The options as given.\n * @returns The extensions module path and the heartbeat period.\n * @throws EditorHostPluginError `IGX-1801` for a malformed origin, `IGX-1803` for a bad option.\n */\nfunction checkOptions(options: EditorHostPluginOptions): { extensions: string; heartbeatIntervalMs: number | null } {\n if (!isEditorOrigin(options.editorOrigin)) {\n throw new EditorHostPluginError(\n EditorHostErrorCode.invalidEditorOrigin,\n `editorOrigin \"${options.editorOrigin}\" is not an origin; pass one such as \"ignifx://app\" or \"http://localhost:5173\".`,\n );\n }\n const interval = options.heartbeatIntervalMs;\n if (interval !== undefined && (!Number.isFinite(interval) || interval <= 0)) {\n throw new EditorHostPluginError(\n EditorHostErrorCode.invalidOption,\n `heartbeatIntervalMs must be a positive number of milliseconds; got ${String(interval)}.`,\n );\n }\n return {\n extensions: normalizeExtensionsModule(options.extensions ?? DEFAULT_EXTENSIONS_MODULE),\n heartbeatIntervalMs: interval ?? null,\n };\n}\n\n/**\n * The editor host's Vite plugin.\n *\n * @remarks\n * It is two plugins, because the two halves run under different commands:\n *\n * - `ignifx-editor-host` (`vite dev` only) serves the scene view at `/__ignifx_editor__/` with\n * `Content-Security-Policy: frame-ancestors <editorOrigin>`, and adds the same header to every\n * page a browser navigates to, so the game's own `index.html` (the play view) can be framed by the\n * editor and by nothing else. A `Content-Security-Policy` in `server.headers` replaces it. The page's module imports the host,\n * `virtual:ignifx/scripts`, `virtual:ignifx/manifest` and the project's extensions module from\n * the project's own graph, and calls `startEditorHost`. It adds the extensions module to\n * `optimizeDeps.entries` (keeping Vite's default crawl) and keeps `@ignifx/editor-host` out of\n * pre-bundling, so the host reaches the same pre-bundled `@ignifx/core` as the game.\n * - `ignifx-editor-host:play-controls` (every command) serves `virtual:ignifx/editor`: the play\n * controls under `vite dev`, an empty function under `vite build`.\n *\n * List it after `ignifx()` from `@ignifx/vite-plugin`, which serves the two modules the scene\n * view imports.\n *\n * @param options - The editor's origin and the scene view's options.\n * @returns The plugins, to be listed in `vite.config.ts`.\n * @throws EditorHostPluginError `IGX-1801` for a malformed `editorOrigin`, `IGX-1803` for a bad\n * `extensions` path or `heartbeatIntervalMs`.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { ignifx } from \"@ignifx/vite-plugin\";\n * import { editorHostPlugin } from \"@ignifx/editor-host/vite\";\n * import { defineConfig } from \"vite\";\n *\n * export default defineConfig({\n * plugins: [ignifx(), editorHostPlugin({ editorOrigin: \"ignifx://app\" })],\n * });\n * ```\n *\n * @beta\n */\nexport function editorHostPlugin(options: EditorHostPluginOptions): Plugin[] {\n const { extensions, heartbeatIntervalMs } = checkOptions(options);\n const { editorOrigin } = options;\n let root = process.cwd();\n let base = \"/\";\n let command: ConfigEnv[\"command\"] = \"serve\";\n let engineVersion: string | null = null;\n\n const extensionsFile = (): string => resolve(root, `.${extensions}`);\n // Only the editor may put either view in a frame; any other page that tries is blocked. A tab the\n // developer opens on the dev server is not a frame, so the policy leaves it alone.\n const framePolicy = `frame-ancestors ${editorOrigin}`;\n\n /**\n * Sends the frame policy with every page a browser navigates to, the game's `index.html` (the\n * play view) included. Navigations and frames ask for `text/html`; module and asset requests do\n * not, and a policy on them would do nothing anyway.\n *\n * @param server - The dev server.\n */\n const installPlayViewPolicy = (server: ViteDevServer): void => {\n server.middlewares.use((request, response, next) => {\n const isRead = request.method === \"GET\" || request.method === \"HEAD\";\n if (isRead && (request.headers.accept ?? \"\").includes(\"text/html\")) {\n response.setHeader(\"Content-Security-Policy\", framePolicy);\n }\n next();\n });\n };\n\n /**\n * Serves the scene view's page and redirects the path without its trailing slash.\n *\n * @param server - The dev server.\n */\n const installPage = (server: ViteDevServer): void => {\n const pagePath = `${base.endsWith(\"/\") ? base.slice(0, -1) : base}${EDITOR_PAGE_PATH}`;\n server.middlewares.use((request, response, next) => {\n const url = request.url ?? \"\";\n const path = url.split(\"?\")[0] ?? \"\";\n if (path === pagePath.slice(0, -1)) {\n response.statusCode = 302;\n response.setHeader(\"Location\", `${pagePath}${url.slice(path.length)}`);\n response.end();\n return;\n }\n if (path !== pagePath && path !== `${pagePath}index.html`) {\n next();\n return;\n }\n server.transformIndexHtml(EDITOR_PAGE_PATH, editorPageHtml(), request.originalUrl).then(\n (html) => {\n response.statusCode = 200;\n response.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n response.setHeader(\"Cache-Control\", \"no-store\");\n response.setHeader(\"Content-Security-Policy\", framePolicy);\n response.end(html);\n },\n (error: unknown) => {\n next(error);\n },\n );\n });\n };\n\n const page: Plugin = {\n name: PAGE_PLUGIN_NAME,\n // A production build must never contain the scene view.\n apply: \"serve\",\n\n config(userConfig) {\n const projectRoot = resolve(process.cwd(), userConfig.root ?? \".\");\n const scanExtensions = existsSync(resolve(projectRoot, `.${extensions}`));\n // Vite concatenates arrays when it merges this into the user's config, and setting `entries`\n // at all replaces its default crawl of every HTML file, so the default is restated only when\n // the user set nothing.\n const entries =\n userConfig.optimizeDeps?.entries === undefined\n ? [DEFAULT_OPTIMIZE_ENTRIES, extensions.slice(1)]\n : [extensions.slice(1)];\n return {\n optimizeDeps: {\n ...(scanExtensions ? { entries } : {}),\n // Served as it is, its `@ignifx/core` import resolves to the game's own pre-bundled core.\n exclude: [\"@ignifx/editor-host\"],\n },\n };\n },\n\n configResolved(resolvedConfig) {\n root = resolvedConfig.root;\n base = resolvedConfig.base;\n engineVersion = readProjectEngineVersion(root);\n },\n\n configureServer(server) {\n // Registered directly rather than returned as a post hook, so they run before Vite's own HTML\n // fallback and index middleware.\n installPlayViewPolicy(server);\n installPage(server);\n },\n\n resolveId(id) {\n return id === EDITOR_ENTRY_MODULE_ID ? RESOLVED_EDITOR_ENTRY_MODULE_ID : null;\n },\n\n load(id) {\n if (id !== RESOLVED_EDITOR_ENTRY_MODULE_ID) {\n return null;\n }\n return editorEntryModuleSource({\n editorOrigin,\n extensionsModule: existsSync(extensionsFile()) ? extensions : null,\n bootScene: options.bootScene ?? null,\n engineVersion,\n heartbeatIntervalMs,\n });\n },\n };\n\n const play: Plugin = {\n name: PLAY_PLUGIN_NAME,\n\n configResolved(resolvedConfig) {\n root = resolvedConfig.root;\n command = resolvedConfig.command;\n engineVersion = readProjectEngineVersion(root);\n },\n\n resolveId(id) {\n return id === EDITOR_MODULE_ID ? RESOLVED_EDITOR_MODULE_ID : null;\n },\n\n load(id) {\n if (id !== RESOLVED_EDITOR_MODULE_ID) {\n return null;\n }\n return playControlsModuleSource({ editorOrigin, engineVersion, heartbeatIntervalMs, hot: command === \"serve\" });\n },\n };\n\n return [page, play];\n}\n"],"mappings":";;;;;;;;;;;;AAiBA,IAAa,wBAAb,cAA2C,MAAM;;CAE/C;;;;;;;CAQA,YAAY,MAA2B,SAAiB;EACtD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;ACbA,MAAa,mBAAmB;;;;;;;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,eAAe,CAAC,IAAI,aAAa;IAC9D,WAAW,QAAQ,aAAa;IAChC;IACA;GACF,CAAC;EACH;CAwBS,GAAG;EApBZ,MAAM;EAEN,eAAe,gBAAgB;GAC7B,OAAO,eAAe;GACtB,UAAU,eAAe;GACzB,gBAAgB,yBAAyB,IAAI;EAC/C;EAEA,UAAU,IAAI;GACZ,OAAO,OAAA,0BAA0B,4BAA4B;EAC/D;EAEA,KAAK,IAAI;GACP,IAAI,OAAO,2BACT,OAAO;GAET,OAAO,yBAAyB;IAAE;IAAc;IAAe;IAAqB,KAAK,YAAY;GAAQ,CAAC;EAChH;CAGe,CAAC;AACpB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,86 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ignifx/editor-host",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.10.0",
|
|
4
|
+
"description": "ignifx editor host: runs a project's own engine inside the ignifx editor's scene view and play view, over a versioned protocol.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"ignifx"
|
|
7
|
+
],
|
|
8
|
+
"homepage": "https://ignifx.com",
|
|
9
|
+
"license": "Apache-2.0",
|
|
10
|
+
"author": "Astrum Forge Studios",
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/astrum-forge/ignifx.git",
|
|
14
|
+
"directory": "packages/editor-host"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"skills",
|
|
19
|
+
"client.d.ts"
|
|
20
|
+
],
|
|
21
|
+
"type": "module",
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./vite": {
|
|
29
|
+
"types": "./dist/vite.d.ts",
|
|
30
|
+
"import": "./dist/vite.js"
|
|
31
|
+
},
|
|
32
|
+
"./client": {
|
|
33
|
+
"types": "./client.d.ts"
|
|
34
|
+
},
|
|
35
|
+
"./package.json": "./package.json"
|
|
36
|
+
},
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public",
|
|
39
|
+
"provenance": false
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@arethetypeswrong/cli": "^0.18.5",
|
|
43
|
+
"@babylonjs/lite": "1.34.0",
|
|
44
|
+
"@microsoft/api-extractor": "^7.59.0",
|
|
45
|
+
"@types/node": "^24.13.3",
|
|
46
|
+
"@types/webxr": "^0.5.0",
|
|
47
|
+
"@webgpu/types": "^0.1.72",
|
|
48
|
+
"publint": "^0.3.24",
|
|
49
|
+
"tsdown": "^0.23.0",
|
|
50
|
+
"typedoc": "^0.28.20",
|
|
51
|
+
"typedoc-plugin-markdown": "^4.13.0",
|
|
52
|
+
"typescript-native": "npm:typescript@7.0.2",
|
|
53
|
+
"vite": "^8.2.2",
|
|
54
|
+
"vitest": "^5.0.0",
|
|
55
|
+
"@ignifx/2d": "0.10.0",
|
|
56
|
+
"@ignifx/core": "0.10.0",
|
|
57
|
+
"@ignifx/vite-plugin": "0.10.0"
|
|
58
|
+
},
|
|
59
|
+
"peerDependencies": {
|
|
60
|
+
"@babylonjs/lite": "1.34.0",
|
|
61
|
+
"vite": "^8.2.2",
|
|
62
|
+
"@ignifx/core": "0.10.0",
|
|
63
|
+
"@ignifx/vite-plugin": "0.10.0"
|
|
64
|
+
},
|
|
65
|
+
"peerDependenciesMeta": {
|
|
66
|
+
"@ignifx/vite-plugin": {
|
|
67
|
+
"optional": true
|
|
68
|
+
},
|
|
69
|
+
"vite": {
|
|
70
|
+
"optional": true
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
"ignifx": {
|
|
74
|
+
"engine": ">=0.0.0 <1.0.0",
|
|
75
|
+
"skill": "./skills/editor-host/SKILL.md"
|
|
76
|
+
},
|
|
77
|
+
"scripts": {
|
|
78
|
+
"build": "tsdown",
|
|
79
|
+
"typecheck": "tsc --build tsconfig.json tsconfig.test.json",
|
|
80
|
+
"test": "vitest run --project node --project node-isolated --root ../.. packages/editor-host",
|
|
81
|
+
"api-report": "api-extractor run --verbose && api-extractor run --verbose -c api-extractor.vite.json",
|
|
82
|
+
"docs:api": "typedoc && typedoc --options typedoc.vite.json",
|
|
83
|
+
"api-report:update": "api-extractor run --local --verbose && api-extractor run --local --verbose -c api-extractor.vite.json",
|
|
84
|
+
"pack-check": "publint && attw --pack . --profile esm-only"
|
|
85
|
+
}
|
|
6
86
|
}
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: editor-host
|
|
3
|
+
description: Connects an ignifx project to the ignifx editor with @ignifx/editor-host: the Vite plugin that serves the editor's scene view from the project's own dev server, the virtual:ignifx/editor play controls a game's main.ts hands its app to (play, pause, step, stop, playState, playStateChanged, playStats), and the host half of the editor protocol 0.3 over a MessagePort (hello/ready, heartbeat, and the scene document methods openScene, applyOps, readBack, select, pick, frame, setGizmo, setViewMode, screenshot, getSchemas, describeSettings), including the 2D view mode (an editor Camera2D and app.twoD.pickAt picking). Use when wiring a project or template for the editor, when the user mentions @ignifx/editor-host, editorHostPlugin, attachEditorPlayControls, virtual:ignifx/editor, startEditorHost or /__ignifx_editor__/, or when debugging why the editor cannot connect to a view or why the scene view disagrees with the editor's document.
|
|
4
|
+
license: Apache-2.0
|
|
5
|
+
metadata:
|
|
6
|
+
ignifx-version: "0.10.0"
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# @ignifx/editor-host
|
|
10
|
+
|
|
11
|
+
## What this is / when to use
|
|
12
|
+
|
|
13
|
+
`@ignifx/editor-host` is the part of the ignifx editor that lives **inside a project**. The editor
|
|
14
|
+
never bundles the engine: it starts the project's own Vite dev server and shows two pages from it in
|
|
15
|
+
frames. The **scene view** is `/__ignifx_editor__/`, a page this package's Vite plugin adds; the
|
|
16
|
+
**play view** is the game's own `index.html`. Both use the project's single copy of `@ignifx/core`,
|
|
17
|
+
so the editor always runs exactly the engine version and the scripts the project has.
|
|
18
|
+
|
|
19
|
+
Use it when a project should open in the editor. Game code never calls the host directly: the Vite
|
|
20
|
+
plugin generates the scene view's page, and `main.ts` adds one line for the play view. Do not ship it;
|
|
21
|
+
production builds contain none of it.
|
|
22
|
+
|
|
23
|
+
The package is on the engine's version line (install the same version as `@ignifx/core`), not the
|
|
24
|
+
editor's, even though its name starts with `editor-`.
|
|
25
|
+
|
|
26
|
+
## Environment
|
|
27
|
+
|
|
28
|
+
- Engine: ignifx `0.10.0`; this package targets `@ignifx/core` `>=0.0.0 <1.0.0`.
|
|
29
|
+
- Peers: `@ignifx/core` and `@babylonjs/lite` (the scene view's gizmos); for the `./vite` entry,
|
|
30
|
+
`@ignifx/vite-plugin` and `vite`.
|
|
31
|
+
- A development dependency of the project, at the same version as its `@ignifx/core`.
|
|
32
|
+
- Nothing happens at import time; the plugin's generated page module is what starts the host.
|
|
33
|
+
|
|
34
|
+
```ts ignore-check
|
|
35
|
+
// vite.config.ts — the editor passes its own origin when it starts the dev server.
|
|
36
|
+
import { ignifx } from "@ignifx/vite-plugin";
|
|
37
|
+
import { editorHostPlugin } from "@ignifx/editor-host/vite";
|
|
38
|
+
import { defineConfig } from "vite";
|
|
39
|
+
|
|
40
|
+
export default defineConfig({
|
|
41
|
+
plugins: [ignifx(), editorHostPlugin({ editorOrigin: process.env.IGNIFX_EDITOR_ORIGIN ?? "ignifx://app" })],
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
| Option | Default | Meaning |
|
|
46
|
+
| --------------------- | ---------------------- | --------------------------------------------------------------------------- |
|
|
47
|
+
| `editorOrigin` | required | The editor's origin; the only one that may frame the scene view or connect |
|
|
48
|
+
| `extensions` | `"/src/extensions.ts"` | Module exporting `extensions()`; the scene view uses `[]` when it is absent |
|
|
49
|
+
| `bootScene` | none | A scene address the scene view loads before it starts |
|
|
50
|
+
| `heartbeatIntervalMs` | `1000` | Milliseconds between `heartbeat` notifications in both views |
|
|
51
|
+
|
|
52
|
+
Add `/// <reference types="@ignifx/editor-host/client" />` beside `@ignifx/vite-plugin/client` so
|
|
53
|
+
`virtual:ignifx/editor` is typed.
|
|
54
|
+
|
|
55
|
+
## Mental model
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
editor window (ignifx://app)
|
|
59
|
+
├── <iframe> scene view http://127.0.0.1:<port>/__ignifx_editor__/
|
|
60
|
+
│ generated module → startEditorHost({ extensions(), scripts, settings, manifest })
|
|
61
|
+
│ owns its app, in edit mode; hostKind "scene"
|
|
62
|
+
│ world: the open document's scene + a persistent "editor" scene (camera, never saved)
|
|
63
|
+
└── <iframe> play view http://localhost:<port>/ (the game's own index.html)
|
|
64
|
+
main.ts → attachEditorPlayControls(app) (virtual:ignifx/editor; a no-op in builds)
|
|
65
|
+
the game owns its app; hostKind "play"
|
|
66
|
+
|
|
67
|
+
each view ◀── MessagePort ──▶ editor JSON-RPC 2.0, protocol 0.3
|
|
68
|
+
connect (window message, origin-checked) → hello → ready → ping/pong, heartbeat
|
|
69
|
+
scene view: schemasChanged → openScene → applyOps… / readBack / select / pick / frame / setGizmo / screenshot
|
|
70
|
+
/ setViewMode / getSchemas / describeSettings (on request only)
|
|
71
|
+
← sceneOpened, selectionChanged, transformDragging/Dragged, hotReloaded, assetReloaded,
|
|
72
|
+
hostError, log
|
|
73
|
+
play view: play / pause / step / stop / playState / playStats
|
|
74
|
+
← playStateChanged, log, hostError, hotReloaded (logRelay; kept from before hello)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The editor posts `{ type: "ignifx-editor/connect" }` with a fresh `MessagePort` to each view on every
|
|
78
|
+
`load`. A host takes a port only from `editorOrigin`, replaces its old port whenever a new one
|
|
79
|
+
arrives, answers `hello` with `ready` (engine version, protocol, capabilities, host kind), and then
|
|
80
|
+
sends a `heartbeat` notification every second so the editor notices a crashed view. The play view's
|
|
81
|
+
module listens as soon as it is evaluated and keeps the port until `attachEditorPlayControls(app)`
|
|
82
|
+
runs, so a port posted while `main.ts` awaits `createApp` is not lost. Under `vite dev` both views
|
|
83
|
+
carry `Content-Security-Policy: frame-ancestors <editorOrigin>`.
|
|
84
|
+
|
|
85
|
+
The editor owns the scene document; the scene view mirrors it. `openScene` sends the whole file
|
|
86
|
+
object (it may hold unsaved edits) and the host builds it with `world.loadSceneFile`, keeping the
|
|
87
|
+
file's uids. Every command the editor applies to its document goes to the host as `applyOps`, the
|
|
88
|
+
same ops; any failure means the mirror drifted, and the editor resends `openScene`. What the user
|
|
89
|
+
does in the view comes back as notifications (`selectionChanged`, `transformDragged`) that the
|
|
90
|
+
editor turns into commands. The host never edits the document. When a script's hot reload changes a
|
|
91
|
+
field's default, the host gives the field its new default wherever the document leaves it out, and
|
|
92
|
+
keeps the values and overrides the document sets (`hotReloadDefaults`), so the editor need not
|
|
93
|
+
reopen the scene.
|
|
94
|
+
|
|
95
|
+
## First app
|
|
96
|
+
|
|
97
|
+
A headless scene-view host and the editor's side of the handshake, in one Node program. An
|
|
98
|
+
`EventTarget` stands in for the frame's `window`.
|
|
99
|
+
|
|
100
|
+
```ts run
|
|
101
|
+
import { EDITOR_CONNECT_MESSAGE_TYPE, PROTOCOL_VERSION, startEditorHost } from "@ignifx/editor-host";
|
|
102
|
+
|
|
103
|
+
const frameWindow = new EventTarget();
|
|
104
|
+
const host = await startEditorHost({ editorOrigin: "ignifx://app", headless: true, messageTarget: frameWindow });
|
|
105
|
+
|
|
106
|
+
// The editor's side: a fresh channel, with one end posted to the view's window.
|
|
107
|
+
const channel = new MessageChannel();
|
|
108
|
+
frameWindow.dispatchEvent(
|
|
109
|
+
new MessageEvent("message", {
|
|
110
|
+
data: { type: EDITOR_CONNECT_MESSAGE_TYPE },
|
|
111
|
+
origin: "ignifx://app",
|
|
112
|
+
ports: [channel.port2],
|
|
113
|
+
}),
|
|
114
|
+
);
|
|
115
|
+
|
|
116
|
+
const ready = await new Promise<unknown>((resolve) => {
|
|
117
|
+
channel.port1.onmessage = (event: MessageEvent): void => {
|
|
118
|
+
resolve(event.data);
|
|
119
|
+
};
|
|
120
|
+
channel.port1.postMessage({
|
|
121
|
+
jsonrpc: "2.0",
|
|
122
|
+
id: 1,
|
|
123
|
+
method: "hello",
|
|
124
|
+
params: { editorVersion: "0.1.0", protocol: PROTOCOL_VERSION },
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
console.log(JSON.stringify(ready));
|
|
128
|
+
|
|
129
|
+
channel.port1.close();
|
|
130
|
+
host.dispose();
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## Core APIs
|
|
134
|
+
|
|
135
|
+
`skills/ignifx/references/api/editor-host.md` and `editor-host-vite.md` have the generated surface.
|
|
136
|
+
|
|
137
|
+
| Member | What it does |
|
|
138
|
+
| -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
|
|
139
|
+
| `editorHostPlugin(options)` (`/vite`) | The two Vite plugins: the scene view's page (dev only) and `virtual:ignifx/editor` |
|
|
140
|
+
| `attachEditorPlayControls(app)` | From `virtual:ignifx/editor`: hands the game's app to the editor; returns a detach |
|
|
141
|
+
| `startEditorHost(options)` | Starts the scene view's host and its edit-mode app; resolves to a disposable `EditorHost` |
|
|
142
|
+
| `listenForEditorPlayControls(options)` | What `virtual:ignifx/editor` calls in development: keeps the editor's port until `attach(app)` starts the controls on it |
|
|
143
|
+
| `startEditorPlayControls(app, options)` | The play controls on their own, listening from the call |
|
|
144
|
+
| `EDITOR_CONNECT_MESSAGE_TYPE`, `isEditorConnectMessage` | The window message that carries the port, and its check |
|
|
145
|
+
| `PROTOCOL_VERSION`, `RpcErrorCode`, `isRpcMessage`, `isPlayState` | The protocol 0.3 values and checks, mirrored from `@ignifx/editor-protocol`; before 1.0 the major and minor must both match |
|
|
146
|
+
| `SceneMethod`, `SceneNotification`, `SceneOp`, `isApplyOpsParams`, … | The scene document methods, notifications, the thirteen ops, and their guards |
|
|
147
|
+
| `EditorHost.editorScene` | The persistent `editor` scene instance holding the host's own objects |
|
|
148
|
+
| `EditorHost.assetChanged(change)` | Reloads an asset changed on disk in place and sends `assetReloaded`; the generated page calls it on `ignifx:asset-changed` |
|
|
149
|
+
| `PlayMethod`, `PlayState` | `play`, `pause`, `step`, `stop`, and what each answers; `playState` reads the state without changing it |
|
|
150
|
+
| `PlayNotification`, `PlayPhase`, `isPlayStateReport` | `playStateChanged` and `playState`'s `{ state: "playing" \| "paused" \| "stopped", frameCount, time }` |
|
|
151
|
+
| `PlayStats`, `isPlayStats` | `playStats`'s `{ fps, frameTimeMs, entityCount, frameCount }`: the newest second of `app.diagnostics` frames, the world's entities |
|
|
152
|
+
| `HostCapability.hotReloadDefaults` | The scene view gives fields the document leaves out their new default after a script's hot reload |
|
|
153
|
+
| `HostCapability.logRelay`, `isAppErrorData`, `LoggedError` | Both views relay `log` (with the first `Error` a line carries), `hostError` (entity, component, phase, stack) and `hotReloaded` |
|
|
154
|
+
| `EditorHostErrorCode` | `IGX-1801` bad origin, `IGX-1802` no window, `IGX-1803` bad option |
|
|
155
|
+
|
|
156
|
+
## Recipes
|
|
157
|
+
|
|
158
|
+
### Hand the game to the play controls
|
|
159
|
+
|
|
160
|
+
```ts ignore-check
|
|
161
|
+
// src/main.ts, after createApp and registerComponents.
|
|
162
|
+
import { attachEditorPlayControls } from "virtual:ignifx/editor";
|
|
163
|
+
import { acceptHotReload } from "virtual:ignifx/scripts";
|
|
164
|
+
|
|
165
|
+
acceptHotReload(app);
|
|
166
|
+
attachEditorPlayControls(app);
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
In `vite build` the import is an empty function, so the same `main.ts` ships with no editor code.
|
|
170
|
+
|
|
171
|
+
### Share the extension list with the scene view
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
// src/extensions.ts — main.ts passes `extensions: extensions()` to createApp too.
|
|
175
|
+
import type { Extension } from "@ignifx/core";
|
|
176
|
+
|
|
177
|
+
export function extensions(): Extension[] {
|
|
178
|
+
return [];
|
|
179
|
+
}
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
### Drive the play view
|
|
183
|
+
|
|
184
|
+
```ts run
|
|
185
|
+
import { createApp } from "@ignifx/core";
|
|
186
|
+
import { EDITOR_CONNECT_MESSAGE_TYPE, PROTOCOL_VERSION, startEditorPlayControls } from "@ignifx/editor-host";
|
|
187
|
+
|
|
188
|
+
const app = await createApp({ headless: true });
|
|
189
|
+
const pageWindow = new EventTarget();
|
|
190
|
+
const controls = startEditorPlayControls(app, { editorOrigin: "ignifx://app", messageTarget: pageWindow });
|
|
191
|
+
|
|
192
|
+
const channel = new MessageChannel();
|
|
193
|
+
pageWindow.dispatchEvent(
|
|
194
|
+
new MessageEvent("message", {
|
|
195
|
+
data: { type: EDITOR_CONNECT_MESSAGE_TYPE },
|
|
196
|
+
origin: "ignifx://app",
|
|
197
|
+
ports: [channel.port2],
|
|
198
|
+
}),
|
|
199
|
+
);
|
|
200
|
+
const answers: unknown[] = [];
|
|
201
|
+
const done = new Promise<void>((resolve) => {
|
|
202
|
+
channel.port1.onmessage = (event: MessageEvent): void => {
|
|
203
|
+
// Answers carry their request's id; `heartbeat` and `playStateChanged` do not.
|
|
204
|
+
if (typeof event.data === "object" && event.data !== null && "id" in event.data) {
|
|
205
|
+
answers.push(event.data);
|
|
206
|
+
}
|
|
207
|
+
if (answers.length === 4) {
|
|
208
|
+
resolve();
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
});
|
|
212
|
+
const send = (id: number, method: string, params?: object): void => {
|
|
213
|
+
// JSON-RPC allows `params` to be absent, but not `undefined`.
|
|
214
|
+
channel.port1.postMessage({ jsonrpc: "2.0", id, method, ...(params === undefined ? {} : { params }) });
|
|
215
|
+
};
|
|
216
|
+
send(1, "hello", { editorVersion: "0.1.0", protocol: PROTOCOL_VERSION });
|
|
217
|
+
send(2, "play");
|
|
218
|
+
send(3, "step", { deltaSeconds: 1 / 60 });
|
|
219
|
+
send(4, "playState");
|
|
220
|
+
await done;
|
|
221
|
+
console.log(JSON.stringify(answers.at(-1)));
|
|
222
|
+
|
|
223
|
+
channel.port1.close();
|
|
224
|
+
controls.dispose();
|
|
225
|
+
app.dispose();
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
### Open a scene document in the scene view
|
|
229
|
+
|
|
230
|
+
```ts run
|
|
231
|
+
import { EDITOR_CONNECT_MESSAGE_TYPE, PROTOCOL_VERSION, startEditorHost } from "@ignifx/editor-host";
|
|
232
|
+
|
|
233
|
+
const frameWindow = new EventTarget();
|
|
234
|
+
const host = await startEditorHost({ editorOrigin: "ignifx://app", headless: true, messageTarget: frameWindow });
|
|
235
|
+
const channel = new MessageChannel();
|
|
236
|
+
frameWindow.dispatchEvent(
|
|
237
|
+
new MessageEvent("message", {
|
|
238
|
+
data: { type: EDITOR_CONNECT_MESSAGE_TYPE },
|
|
239
|
+
origin: "ignifx://app",
|
|
240
|
+
ports: [channel.port2],
|
|
241
|
+
}),
|
|
242
|
+
);
|
|
243
|
+
|
|
244
|
+
// Answers by id; notifications (heartbeat, schemasChanged, sceneOpened, log) are skipped here.
|
|
245
|
+
const waiting = new Map<number, (result: unknown) => void>();
|
|
246
|
+
channel.port1.onmessage = (event: MessageEvent<{ id?: number; result?: unknown; error?: unknown }>): void => {
|
|
247
|
+
const { id } = event.data;
|
|
248
|
+
if (id !== undefined) {
|
|
249
|
+
waiting.get(id)?.(event.data.result ?? event.data.error);
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
let nextId = 0;
|
|
253
|
+
const request = async (method: string, params: unknown): Promise<unknown> => {
|
|
254
|
+
nextId += 1;
|
|
255
|
+
const id = nextId;
|
|
256
|
+
const answer = new Promise<unknown>((resolve) => waiting.set(id, resolve));
|
|
257
|
+
channel.port1.postMessage({ jsonrpc: "2.0", id, method, params });
|
|
258
|
+
return answer;
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
await request("hello", { editorVersion: "0.1.0", protocol: PROTOCOL_VERSION });
|
|
262
|
+
const transform = { position: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] };
|
|
263
|
+
const file = {
|
|
264
|
+
format: "ignifx.scene",
|
|
265
|
+
formatVersion: 1,
|
|
266
|
+
name: "level01",
|
|
267
|
+
entities: [{ uid: "01J9Z6M7E5S3A0V2Q4R8T1Y6WX", name: "Player", parent: null, transform }],
|
|
268
|
+
};
|
|
269
|
+
console.log(JSON.stringify(await request("openScene", { file, address: null })));
|
|
270
|
+
await request("applyOps", {
|
|
271
|
+
ops: [{ op: "setEntityField", entity: "01J9Z6M7E5S3A0V2Q4R8T1Y6WX", field: "name", value: "Hero" }],
|
|
272
|
+
commandName: "Rename Player",
|
|
273
|
+
commandId: "cmd-1",
|
|
274
|
+
});
|
|
275
|
+
console.log(JSON.stringify(await request("readBack", {})));
|
|
276
|
+
|
|
277
|
+
channel.port1.close();
|
|
278
|
+
host.dispose();
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
## File formats
|
|
282
|
+
|
|
283
|
+
None of its own. The scene view builds the editor's scene document (`ignifx.scene`) from the file
|
|
284
|
+
object `openScene` sends, through `world.loadSceneFile`; `readBack` answers with the records
|
|
285
|
+
`serializeScene` writes.
|
|
286
|
+
|
|
287
|
+
## Gotchas
|
|
288
|
+
|
|
289
|
+
- **List `editorHostPlugin` for `vite build` too** when `main.ts` imports `virtual:ignifx/editor`:
|
|
290
|
+
the build half is what turns it into an empty function. Without the plugin the import does not
|
|
291
|
+
resolve.
|
|
292
|
+
- **`editorOrigin` is exact.** It must equal `event.origin` as the browser reports it, with no path or
|
|
293
|
+
trailing slash: `ignifx://app` for the packaged editor, `http://localhost:<port>` for the editor's
|
|
294
|
+
own dev server. A mismatch is silent by design: the host just never connects.
|
|
295
|
+
- **Every view reload needs a new port.** A transferred `MessagePort` cannot be posted twice; the
|
|
296
|
+
editor makes a fresh `MessageChannel` on each `load`, and the host closes the previous port.
|
|
297
|
+
- **The scene view runs in edit mode** (`createApp({ editMode: true })`, ADR-0028): a script gets no
|
|
298
|
+
callback unless its class sets `static runInEditMode = true`, and physics does not step. Pass
|
|
299
|
+
`editMode: false` to `startEditorHost` to run it as a second copy of the game. The play view is the
|
|
300
|
+
game's own app and is never in edit mode.
|
|
301
|
+
- **The engine version is read from the project.** `VERSION` from `@ignifx/core` is `"0.0.0"` when
|
|
302
|
+
core runs from source rather than its build, so the plugin reads `@ignifx/core/package.json` and
|
|
303
|
+
passes `engineVersion`; the host prefers a stamped `VERSION`.
|
|
304
|
+
- **Script edits reload both views** while `main.ts` imports `src/scripts/**` statically: Vite's one
|
|
305
|
+
module graph sends a full reload to every page when an update reaches a module that does not
|
|
306
|
+
accept it.
|
|
307
|
+
- **Scene methods answer `notReady` until the app has started.** The host answers `hello` at once;
|
|
308
|
+
its first `schemasChanged` is the cue that `openScene` and the rest are accepted. `applyOps`,
|
|
309
|
+
`readBack` and `frame` answer `noScene` while no scene is open.
|
|
310
|
+
- **The scene view keeps the project's `rendering.msaaSamples`.** The gizmos and the outline draw in
|
|
311
|
+
core's render overlay (`app.renderer.openOverlay()`), which works at every MSAA setting.
|
|
312
|
+
- **A headless host lists only `heartbeat`.** Without a canvas there are no gizmos, no `screenshot`,
|
|
313
|
+
and every `pick` misses without a `ray`; `setGizmo` and `screenshot` then answer `methodNotFound`. In headless
|
|
314
|
+
tests, asset loads after `start()` settle only when something calls `app.step()`.
|
|
315
|
+
- **A `pick` carries the camera ray, hit or miss.** On a canvas the answer adds
|
|
316
|
+
`ray: { origin, direction }` (world space, from the editor camera's `screenToRay` at the converted
|
|
317
|
+
backing pixel) and, when the ray crosses `z = 0` ahead of the camera, `plane: [x, y, 0]`. A 3D
|
|
318
|
+
editor drops an asset where `ray` meets `y = 0`; a 2D one uses `plane`.
|
|
319
|
+
- **The 2D view mode needs a canvas, not a dependency.** On a canvas the host lists `viewMode2d` and
|
|
320
|
+
`pick2d`. `openScene` and `sceneOpened` report `viewMode`: `"2d"` for `twoD.mode: "sprite"` or a
|
|
321
|
+
scene whose cameras are all `Camera2D`. `setViewMode { mode: "2d" }` enables the host's own
|
|
322
|
+
`Camera2D` (priority 1 000 000) and makes the 3D editor camera orthographic over the same
|
|
323
|
+
rectangle; the level's `Camera2D` is never changed. In 2D mode `frame` fits sprite quads and
|
|
324
|
+
tilemaps, and `pick` and clicks use `app.twoD.pickAt` (unpickable sprites included): a hit's
|
|
325
|
+
`point` is on `z = 0` and its `distance` is `null`. The host finds `app.twoD` and the 2D classes
|
|
326
|
+
by name, so a project without `@ignifx/2d` still gets an orthographic 2D view of its meshes.
|
|
327
|
+
- **Settings over the protocol.** `describeSettings` answers `{ sections, values }`: core's
|
|
328
|
+
`describeSettings(app)` with each section's `settingsJsonSchema` entry as `propsSchema`, and the
|
|
329
|
+
values the app resolved, in the settings form (`{ x, y, z }`, `{ r, g, b, a }`). No notification
|
|
330
|
+
announces settings; ask again after the project's settings change.
|
|
331
|
+
- **A changed asset reloads in place, not the view.** The scene view's page hands every
|
|
332
|
+
`ignifx:asset-changed` event to `host.assetChanged`, which calls `app.assets.reload(address)` for an
|
|
333
|
+
asset the app has loaded, of type `scene` (a scene or prefab), `model`, `mesh`, `material`,
|
|
334
|
+
`spriteatlas` or `shader`. A changed prefab rebuilds the document's instances of it, directly or
|
|
335
|
+
through another prefab, with their uids, transforms, overrides and document children; `readBack`
|
|
336
|
+
then writes the new prefab's hash. The host sends `assetReloaded { address, type, entities }`
|
|
337
|
+
(the rebuilt instance roots) once the new value is in. A texture, a removed file and the open
|
|
338
|
+
document's own file are left alone and send nothing.
|
|
339
|
+
- **Document uids only.** Members of an instanced prefab and the editor's own entities never appear
|
|
340
|
+
in a selection, a pick or `readBack`; a pick on a prefab member resolves to its instance root.
|
|
341
|
+
|
|
342
|
+
## Deprecated (current window)
|
|
343
|
+
|
|
344
|
+
None (pre-1.0: no deprecation window; breaking changes are listed in the changelog).
|
|
345
|
+
|
|
346
|
+
## Where to look next
|
|
347
|
+
|
|
348
|
+
`docs/architecture/17-editor-host.md` for the design, the protocol and the security rules ·
|
|
349
|
+
`packages/editor-host/api/editor-host.api.md` and `editor-host-vite.api.md` for the exact surface ·
|
|
350
|
+
`skills/ignifx/SKILL.md` for the engine.
|
package/README.md
DELETED