@forgeax/engine-host 0.1.28 → 0.1.29
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/README.md +9 -0
- package/dist/backend.d.ts +7 -1
- package/dist/backend.d.ts.map +1 -1
- package/dist/backend.mjs +20 -2
- package/dist/backend.mjs.map +1 -1
- package/dist/frontend.mjs.map +1 -1
- package/dist/index.mjs +23 -3
- package/dist/index.mjs.map +1 -1
- package/dist/protocol.d.ts +2 -0
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.mjs.map +1 -1
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.mjs +3 -1
- package/dist/transport.mjs.map +1 -1
- package/package.json +2 -2
- package/src/__tests__/host.test.ts +109 -0
- package/src/backend.ts +29 -3
- package/src/protocol.ts +6 -1
- package/src/transport.ts +2 -0
package/dist/frontend.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/protocol.ts","../src/startup.ts","../src/transport.ts","../src/frontend.ts"],"names":["Context","report","host","activeLoader"],"mappings":";;;;;;AAoBO,IAAM,4BAAA,GAA+B,CAAA;AA4GrC,IAAM,iBAAA,GAAN,cAEG,KAAA,CAAM;AAAA,EACL,IAAA;AAAA,EACA,QAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EAET,WAAA,CAAY,IAAA,EAAS,QAAA,EAAkB,IAAA,EAAc,MAAA,EAA0C;AAC7F,IAAA,KAAA,CAAM,CAAA,EAAG,IAAI,CAAA,EAAA,EAAK,QAAQ,CAAA,CAAE,CAAA;AAC5B,IAAA,IAAA,CAAK,IAAA,GAAO,mBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AACF;AAOO,S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AAY,MAAM,oBAAA,CAAqB,IAAA,CAAK,OAAA,EAAS,SAAS,KAAK,CAAA;AACzE,MAAA,MAAA,GAAS,SAAA,CAAU,MAAA;AACnB,MAAA,SAAA,CAAU,SAAS,CAAA;AAAA,IACrB;AACA,IAAA,MAAM,UAAU,oBAAA,CAAqB,OAAA,CAAQ,KAAA,CAAM,OAAA,EAAS,OAAO,KAAK,CAAA;AACxE,IAAA,MAAM,MAAA,CAAO,IAAA,CAAK,MAAA,CAAO,OAAO,CAAA;AAChC,IAAA,MAAM,OAAO,KAAA,EAAM;AACnB,IAAA,MAAM,aAAA,GAAgB,UAAU,MAAM,CAAA;AACtC,IAAA,WAAA,CAAY,aAAa,CAAA;AACzB,IAAA,MAAA,EAAO;AACP,IAAA,MAAM,MAAA,CAAO,EAAE,KAAA,EAAO,QAAA,EAAU,QAAA,EAAU,QAAQ,KAAA,CAAM,QAAA,EAAU,OAAA,EAAS,aAAA,EAAe,CAAA;AAAA,EAC5F,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,KAAA,YAAiB,iBAAA,IAAqB,KAAA,CAAM,IAAA,KAAS,+BAAA,EAAiC;AAIxF,MAAA,MAAM,KAAA;AAAA,IACR;AACA,IAAA,MAAMC,gBAAe,SAAA,EAAU;AAC/B,IAAA,MAAM,aAAA,GAAgBA,aAAAA,KAAiB,MAAA,GAAY,MAAA,GAAY,UAAUA,aAAY,CAAA;AACrF,IAAA,MAAM,MAAA,CAAO;AAAA,MACX,KAAA,EAAO,QAAA;AAAA,MACP,UAAU,IAAA,CAAK,QAAA;AAAA,MACf,GAAI,aAAA,KAAkB,MAAA,GAAY,EAAC,GAAI,EAAE,SAAS,aAAA,EAAc;AAAA,MAChE;AAAA,KACD,CAAA;AACD,IAAA,MAAM,KAAA;AAAA,EACR;AACF","file":"frontend.mjs","sourcesContent":["import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader';\nimport type {\n GamePluginEntry,\n PluginCatalog,\n PluginCatalogRecord,\n PluginRealm,\n} from '@forgeax/engine-plugin/loader';\n\ndeclare module '@forgeax/engine-plugin' {\n interface EngineContextServices {\n hostAssembly:\n | import('./backend.js').BackendAssemblyAuthority\n | import('./frontend.js').FrontendAssemblyState;\n hostTransport:\n | import('./transport.js').HostTransportServer\n | import('./transport.js').HostTransportClient;\n }\n}\n\n/** Wire version for the backend-derived browser assembly. */\nexport const HOST_ASSEMBLY_SCHEMA_VERSION = 1 as const;\n\nexport type HostAssemblySchemaVersion = typeof HOST_ASSEMBLY_SCHEMA_VERSION;\n\nexport interface HostModuleDescriptor {\n /** The exact module name used by a Cordis Entry. */\n readonly name: string;\n /** Physical ForgeaX realm expected by the CatalogLoader. */\n readonly realm: PluginRealm;\n /** Code identity. The backend and browser must agree on this value. */\n readonly version: string;\n /** Optional content identity for a static or generated catalog. */\n readonly digest?: string;\n /** URL used by a live browser host. Static builds omit it and use a Catalog. */\n readonly url?: string;\n}\n\n/** One package's explicitly paired backend/frontend Entry projections. */\nexport interface HostPluginPair {\n readonly id: string;\n readonly backend?: HostPluginEndpoint;\n readonly frontend?: HostPluginEndpoint;\n}\n\nexport interface HostPluginEndpoint {\n readonly entry: GamePluginEntry;\n readonly module: HostModuleDescriptor;\n}\n\n/** Safe identity projection; backend Entry configuration never crosses the wire. */\nexport interface HostAssemblyPair {\n readonly id: string;\n readonly entryId: string;\n readonly module: HostModuleDescriptor;\n}\n\n/**\n * A serializable projection of the entries that a frontend may activate.\n * `EntryOptions` is intentionally retained so nested Groups and repeated Entry\n * instances keep native Loader identity and reconciliation semantics.\n */\nexport interface HostAssembly {\n readonly schemaVersion: HostAssemblySchemaVersion;\n /** Digest of entries, modules and explicitly projected configuration. */\n readonly revision: string;\n readonly entries: readonly GamePluginEntry[];\n readonly modules: readonly HostModuleDescriptor[];\n readonly pairs: readonly HostAssemblyPair[];\n /** Safe, frontend-visible configuration only. */\n readonly config?: unknown;\n}\n\nexport interface HostAssemblyInput {\n /** Backend Entries are local authority and are never serialized. */\n readonly backendEntries?: readonly GamePluginEntry[];\n readonly entries?: readonly GamePluginEntry[];\n readonly modules?: readonly HostModuleDescriptor[];\n readonly pairs?: readonly HostPluginPair[];\n readonly config?: unknown;\n}\n\nexport interface HostActivationEntry {\n readonly entryId: string;\n readonly fiberState: string;\n readonly failure?: HostErrorSummary;\n}\n\nexport interface HostErrorSummary {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: Readonly<Record<string, unknown>>;\n}\n\nexport interface HostActivationReport {\n readonly state: 'created' | 'loading' | 'active' | 'failed' | 'disposed';\n readonly revision: string;\n readonly entries?: readonly HostActivationEntry[];\n readonly error?: HostErrorSummary;\n}\n\nexport interface HostAssemblyErrorDetailByCode {\n 'host-assembly-invalid': { readonly reason: string };\n 'host-assembly-revision-mismatch': { readonly actual: string; readonly expected: string };\n 'host-assembly-module-missing': { readonly name: string };\n 'host-assembly-module-version-mismatch': {\n readonly name: string;\n readonly actual: string;\n readonly expected: string;\n };\n 'host-assembly-reload-required': {\n readonly module: string;\n readonly actual: string;\n readonly expected: string;\n };\n 'host-assembly-service-unavailable': { readonly service: string };\n 'host-assembly-stale-request': { readonly service: string; readonly generation: number };\n 'host-assembly-request-aborted': { readonly service: string };\n 'host-transport-failure': { readonly service: string; readonly reason: string };\n 'host-assembly-not-ready': {\n readonly entryId: string;\n readonly fiberState: string;\n readonly failure?: HostErrorSummary;\n };\n}\n\nexport type HostAssemblyErrorCode = keyof HostAssemblyErrorDetailByCode;\n\nexport class HostAssemblyError<\n C extends HostAssemblyErrorCode = HostAssemblyErrorCode,\n> extends Error {\n readonly code: C;\n readonly expected: string;\n readonly hint: string;\n readonly detail: HostAssemblyErrorDetailByCode[C];\n\n constructor(code: C, expected: string, hint: string, detail: HostAssemblyErrorDetailByCode[C]) {\n super(`${code}: ${expected}`);\n this.name = 'HostAssemblyError';\n this.code = code;\n this.expected = expected;\n this.hint = hint;\n this.detail = detail;\n }\n}\n\n/**\n * Prove that the code selected by a local Catalog is the code named by an\n * assembly descriptor. An optional digest is still checked whenever either\n * side supplies one; an unrelated digest must never stand in for a version.\n */\nexport function assertHostModuleCatalogIdentity(\n module: HostModuleDescriptor,\n record: PluginCatalogRecord,\n): void {\n if (record.version !== undefined && record.version !== module.version) {\n throw new HostAssemblyError(\n 'host-assembly-module-version-mismatch',\n `module ${module.name} to load catalog version ${module.version}`,\n 'Regenerate the static Catalog from the same backend package revision.',\n { name: module.name, actual: record.version, expected: module.version },\n );\n }\n if (\n record.digest !== undefined &&\n module.digest !== undefined &&\n record.digest !== module.digest\n ) {\n throw new HostAssemblyError(\n 'host-assembly-module-version-mismatch',\n `module ${module.name} to load catalog digest ${module.digest ?? 'none'}`,\n 'Regenerate the static Catalog from the same backend package bytes.',\n { name: module.name, actual: record.digest, expected: module.digest ?? 'none' },\n );\n }\n const versionMatches = record.version !== undefined && record.version === module.version;\n const digestMatches =\n module.digest !== undefined && record.digest !== undefined && record.digest === module.digest;\n const staticWithoutIdentity =\n module.version === 'static' &&\n module.digest === undefined &&\n record.version === undefined &&\n record.digest === undefined;\n if (!versionMatches && !digestMatches && !staticWithoutIdentity) {\n throw new HostAssemblyError(\n 'host-assembly-module-version-mismatch',\n `module ${module.name} to have a matching catalog code identity for ${module.version}`,\n 'Add the generated module version or digest to the static Catalog.',\n {\n name: module.name,\n actual: record.version ?? record.digest ?? 'unknown',\n expected: module.version,\n },\n );\n }\n}\n\nexport interface HostAssemblyResult {\n readonly ok: true;\n readonly value: HostAssembly;\n}\n\nexport interface HostAssemblyFailure {\n readonly ok: false;\n readonly error: HostAssemblyError;\n}\n\nexport type HostAssemblyValidation = HostAssemblyResult | HostAssemblyFailure;\n\n/** JSON-stable projection used for revision identity and diagnostics. */\nexport function canonicalHostJson(value: unknown): string {\n if (value === undefined) return 'undefined';\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(canonicalHostJson).join(',')}]`;\n return `{${Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, item]) => `${JSON.stringify(key)}:${canonicalHostJson(item)}`)\n .join(',')}}`;\n}\n\n/** Small deterministic digest; it is an identity check, not a security hash. */\nexport function hostRevision(value: unknown): string {\n let hash = 2166136261;\n for (const char of canonicalHostJson(value)) {\n hash ^= char.codePointAt(0) ?? 0;\n hash = Math.imul(hash, 16777619);\n }\n return `fnv1a:${(hash >>> 0).toString(16).padStart(8, '0')}`;\n}\n\nfunction cloneEntry(entry: GamePluginEntry): GamePluginEntry {\n const config = entry.group\n ? (entry.config as readonly GamePluginEntry[] | undefined)?.map(cloneEntry)\n : entry.config;\n return {\n id: entry.id,\n name: entry.name,\n ...(config === undefined ? {} : { config }),\n ...(entry.group === undefined ? {} : { group: entry.group }),\n ...(entry.disabled === undefined ? {} : { disabled: entry.disabled }),\n ...(entry.inject === undefined ? {} : { inject: entry.inject }),\n ...(entry.realm === undefined ? {} : { realm: entry.realm }),\n };\n}\n\nfunction projectPairs(pairs: readonly HostPluginPair[]): {\n readonly entries: readonly GamePluginEntry[];\n readonly modules: readonly HostModuleDescriptor[];\n readonly projections: readonly HostAssemblyPair[];\n} {\n const entries: GamePluginEntry[] = [];\n const modules: HostModuleDescriptor[] = [];\n const projections: HostAssemblyPair[] = [];\n for (const pair of pairs) {\n if (\n pair.backend !== undefined &&\n pair.frontend !== undefined &&\n pair.backend.module.version !== pair.frontend.module.version\n ) {\n throw new HostAssemblyError(\n 'host-assembly-module-version-mismatch',\n `paired module ${pair.id} to use one code version on both hosts`,\n 'Resolve backend and frontend package entries from the same locked package revision.',\n {\n name: pair.id,\n actual: pair.backend.module.version,\n expected: pair.frontend.module.version,\n },\n );\n }\n if (pair.frontend === undefined) continue;\n entries.push(pair.frontend.entry);\n modules.push(pair.frontend.module);\n projections.push({\n id: pair.id,\n entryId: pair.frontend.entry.id,\n module: pair.frontend.module,\n });\n }\n return { entries, modules, projections };\n}\n\nfunction assemblyPairsFromInput(input: HostAssemblyInput): {\n readonly entries: readonly GamePluginEntry[];\n readonly modules: readonly HostModuleDescriptor[];\n readonly pairs: readonly HostAssemblyPair[];\n} {\n if (input.pairs !== undefined) {\n const projected = projectPairs(input.pairs);\n return {\n entries: input.entries ?? projected.entries,\n modules: input.modules ?? projected.modules,\n pairs: projected.projections,\n };\n }\n const entries = input.entries ?? [];\n const modules = [...(input.modules ?? [])];\n for (const [index, entry] of entries.entries()) {\n if (modules[index] !== undefined || modules.some((module) => module.name === entry.name))\n continue;\n modules.push({\n name: entry.name,\n realm: entry.realm ?? 'engine',\n version: 'unknown',\n });\n }\n return {\n entries,\n modules,\n pairs: entries.map((entry, index) => ({\n id: entry.id,\n entryId: entry.id,\n module:\n modules[index]?.name === entry.name\n ? modules[index]\n : (modules.find((module) => module.name === entry.name) ?? {\n name: entry.name,\n realm: entry.realm ?? 'engine',\n version: 'unknown',\n }),\n })),\n };\n}\n\n/** Build one disposable assembly projection from effective backend inputs. */\nexport function createHostAssembly(input: HostAssemblyInput): HostAssembly {\n const projected = assemblyPairsFromInput(input);\n const entries = projected.entries.map(cloneEntry);\n const modules = projected.modules.map((module) => ({ ...module }));\n const pairs = projected.pairs.map((pair) => ({ ...pair, module: { ...pair.module } }));\n const identity = {\n schemaVersion: HOST_ASSEMBLY_SCHEMA_VERSION,\n entries,\n modules,\n pairs,\n ...(input.config === undefined ? {} : { config: input.config }),\n };\n return {\n ...identity,\n revision: hostRevision(identity),\n };\n}\n\nfunction validateEntry(entry: EntryOptions, path: string): string | undefined {\n if (entry === null || typeof entry !== 'object') return `${path} must be an Entry object`;\n if (typeof entry.id !== 'string' || entry.id.length === 0) return `${path}.id must be non-empty`;\n if (typeof entry.name !== 'string' || entry.name.length === 0)\n return `${path}.name must be non-empty`;\n if (entry.group === true) {\n if (!Array.isArray(entry.config)) return `${path}.config must be an Entry array for a Group`;\n for (const [index, child] of entry.config.entries()) {\n const reason = validateEntry(child as EntryOptions, `${path}.config[${index}]`);\n if (reason !== undefined) return reason;\n }\n }\n return undefined;\n}\n\n/** Validate a received assembly before touching the native Loader. */\nexport function validateHostAssembly(assembly: HostAssembly): HostAssemblyValidation {\n if (assembly === null || typeof assembly !== 'object') {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'assembly to be an object',\n 'Regenerate the frontend assembly from the active backend authority.',\n { reason: 'assembly is not an object' },\n ),\n };\n }\n if (assembly.schemaVersion !== HOST_ASSEMBLY_SCHEMA_VERSION) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n `assembly schema ${HOST_ASSEMBLY_SCHEMA_VERSION}`,\n 'Regenerate the frontend assembly with the matching Engine host package.',\n { reason: `unsupported schema ${String(assembly.schemaVersion)}` },\n ),\n };\n }\n if (!Array.isArray(assembly.entries) || !Array.isArray(assembly.modules)) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'assembly entries and modules to be arrays',\n 'Regenerate the frontend assembly from the active backend authority.',\n { reason: 'entries or modules is not an array' },\n ),\n };\n }\n if (!Array.isArray(assembly.pairs)) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'assembly pairs to be an array',\n 'Regenerate the assembly from the backend host using the matching host package.',\n { reason: 'pairs is not an array' },\n ),\n };\n }\n const seen = new Set<string>();\n for (const [index, entry] of assembly.entries.entries()) {\n const reason = validateEntry(entry, `entries[${index}]`);\n if (reason !== undefined) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'all assembly entries to be valid native EntryOptions',\n 'Repair the backend Entry projection before publishing it to a browser.',\n { reason },\n ),\n };\n }\n if (seen.has(entry.id)) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'assembly Entry ids to be unique',\n 'Give repeated plugin instances independent stable ids.',\n { reason: `duplicate Entry id ${entry.id}` },\n ),\n };\n }\n seen.add(entry.id);\n }\n const seenModules = new Map<string, HostModuleDescriptor>();\n for (const [index, module] of assembly.modules.entries()) {\n if (\n module === null ||\n typeof module !== 'object' ||\n typeof module.name !== 'string' ||\n typeof module.realm !== 'string' ||\n typeof module.version !== 'string' ||\n module.name.length === 0 ||\n module.version.length === 0 ||\n (module.url !== undefined && typeof module.url !== 'string') ||\n (module.digest !== undefined &&\n (typeof module.digest !== 'string' || module.digest.length === 0))\n ) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'module names and versions to be non-empty',\n 'Regenerate the module projection from the resolved package metadata.',\n { reason: `invalid module at index ${index}` },\n ),\n };\n }\n const previousModule = seenModules.get(module.name);\n if (\n previousModule !== undefined &&\n (previousModule.realm !== module.realm ||\n previousModule.version !== module.version ||\n previousModule.url !== module.url ||\n previousModule.digest !== module.digest)\n ) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'assembly module identity to be consistent for repeated Entries',\n 'Reuse one resolved module identity when a package has multiple Entry instances.',\n { reason: `module ${module.name} has conflicting identities` },\n ),\n };\n }\n seenModules.set(module.name, module);\n }\n const seenPairIds = new Set<string>();\n for (const [index, pair] of assembly.pairs.entries()) {\n const pairModule = pair?.module;\n if (\n pair === null ||\n typeof pair !== 'object' ||\n typeof pair.id !== 'string' ||\n pair.id.length === 0 ||\n typeof pair.entryId !== 'string' ||\n pair.entryId.length === 0 ||\n pairModule === null ||\n pairModule === undefined ||\n typeof pairModule !== 'object' ||\n typeof pairModule.name !== 'string' ||\n typeof pairModule.realm !== 'string' ||\n typeof pairModule.version !== 'string' ||\n pairModule.name.length === 0 ||\n pairModule.version.length === 0 ||\n (pairModule.url !== undefined && typeof pairModule.url !== 'string') ||\n (pairModule.digest !== undefined &&\n (typeof pairModule.digest !== 'string' || pairModule.digest.length === 0))\n ) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'assembly pair identities and modules to be valid',\n 'Regenerate paired frontend entries from the backend package manifest.',\n { reason: `invalid pair at index ${index}` },\n ),\n };\n }\n if (seenPairIds.has(pair.id)) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'assembly pair ids to be unique',\n 'Give each paired package instance an independent stable id.',\n { reason: `duplicate pair ${pair.id}` },\n ),\n };\n }\n seenPairIds.add(pair.id);\n if (!assembly.entries.some((entry) => entry.id === pair.entryId)) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n `pair ${pair.id} to reference an assembly Entry`,\n 'Keep paired identity and frontend Entry projection under one backend authority.',\n { reason: `missing frontend Entry ${pair.entryId}` },\n ),\n };\n }\n const module = assembly.modules.find(\n (candidate) =>\n candidate.name === pairModule.name &&\n candidate.realm === pairModule.realm &&\n candidate.version === pairModule.version &&\n candidate.url === pairModule.url &&\n candidate.digest === pairModule.digest,\n );\n if (module === undefined) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n `pair ${pair.id} to reference a resolved frontend module`,\n 'Keep module/code identity in the backend-derived assembly projection.',\n { reason: `missing frontend module ${pairModule.name}` },\n ),\n };\n }\n }\n const expected = hostRevision({\n schemaVersion: assembly.schemaVersion,\n entries: assembly.entries,\n modules: assembly.modules,\n pairs: assembly.pairs,\n ...(assembly.config === undefined ? {} : { config: assembly.config }),\n });\n if (expected !== assembly.revision) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-revision-mismatch',\n 'assembly revision to match its entries and modules',\n 'Discard the stale response and request the current backend assembly again.',\n { actual: assembly.revision, expected },\n ),\n };\n }\n return { ok: true, value: assembly };\n}\n\n/** Derive a static module descriptor set from an existing native Catalog. */\nexport function modulesFromCatalog(\n catalog: PluginCatalog,\n realm: PluginRealm,\n version = 'static',\n): HostModuleDescriptor[] {\n return [...catalog.entries()]\n .filter(([, record]) => record.realm === realm)\n .map(([name, record]) => ({\n name,\n realm,\n version: record.version ?? version,\n ...(record.digest === undefined ? {} : { digest: record.digest }),\n }));\n}\n","import { Context, type Fiber, type Plugin } from '@forgeax/engine-plugin';\n\n/**\n * The product-neutral host bootstrap. It owns only a Cordis Context and the\n * supplied startup entries; assembly, transport, Project, and App are all\n * ordinary plugins layered above this seam.\n */\nexport interface HostStartupOptions {\n readonly context?: Context;\n readonly startupPlugins?: readonly Plugin[];\n}\n\nexport interface HostStartup {\n readonly context: Context;\n readonly ownedContext: boolean;\n readonly fibers: readonly Fiber[];\n dispose(): Promise<void>;\n}\n\nexport async function createHostStartup(options: HostStartupOptions = {}): Promise<HostStartup> {\n const context = options.context ?? new Context();\n const ownedContext = options.context === undefined;\n const fibers: Fiber[] = [];\n let disposed = false;\n try {\n for (const plugin of options.startupPlugins ?? []) fibers.push(await context.plugin(plugin));\n } catch (error) {\n for (const fiber of fibers.reverse()) await fiber.dispose();\n if (ownedContext) await context.fiber.dispose();\n throw error;\n }\n return {\n context,\n ownedContext,\n fibers,\n async dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n for (const fiber of [...fibers].reverse()) await fiber.dispose();\n if (ownedContext) await context.fiber.dispose();\n },\n };\n}\n","import { HostAssemblyError, type HostErrorSummary } from './protocol.js';\n\nexport const HOST_ASSEMBLY_SERVICE = 'host/assembly.get' as const;\nexport const HOST_ACTIVATION_REPORT_SERVICE = 'host/assembly.report' as const;\nexport const HOST_ASSEMBLY_CHANGED_TOPIC = 'host/assembly.changed' as const;\n\nexport interface HostRequestOptions {\n readonly signal?: AbortSignal;\n /** The service generation observed by the caller. */\n readonly generation?: number;\n}\n\nexport interface HostServiceRequest<T = unknown> {\n readonly service: string;\n readonly payload: T;\n readonly generation: number;\n readonly signal: AbortSignal;\n}\n\nexport type HostServiceHandler<TPayload = unknown, TResult = unknown> = (\n request: HostServiceRequest<TPayload>,\n) => Promise<TResult> | TResult;\n\nexport interface HostServiceSnapshot {\n readonly service: string;\n readonly generation: number;\n}\n\nexport interface HostTransportClient {\n readonly connected: boolean;\n readonly generation: number;\n request<TPayload, TResult>(\n service: string,\n payload: TPayload,\n options?: HostRequestOptions,\n ): Promise<TResult>;\n subscribe<T>(topic: string, listener: (payload: T) => void): () => void;\n /** Observe a terminal connection loss without issuing another request. */\n onDisconnect(listener: (error: HostAssemblyError) => void): () => void;\n close(reason?: unknown): void;\n}\n\nexport interface HostTransportServer {\n readonly connectedClients: number;\n register<TPayload, TResult>(\n service: string,\n handler: HostServiceHandler<TPayload, TResult>,\n ): () => void;\n invalidate(service: string): void;\n snapshot(service: string): HostServiceSnapshot | undefined;\n publish<T>(topic: string, payload: T): void;\n connect(): HostTransportClient;\n close(reason?: unknown): void;\n}\n\ninterface ServiceRecord {\n readonly identity: symbol;\n generation: number;\n handler: (request: HostServiceRequest<unknown>) => Promise<unknown> | unknown;\n pending: Set<AbortController>;\n}\n\ninterface ClientState {\n connected: boolean;\n readonly subscriptions: Map<string, Set<(payload: unknown) => void>>;\n readonly pending: Set<AbortController>;\n readonly disconnectListeners: Set<(error: HostAssemblyError) => void>;\n}\n\n/**\n * Create the small typed transport seam used by host plugins.\n *\n * This implementation is deliberately transport-neutral: the same request,\n * subscription, cancellation, and generation semantics can be adapted to a\n * WebSocket or MessagePort without moving business objects across the wire.\n * It is also useful for deterministic host and lifecycle tests.\n */\nexport function createHostTransport(): HostTransportServer {\n const services = new Map<string, ServiceRecord>();\n const generations = new Map<string, number>();\n const clients = new Set<ClientState>();\n let closed = false;\n\n const closeClient = (state: ClientState, reason?: unknown): void => {\n if (!state.connected) return;\n state.connected = false;\n for (const controller of state.pending) controller.abort();\n state.pending.clear();\n for (const callbacks of state.subscriptions.values()) callbacks.clear();\n state.subscriptions.clear();\n clients.delete(state);\n const error = new HostAssemblyError(\n 'host-transport-failure',\n 'the host connection to remain available',\n 'Reconnect the frontend host before issuing another request.',\n { service: 'host/socket', reason: String(reason ?? 'host connection closed') },\n );\n for (const listener of state.disconnectListeners) listener(error);\n state.disconnectListeners.clear();\n };\n\n const server: HostTransportServer = {\n get connectedClients() {\n return clients.size;\n },\n register(service, handler) {\n if (closed) throw new Error('host transport is closed');\n const previous = services.get(service);\n const generation = (generations.get(service) ?? 0) + 1;\n generations.set(service, generation);\n for (const controller of previous?.pending ?? []) controller.abort();\n const identity = Symbol(service);\n services.set(service, {\n identity,\n generation,\n handler: handler as unknown as (\n request: HostServiceRequest<unknown>,\n ) => Promise<unknown> | unknown,\n pending: new Set(),\n });\n return () => {\n const current = services.get(service);\n if (current?.identity !== identity) return;\n for (const controller of current.pending) controller.abort();\n generations.set(service, current.generation + 1);\n services.delete(service);\n };\n },\n invalidate(service) {\n const current = services.get(service);\n if (current === undefined) return;\n for (const controller of current.pending) controller.abort();\n generations.set(service, current.generation + 1);\n services.delete(service);\n },\n snapshot(service) {\n const current = services.get(service);\n return current === undefined ? undefined : { service, generation: current.generation };\n },\n publish(topic, payload) {\n for (const state of clients) {\n for (const listener of state.subscriptions.get(topic) ?? []) listener(payload);\n }\n },\n connect() {\n if (closed) throw new Error('host transport is closed');\n const state: ClientState = {\n connected: true,\n subscriptions: new Map(),\n pending: new Set(),\n disconnectListeners: new Set(),\n };\n clients.add(state);\n const client: HostTransportClient = {\n get connected() {\n return state.connected;\n },\n get generation() {\n let current = 0;\n for (const service of services.values()) current = Math.max(current, service.generation);\n return current;\n },\n async request(service, payload, options = {}) {\n if (!state.connected) {\n throw new HostAssemblyError(\n 'host-assembly-service-unavailable',\n `service ${service} to be available on the current connection`,\n 'Reconnect the frontend host before issuing another request.',\n { service },\n );\n }\n if (options.signal?.aborted) {\n throw new HostAssemblyError(\n 'host-assembly-request-aborted',\n `request ${service} to start with a live AbortSignal`,\n 'Start a fresh request with a live AbortSignal.',\n { service },\n );\n }\n const record = services.get(service);\n if (record === undefined) {\n const invalidatedGeneration = generations.get(service);\n if (\n options.generation !== undefined &&\n invalidatedGeneration !== undefined &&\n options.generation < invalidatedGeneration\n ) {\n throw new HostAssemblyError(\n 'host-assembly-stale-request',\n `request generation ${options.generation} to match the invalidated service ${service}`,\n 'Refresh the client capability after the backend service is enabled again.',\n { service, generation: options.generation },\n );\n }\n throw new HostAssemblyError(\n 'host-assembly-service-unavailable',\n `service ${service} to be registered`,\n 'Wait for the backend plugin to activate before using this capability.',\n { service },\n );\n }\n const generation = options.generation ?? record.generation;\n if (generation !== record.generation) {\n throw new HostAssemblyError(\n 'host-assembly-stale-request',\n `request generation ${generation} to match service ${service}`,\n 'Refresh the client capability and retry only when the owning business contract permits it.',\n { service, generation },\n );\n }\n const controller = new AbortController();\n const abortFromCaller = (): void => controller.abort();\n options.signal?.addEventListener('abort', abortFromCaller, { once: true });\n record.pending.add(controller);\n state.pending.add(controller);\n let removeAbortRequest: (() => void) | undefined;\n try {\n if (controller.signal.aborted) {\n throw new HostAssemblyError(\n 'host-assembly-request-aborted',\n `request ${service} not to be aborted before execution`,\n 'Start a fresh request with a live AbortSignal.',\n { service },\n );\n }\n let abortReject: ((reason: unknown) => void) | undefined;\n const aborted = new Promise<never>((_, reject) => {\n abortReject = reject;\n });\n const abortRequest = (): void => {\n abortReject?.(\n new HostAssemblyError(\n 'host-assembly-request-aborted',\n `request ${service} to finish before its service is closed or invalidated`,\n 'Treat the capability as withdrawn and refresh the service before retrying.',\n { service },\n ),\n );\n };\n controller.signal.addEventListener('abort', abortRequest, { once: true });\n removeAbortRequest = () => controller.signal.removeEventListener('abort', abortRequest);\n const result = await Promise.race([\n Promise.resolve(\n record.handler({\n service,\n payload,\n generation,\n signal: controller.signal,\n }),\n ),\n aborted,\n ]);\n if (controller.signal.aborted) {\n throw new HostAssemblyError(\n 'host-assembly-request-aborted',\n `request ${service} to finish before its service is invalidated`,\n 'Treat the capability as withdrawn and refresh the service before retrying.',\n { service },\n );\n }\n return result as never;\n } finally {\n removeAbortRequest?.();\n record.pending.delete(controller);\n state.pending.delete(controller);\n options.signal?.removeEventListener('abort', abortFromCaller);\n }\n },\n subscribe(topic, listener) {\n if (!state.connected) return () => {};\n const callbacks = state.subscriptions.get(topic) ?? new Set();\n callbacks.add(listener as (payload: unknown) => void);\n state.subscriptions.set(topic, callbacks);\n return () => {\n callbacks.delete(listener as (payload: unknown) => void);\n if (callbacks.size === 0) state.subscriptions.delete(topic);\n };\n },\n onDisconnect(listener) {\n if (!state.connected) {\n listener(\n new HostAssemblyError(\n 'host-transport-failure',\n 'the host connection to remain available',\n 'Reconnect the frontend host before issuing another request.',\n { service: 'host/socket', reason: 'host connection is already closed' },\n ),\n );\n return () => {};\n }\n state.disconnectListeners.add(listener);\n return () => state.disconnectListeners.delete(listener);\n },\n close(reason) {\n closeClient(state, reason);\n },\n };\n return client;\n },\n close(reason) {\n if (closed) return;\n closed = true;\n for (const service of services.values())\n for (const controller of service.pending) controller.abort();\n services.clear();\n for (const client of [...clients]) closeClient(client, reason);\n generations.clear();\n },\n };\n\n return server;\n}\n\n/** Minimal socket shape shared by browser WebSocket and Node `ws` instances. */\nexport interface HostSocketLike {\n readonly readyState?: number;\n send(data: string): void;\n close(code?: number, reason?: string): void;\n addEventListener?(type: string, listener: (...args: unknown[]) => void): void;\n removeEventListener?(type: string, listener: (...args: unknown[]) => void): void;\n on?(type: string, listener: (...args: unknown[]) => void): void;\n off?(type: string, listener: (...args: unknown[]) => void): void;\n}\n\ntype HostWireMessage =\n | {\n readonly kind: 'request';\n readonly id: string;\n readonly service: string;\n readonly payload: unknown;\n readonly generation?: number;\n }\n | { readonly kind: 'cancel'; readonly id: string }\n | { readonly kind: 'subscribe'; readonly topic: string }\n | { readonly kind: 'unsubscribe'; readonly topic: string }\n | {\n readonly kind: 'response';\n readonly id: string;\n readonly ok: boolean;\n readonly value?: unknown;\n readonly error?: HostErrorSummary;\n readonly generation?: number;\n }\n | { readonly kind: 'event'; readonly topic: string; readonly payload: unknown };\n\nfunction addSocketListener(\n socket: HostSocketLike,\n type: string,\n listener: (...args: unknown[]) => void,\n): () => void {\n if (socket.addEventListener !== undefined) {\n socket.addEventListener(type, listener);\n return () => socket.removeEventListener?.(type, listener);\n }\n socket.on?.(type, listener);\n return () => socket.off?.(type, listener);\n}\n\nfunction socketPayload(value: unknown): string | undefined {\n const data = Array.isArray(value) ? value[0] : value;\n if (typeof data === 'string') return data;\n if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);\n if (data instanceof Uint8Array) return new TextDecoder().decode(data);\n if (data !== null && typeof data === 'object' && 'data' in data)\n return socketPayload((data as { readonly data?: unknown }).data);\n return undefined;\n}\n\nfunction parseWire(value: unknown): HostWireMessage | undefined {\n const source = socketPayload(value);\n if (source === undefined) return undefined;\n try {\n const parsed = JSON.parse(source) as unknown;\n return parsed !== null &&\n typeof parsed === 'object' &&\n typeof (parsed as { kind?: unknown }).kind === 'string'\n ? (parsed as HostWireMessage)\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction serializeError(service: string, error: unknown): HostErrorSummary {\n if (\n error !== null &&\n typeof error === 'object' &&\n typeof (error as { code?: unknown }).code === 'string' &&\n typeof (error as { expected?: unknown }).expected === 'string' &&\n typeof (error as { hint?: unknown }).hint === 'string'\n ) {\n const detail = (error as { readonly detail?: unknown }).detail;\n return {\n code: (error as { readonly code: string }).code,\n expected: (error as { readonly expected: string }).expected,\n hint: (error as { readonly hint: string }).hint,\n detail:\n detail !== null && typeof detail === 'object'\n ? (detail as Readonly<Record<string, unknown>>)\n : { reason: String(detail ?? 'unknown failure') },\n };\n }\n return {\n code: 'host-transport-failure',\n expected: `service ${service} to complete without an exception`,\n hint: 'Inspect the backend host process and reconnect before retrying.',\n detail: { service, reason: error instanceof Error ? error.message : String(error) },\n };\n}\n\nfunction errorFromSummary(service: string, summary: HostErrorSummary): HostAssemblyError {\n const detail = summary.detail as Record<string, unknown>;\n const supported = new Set([\n 'host-assembly-invalid',\n 'host-assembly-revision-mismatch',\n 'host-assembly-module-missing',\n 'host-assembly-module-version-mismatch',\n 'host-assembly-reload-required',\n 'host-assembly-service-unavailable',\n 'host-assembly-stale-request',\n 'host-assembly-request-aborted',\n 'host-assembly-not-ready',\n 'host-transport-failure',\n ]);\n if (supported.has(summary.code)) {\n return new HostAssemblyError(\n summary.code as never,\n summary.expected,\n summary.hint,\n detail as never,\n );\n }\n return new HostAssemblyError('host-transport-failure', summary.expected, summary.hint, {\n service,\n reason: summary.detail.reason ? String(summary.detail.reason) : summary.code,\n });\n}\n\nfunction transportFailure(service: string, reason: string): HostAssemblyError {\n return new HostAssemblyError(\n 'host-transport-failure',\n `service ${service} to remain connected`,\n 'Reconnect the frontend host and inspect the backend transport diagnostics.',\n { service, reason },\n );\n}\n\nfunction sendWire(socket: HostSocketLike, message: HostWireMessage): void {\n socket.send(JSON.stringify(message));\n}\n\n/** Connect one browser WebSocket (or an already-open Node `ws`) to a host server. */\nexport async function createHostWebSocketClient(\n socket: HostSocketLike,\n): Promise<HostTransportClient> {\n if (socket.readyState !== undefined && socket.readyState !== 1) {\n await new Promise<void>((resolve, reject) => {\n const removeOpen = addSocketListener(socket, 'open', () => {\n removeOpen();\n removeError();\n resolve();\n });\n const removeError = addSocketListener(socket, 'error', (cause) => {\n removeOpen();\n removeError();\n reject(transportFailure('host/connect', String(cause ?? 'socket error')));\n });\n });\n }\n const pending = new Map<\n string,\n {\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n readonly cleanup: () => void;\n }\n >();\n const subscriptions = new Map<string, Set<(payload: unknown) => void>>();\n const disconnectListeners = new Set<(error: HostAssemblyError) => void>();\n let connected = true;\n let generation = 0;\n let sequence = 0;\n const disconnectError = (reason: unknown): HostAssemblyError =>\n transportFailure('host/socket', reason instanceof Error ? reason.message : String(reason));\n const failPending = (reason: unknown): void => {\n if (!connected) return;\n connected = false;\n for (const request of pending.values()) {\n request.cleanup();\n request.reject(reason);\n }\n pending.clear();\n subscriptions.clear();\n const error = disconnectError(reason);\n for (const listener of disconnectListeners) listener(error);\n disconnectListeners.clear();\n };\n const removeMessage = addSocketListener(socket, 'message', (event) => {\n const message = parseWire(event);\n if (message === undefined) return;\n if (message.kind === 'event') {\n for (const listener of subscriptions.get(message.topic) ?? []) listener(message.payload);\n return;\n }\n if (message.kind !== 'response') return;\n if (message.generation !== undefined) generation = Math.max(generation, message.generation);\n const request = pending.get(message.id);\n if (request === undefined) return;\n pending.delete(message.id);\n request.cleanup();\n if (message.ok) request.resolve(message.value);\n else\n request.reject(\n errorFromSummary(\n 'host/socket',\n message.error ?? serializeError('host/socket', 'unknown response failure'),\n ),\n );\n });\n const removeClose = addSocketListener(socket, 'close', (reason) => {\n removeMessage();\n removeClose();\n removeError();\n failPending(disconnectError(reason));\n });\n const removeError = addSocketListener(socket, 'error', (reason) => {\n failPending(disconnectError(reason));\n });\n const client: HostTransportClient = {\n get connected() {\n return connected;\n },\n get generation() {\n return generation;\n },\n request<TPayload, TResult>(\n service: string,\n payload: TPayload,\n options: HostRequestOptions = {},\n ): Promise<TResult> {\n if (!connected) return Promise.reject(disconnectError('socket is closed'));\n if (options.signal?.aborted)\n return Promise.reject(\n new HostAssemblyError(\n 'host-assembly-request-aborted',\n `request ${service} to start with a live AbortSignal`,\n 'Start a fresh request with a live AbortSignal.',\n { service },\n ),\n );\n sequence += 1;\n const id = `${Date.now().toString(36)}-${sequence.toString(36)}`;\n return new Promise<TResult>((resolve, reject) => {\n const abort = (): void => {\n const request = pending.get(id);\n if (request === undefined) return;\n pending.delete(id);\n request.cleanup();\n try {\n sendWire(socket, { kind: 'cancel', id });\n } catch {\n // The close/error listener reports the transport failure separately.\n }\n reject(\n new HostAssemblyError(\n 'host-assembly-request-aborted',\n `request ${service} to finish before cancellation`,\n 'Start a fresh request with a live AbortSignal.',\n { service },\n ),\n );\n };\n const cleanup = (): void => options.signal?.removeEventListener('abort', abort);\n pending.set(id, {\n resolve: resolve as unknown as (value: unknown) => void,\n reject,\n cleanup,\n });\n options.signal?.addEventListener('abort', abort, { once: true });\n if (options.signal?.aborted) {\n abort();\n return;\n }\n try {\n sendWire(socket, {\n kind: 'request',\n id,\n service,\n payload,\n ...(options.generation === undefined ? {} : { generation: options.generation }),\n });\n } catch (cause) {\n const request = pending.get(id);\n request?.cleanup();\n pending.delete(id);\n reject(disconnectError(cause));\n }\n });\n },\n subscribe(topic, listener) {\n if (!connected) return () => {};\n const listeners = subscriptions.get(topic) ?? new Set();\n listeners.add(listener as (payload: unknown) => void);\n subscriptions.set(topic, listeners);\n sendWire(socket, { kind: 'subscribe', topic });\n return () => {\n listeners.delete(listener as (payload: unknown) => void);\n if (listeners.size !== 0) return;\n subscriptions.delete(topic);\n sendWire(socket, { kind: 'unsubscribe', topic });\n };\n },\n onDisconnect(listener) {\n if (!connected) {\n listener(disconnectError('socket is already closed'));\n return () => {};\n }\n disconnectListeners.add(listener);\n return () => disconnectListeners.delete(listener);\n },\n close(reason) {\n if (!connected) return;\n failPending(disconnectError(reason ?? 'client closed the host connection'));\n removeMessage();\n removeClose();\n removeError();\n socket.close();\n },\n };\n return client;\n}\n\n/** Open a browser-native WebSocket and install the typed host client. */\nexport async function connectHostWebSocket(url: string): Promise<HostTransportClient> {\n const Constructor = globalThis.WebSocket;\n if (typeof Constructor !== 'function')\n throw transportFailure('host/connect', 'the current runtime does not provide WebSocket');\n return createHostWebSocketClient(new Constructor(url) as unknown as HostSocketLike);\n}\n\n/** Attach one accepted process-side socket to an Engine host transport server. */\nexport function attachHostWebSocketServer(\n socket: HostSocketLike,\n server: HostTransportServer,\n): () => void {\n const client = server.connect();\n const pending = new Map<string, AbortController>();\n const subscriptions = new Map<string, () => void>();\n let disposed = false;\n const removeMessage = addSocketListener(socket, 'message', (event) => {\n const message = parseWire(event);\n if (message === undefined || disposed) return;\n if (message.kind === 'cancel') {\n pending.get(message.id)?.abort();\n return;\n }\n if (message.kind === 'subscribe') {\n subscriptions.get(message.topic)?.();\n subscriptions.set(\n message.topic,\n client.subscribe(message.topic, (payload) => {\n if (!disposed) sendWire(socket, { kind: 'event', topic: message.topic, payload });\n }),\n );\n return;\n }\n if (message.kind === 'unsubscribe') {\n subscriptions.get(message.topic)?.();\n subscriptions.delete(message.topic);\n return;\n }\n if (message.kind !== 'request') return;\n const controller = new AbortController();\n pending.set(message.id, controller);\n void client\n .request(message.service, message.payload, {\n signal: controller.signal,\n ...(message.generation === undefined ? {} : { generation: message.generation }),\n })\n .then((value) => {\n if (!disposed)\n sendWire(socket, {\n kind: 'response',\n id: message.id,\n ok: true,\n value,\n generation: client.generation,\n });\n })\n .catch((error) => {\n if (!disposed)\n sendWire(socket, {\n kind: 'response',\n id: message.id,\n ok: false,\n error: serializeError(message.service, error),\n generation: client.generation,\n });\n })\n .finally(() => pending.delete(message.id));\n });\n const removeClose = addSocketListener(socket, 'close', () => dispose());\n const removeError = addSocketListener(socket, 'error', () => dispose());\n function dispose(): void {\n if (disposed) return;\n disposed = true;\n removeMessage();\n removeClose();\n removeError();\n for (const controller of pending.values()) controller.abort();\n pending.clear();\n for (const unsubscribe of subscriptions.values()) unsubscribe();\n subscriptions.clear();\n client.close('host socket disconnected');\n }\n return dispose;\n}\n","import { Context, type Fiber, inspectCatalogPlugins, type Plugin } from '@forgeax/engine-plugin';\nimport {\n type CatalogLoader,\n type GamePluginEntry,\n installCatalogLoader,\n type PluginCatalog,\n type PluginCatalogRecord,\n type PluginRealm,\n projectPluginEntries,\n} from '@forgeax/engine-plugin/loader';\nimport {\n assertHostModuleCatalogIdentity,\n createHostAssembly,\n type HostActivationEntry,\n type HostActivationReport,\n type HostAssembly,\n HostAssemblyError,\n type HostErrorSummary,\n modulesFromCatalog,\n validateHostAssembly,\n} from './protocol.js';\nimport { createHostStartup, type HostStartup } from './startup.js';\nimport {\n HOST_ACTIVATION_REPORT_SERVICE,\n HOST_ASSEMBLY_SERVICE,\n type HostTransportClient,\n} from './transport.js';\n\nexport type FrontendHostState = 'created' | 'loading' | 'active' | 'failed' | 'disposed';\n\nexport interface FrontendHostStatus {\n readonly state: FrontendHostState;\n readonly revision: string;\n readonly entries?: readonly HostActivationEntry[];\n readonly error?: unknown;\n}\n\nexport interface FrontendAssemblyState {\n readonly current: HostAssembly;\n readonly status: FrontendHostStatus;\n}\n\nexport interface FrontendHostOptions {\n /** App may provide its existing Engine Context; the host owns only its Fiber. */\n readonly context?: Context;\n readonly startupPlugins?: readonly Plugin[];\n readonly catalog?: PluginCatalog;\n /**\n * Optional local assembly snapshot used for the first staged activation.\n * When a transport is also present, the backend remains authoritative for\n * later updates; this snapshot lets callers activate provider-only entries\n * before their host-owned services are ready.\n */\n readonly assembly?: HostAssembly;\n readonly entries?: readonly GamePluginEntry[];\n readonly realm?: PluginRealm;\n readonly config?: unknown;\n readonly transport?: HostTransportClient;\n readonly moduleVersions?: ReadonlyMap<string, string>;\n readonly reportStatus?: (status: FrontendHostStatus) => void | Promise<void>;\n readonly autoActivate?: boolean;\n}\n\nexport interface FrontendHost {\n readonly context: Context;\n readonly loader?: CatalogLoader;\n readonly assembly: FrontendAssemblyState;\n readonly transport?: HostTransportClient;\n readonly ownedContext: boolean;\n readonly status: FrontendHostStatus;\n activate(assembly?: HostAssembly): Promise<void>;\n update(assembly: HostAssembly): Promise<void>;\n dispose(): Promise<void>;\n}\n\nfunction hostFoundationPlugin(\n assembly: FrontendAssemblyState,\n transport: HostTransportClient | undefined,\n): Plugin {\n return {\n name: 'forgeax:frontend-host-foundation',\n provide: ['hostAssembly', 'hostTransport'],\n apply(ctx) {\n ctx.provide('hostAssembly', assembly);\n if (transport !== undefined) ctx.provide('hostTransport', transport);\n },\n };\n}\n\nfunction dynamicModuleRecord(\n name: string,\n realm: PluginRealm,\n version: string,\n url: string | undefined,\n digest: string | undefined,\n): PluginCatalogRecord {\n if (url === undefined) {\n return {\n realm,\n version,\n ...(digest === undefined ? {} : { digest }),\n load: async () => {\n throw new HostAssemblyError(\n 'host-assembly-module-missing',\n `module ${name} to have a browser URL or static Catalog record`,\n 'Add the module to the frozen Catalog or publish its browser entry from the backend.',\n { name },\n );\n },\n };\n }\n return {\n realm,\n version,\n ...(digest === undefined ? {} : { digest }),\n load: () => import(/* @vite-ignore */ url),\n };\n}\n\nfunction catalogForAssembly(\n assembly: HostAssembly,\n staticCatalog: PluginCatalog | undefined,\n): PluginCatalog {\n const catalog = new Map<string, PluginCatalogRecord>();\n for (const module of assembly.modules) {\n const existing = staticCatalog?.get(module.name);\n if (existing !== undefined) {\n assertHostModuleCatalogIdentity(module, existing);\n catalog.set(module.name, existing);\n continue;\n }\n catalog.set(\n module.name,\n dynamicModuleRecord(module.name, module.realm, module.version, module.url, module.digest),\n );\n }\n for (const [name, record] of staticCatalog ?? []) {\n if (!catalog.has(name)) catalog.set(name, record);\n }\n return catalog;\n}\n\nfunction assertModuleVersions(\n assembly: HostAssembly,\n versions: ReadonlyMap<string, string> | undefined,\n): void {\n if (versions === undefined) return;\n for (const module of assembly.modules) {\n const actual = versions.get(module.name);\n if (actual === undefined || actual === module.version) continue;\n throw new HostAssemblyError(\n 'host-assembly-module-version-mismatch',\n `module ${module.name} to use version ${module.version}`,\n 'Refresh the browser module graph from the same backend assembly revision.',\n { name: module.name, actual, expected: module.version },\n );\n }\n}\n\nfunction moduleIdentity(module: {\n readonly version: string;\n readonly digest?: string;\n readonly url?: string;\n}): string {\n return `${module.version}@${module.digest ?? module.url ?? '<catalog>'}`;\n}\n\n/**\n * The native Loader keeps the imported module graph for its lifetime. A new\n * module URL or code identity therefore cannot be applied by Entry.update;\n * accepting it would report a new assembly while executing the old code.\n */\nfunction assertModuleReloadBoundary(previous: HostAssembly, next: HostAssembly): void {\n const previousModules = new Map(previous.modules.map((module) => [module.name, module]));\n const nextModules = new Map(next.modules.map((module) => [module.name, module]));\n const names = new Set([...previousModules.keys(), ...nextModules.keys()]);\n for (const name of names) {\n const before = previousModules.get(name);\n const after = nextModules.get(name);\n const beforeIdentity = before === undefined ? '<absent>' : moduleIdentity(before);\n const afterIdentity = after === undefined ? '<absent>' : moduleIdentity(after);\n if (\n before === undefined ||\n after === undefined ||\n before.realm !== after.realm ||\n beforeIdentity !== afterIdentity\n ) {\n throw new HostAssemblyError(\n 'host-assembly-reload-required',\n `module ${name} to keep its loaded code identity ${beforeIdentity}`,\n 'Reload the frontend host to install the new module graph before activating this assembly.',\n { module: name, actual: beforeIdentity, expected: afterIdentity },\n );\n }\n }\n}\n\nfunction staticAssembly(options: FrontendHostOptions, realm: PluginRealm): HostAssembly {\n const entries = options.entries ?? [];\n const modules =\n options.catalog === undefined ? [] : modulesFromCatalog(options.catalog, realm, 'static');\n return createHostAssembly({\n entries,\n modules,\n ...(options.config === undefined ? {} : { config: options.config }),\n });\n}\n\nfunction errorSummary(error: unknown): HostErrorSummary | undefined {\n if (\n error === null ||\n typeof error !== 'object' ||\n typeof (error as { code?: unknown }).code !== 'string' ||\n typeof (error as { expected?: unknown }).expected !== 'string' ||\n typeof (error as { hint?: unknown }).hint !== 'string'\n )\n return undefined;\n const detail = (error as { readonly detail?: unknown }).detail;\n return {\n code: (error as { readonly code: string }).code,\n expected: (error as { readonly expected: string }).expected,\n hint: (error as { readonly hint: string }).hint,\n detail:\n detail !== null && typeof detail === 'object'\n ? (detail as Readonly<Record<string, unknown>>)\n : { reason: String(detail ?? 'unknown failure') },\n };\n}\n\nasync function fetchInitialAssembly(\n options: FrontendHostOptions,\n realm: PluginRealm,\n): Promise<HostAssembly> {\n // An explicit assembly is an intentional bootstrap snapshot. DevKit uses\n // it to stage provider-only entries on reconnect before installing the\n // GameHost service; the transport still supplies the authoritative full\n // assembly immediately afterwards.\n if (options.assembly !== undefined) return options.assembly;\n if (options.transport !== undefined)\n return options.transport.request<undefined, HostAssembly>(HOST_ASSEMBLY_SERVICE, undefined);\n if (\n options.entries !== undefined ||\n options.catalog !== undefined ||\n options.config !== undefined\n )\n return staticAssembly(options, realm);\n throw new HostAssemblyError(\n 'host-assembly-service-unavailable',\n 'a static assembly or backend transport to be provided',\n 'Pass the frozen assembly for a static player or connect the frontend host to a backend host.',\n { service: HOST_ASSEMBLY_SERVICE },\n );\n}\n\nfunction readiness(loader: CatalogLoader): readonly HostActivationEntry[] {\n return inspectCatalogPlugins(loader).live.map((entry) => ({\n entryId: entry.entryId,\n fiberState: entry.fiberState,\n ...(entry.failure === undefined\n ? {}\n : {\n failure: {\n code: entry.failure.code,\n expected: entry.failure.expected,\n hint: entry.failure.hint,\n detail: entry.failure.detail,\n },\n }),\n }));\n}\n\nfunction assertReady(entries: readonly HostActivationEntry[]): void {\n const failed = entries.find(\n (entry) => entry.fiberState !== 'active' && entry.fiberState !== 'disabled',\n );\n if (failed === undefined) return;\n throw new HostAssemblyError(\n 'host-assembly-not-ready',\n `Entry ${failed.entryId} to reach active or disabled Fiber state`,\n 'Inspect the Entry failure or waiting dependency and repair the frontend package graph.',\n {\n entryId: failed.entryId,\n fiberState: failed.fiberState,\n ...(failed.failure === undefined ? {} : { failure: failed.failure }),\n },\n );\n}\n\n/** Start one independent browser-side manager and its native Cordis Loader. */\nexport async function createFrontendHost(options: FrontendHostOptions = {}): Promise<FrontendHost> {\n const realm = options.realm ?? 'engine';\n const initial = await fetchInitialAssembly(options, realm);\n const context = options.context ?? new Context();\n const ownedContext = options.context === undefined;\n const checked = validateHostAssembly(initial);\n if (!checked.ok) throw checked.error;\n let current = checked.value;\n let status: FrontendHostStatus = {\n state: 'created',\n revision: current.revision,\n };\n const state: FrontendAssemblyState = {\n get current() {\n return current;\n },\n get status() {\n return status;\n },\n };\n let startup: HostStartup | undefined;\n let loaderFiber: Fiber | undefined;\n let loader: CatalogLoader | undefined;\n let disposed = false;\n let removeTransportDisconnect: (() => void) | undefined;\n const report = async (next: FrontendHostStatus): Promise<void> => {\n status = next;\n await options.reportStatus?.(next);\n if (options.transport !== undefined) {\n const report: {\n state: HostActivationReport['state'];\n revision: string;\n entries?: readonly HostActivationEntry[];\n error?: HostErrorSummary;\n } = {\n state: next.state,\n revision: next.revision,\n };\n if (next.entries !== undefined) report.entries = next.entries;\n const failure = errorSummary(next.error);\n if (failure !== undefined) report.error = failure;\n try {\n await options.transport.request(HOST_ACTIVATION_REPORT_SERVICE, report);\n } catch (error) {\n const failed: FrontendHostStatus = {\n ...next,\n state: next.state === 'active' ? 'failed' : next.state,\n error,\n };\n status = failed;\n await options.reportStatus?.(failed);\n throw error;\n }\n }\n };\n if (options.transport !== undefined) {\n removeTransportDisconnect = options.transport.onDisconnect((error) => {\n if (disposed) return;\n const failed: FrontendHostStatus = {\n state: 'failed',\n revision: current.revision,\n error,\n };\n status = failed;\n void Promise.resolve(options.reportStatus?.(failed)).catch(() => {});\n });\n }\n\n try {\n startup = await createHostStartup({\n context,\n startupPlugins: [\n hostFoundationPlugin(state, options.transport),\n ...(options.startupPlugins ?? []),\n ],\n });\n if (options.autoActivate !== false) {\n // Activation is performed below through the returned host so its status\n // callback and failure rollback cover the first assembly as well.\n const host = {\n context,\n ...(options.transport === undefined ? {} : { transport: options.transport }),\n assembly: state,\n ...(ownedContext ? { ownedContext: true } : { ownedContext: false }),\n get status() {\n return status;\n },\n activate: async (_next?: HostAssembly) => {},\n update: async (_next: HostAssembly) => {},\n dispose: async () => {},\n } as FrontendHost;\n await activateFrontendHost(\n host,\n initial,\n options,\n realm,\n () => loader,\n (value) => {\n loader = value.loader;\n loaderFiber = value.fiber;\n },\n report,\n () => {\n current = initial;\n },\n );\n }\n } catch (error) {\n removeTransportDisconnect?.();\n await loaderFiber?.dispose();\n await startup?.dispose();\n throw error;\n }\n\n const host: FrontendHost = {\n context,\n ...(loader === undefined ? {} : { loader }),\n ...(options.transport === undefined ? {} : { transport: options.transport }),\n assembly: state,\n ownedContext,\n get status() {\n return status;\n },\n async activate(next = current) {\n await activateFrontendHost(\n host,\n next,\n options,\n realm,\n () => loader,\n (value) => {\n loader = value.loader;\n loaderFiber = value.fiber;\n (host as { loader?: CatalogLoader }).loader = value.loader;\n },\n report,\n () => {\n current = next;\n },\n );\n },\n async update(next) {\n await host.activate(next);\n },\n async dispose() {\n if (disposed) return;\n disposed = true;\n removeTransportDisconnect?.();\n await loaderFiber?.dispose();\n await startup?.dispose();\n status = { state: 'disposed', revision: current.revision };\n },\n };\n return host;\n}\n\nasync function activateFrontendHost(\n host: FrontendHost,\n next: HostAssembly,\n options: FrontendHostOptions,\n realm: PluginRealm,\n getLoader: () => CatalogLoader | undefined,\n setLoader: (value: { loader: CatalogLoader; fiber: Fiber }) => void,\n report: (status: FrontendHostStatus) => Promise<void>,\n commit: () => void,\n): Promise<void> {\n if (host.status.state === 'disposed') {\n throw new HostAssemblyError(\n 'host-assembly-service-unavailable',\n 'frontend host to remain active while activating an assembly',\n 'Create a new frontend host for the next browser connection.',\n { service: 'host-assembly' },\n );\n }\n const checked = validateHostAssembly(next);\n if (!checked.ok) {\n await report({ state: 'failed', revision: next.revision, error: checked.error });\n throw checked.error;\n }\n const activeLoader = getLoader();\n try {\n if (activeLoader !== undefined)\n assertModuleReloadBoundary(host.assembly.current, checked.value);\n await report({ state: 'loading', revision: next.revision });\n assertModuleVersions(checked.value, options.moduleVersions);\n let loader = activeLoader;\n if (loader === undefined) {\n const catalog = catalogForAssembly(checked.value, options.catalog);\n const installed = await installCatalogLoader(host.context, catalog, realm);\n loader = installed.loader;\n setLoader(installed);\n }\n const entries = projectPluginEntries(checked.value.entries, realm, realm);\n await loader.root.update(entries);\n await loader.await();\n const actualEntries = readiness(loader);\n assertReady(actualEntries);\n commit();\n await report({ state: 'active', revision: checked.value.revision, entries: actualEntries });\n } catch (error) {\n if (error instanceof HostAssemblyError && error.code === 'host-assembly-reload-required') {\n // The old Loader and its active Fibers are still authoritative. Do not\n // publish a failed status for the candidate revision or disguise a\n // required page reload as an in-place activation failure.\n throw error;\n }\n const activeLoader = getLoader();\n const actualEntries = activeLoader === undefined ? undefined : readiness(activeLoader);\n await report({\n state: 'failed',\n revision: next.revision,\n ...(actualEntries === undefined ? {} : { entries: actualEntries }),\n error,\n });\n throw error;\n }\n}\n\nexport { HostAssemblyError };\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/protocol.ts","../src/startup.ts","../src/transport.ts","../src/frontend.ts"],"names":["Context","report","host","activeLoader"],"mappings":";;;;;;AAoBO,IAAM,4BAAA,GAA+B,CAAA;AAiHrC,IAAM,iBAAA,GAAN,cAEG,KAAA,CAAM;AAAA,EACL,IAAA;AAAA,EACA,QAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EAET,WAAA,CAAY,IAAA,EAAS,QAAA,EAAkB,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A,MAAM,MAAA,CAAO;AAAA,MACX,KAAA,EAAO,QAAA;AAAA,MACP,UAAU,IAAA,CAAK,QAAA;AAAA,MACf,GAAI,aAAA,KAAkB,MAAA,GAAY,EAAC,GAAI,EAAE,SAAS,aAAA,EAAc;AAAA,MAChE;AAAA,KACD,CAAA;AACD,IAAA,MAAM,KAAA;AAAA,EACR;AACF","file":"frontend.mjs","sourcesContent":["import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader';\nimport type {\n GamePluginEntry,\n PluginCatalog,\n PluginCatalogRecord,\n PluginRealm,\n} from '@forgeax/engine-plugin/loader';\n\ndeclare module '@forgeax/engine-plugin' {\n interface EngineContextServices {\n hostAssembly:\n | import('./backend.js').BackendAssemblyAuthority\n | import('./frontend.js').FrontendAssemblyState;\n hostTransport:\n | import('./transport.js').HostTransportServer\n | import('./transport.js').HostTransportClient;\n }\n}\n\n/** Wire version for the backend-derived browser assembly. */\nexport const HOST_ASSEMBLY_SCHEMA_VERSION = 1 as const;\n\nexport type HostAssemblySchemaVersion = typeof HOST_ASSEMBLY_SCHEMA_VERSION;\n\nexport interface HostModuleDescriptor {\n /** The exact module name used by a Cordis Entry. */\n readonly name: string;\n /** Physical ForgeaX realm expected by the CatalogLoader. */\n readonly realm: PluginRealm;\n /** Code identity. The backend and browser must agree on this value. */\n readonly version: string;\n /** Optional content identity for a static or generated catalog. */\n readonly digest?: string;\n /** URL used by a live browser host. Static builds omit it and use a Catalog. */\n readonly url?: string;\n}\n\n/** One package's explicitly paired backend/frontend Entry projections. */\nexport interface HostPluginPair {\n readonly id: string;\n readonly backend?: HostPluginEndpoint;\n readonly frontend?: HostPluginEndpoint;\n}\n\nexport interface HostPluginEndpoint {\n readonly entry: GamePluginEntry;\n readonly module: HostModuleDescriptor;\n}\n\n/** Safe identity projection; backend Entry configuration never crosses the wire. */\nexport interface HostAssemblyPair {\n readonly id: string;\n readonly entryId: string;\n readonly module: HostModuleDescriptor;\n}\n\n/**\n * A serializable projection of the entries that a frontend may activate.\n * `EntryOptions` is intentionally retained so nested Groups and repeated Entry\n * instances keep native Loader identity and reconciliation semantics.\n */\nexport interface HostAssembly {\n readonly schemaVersion: HostAssemblySchemaVersion;\n /** Digest of entries, modules and explicitly projected configuration. */\n readonly revision: string;\n readonly entries: readonly GamePluginEntry[];\n readonly modules: readonly HostModuleDescriptor[];\n readonly pairs: readonly HostAssemblyPair[];\n /** Safe, frontend-visible configuration only. */\n readonly config?: unknown;\n}\n\nexport interface HostAssemblyInput {\n /** Backend Entries are local authority and are never serialized. */\n readonly backendEntries?: readonly GamePluginEntry[];\n readonly entries?: readonly GamePluginEntry[];\n readonly modules?: readonly HostModuleDescriptor[];\n readonly pairs?: readonly HostPluginPair[];\n readonly config?: unknown;\n}\n\nexport interface HostActivationEntry {\n readonly entryId: string;\n readonly fiberState: string;\n readonly failure?: HostErrorSummary;\n}\n\nexport interface HostErrorSummary {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: Readonly<Record<string, unknown>>;\n}\n\nexport interface HostActivationReport {\n readonly state: 'created' | 'loading' | 'active' | 'failed' | 'disposed';\n readonly revision: string;\n readonly entries?: readonly HostActivationEntry[];\n readonly error?: HostErrorSummary;\n}\n\nexport interface HostAssemblyErrorDetailByCode {\n 'host-assembly-invalid': { readonly reason: string };\n 'host-assembly-revision-mismatch': { readonly actual: string; readonly expected: string };\n 'host-assembly-module-missing': { readonly name: string };\n 'host-assembly-module-version-mismatch': {\n readonly name: string;\n readonly actual: string;\n readonly expected: string;\n };\n 'host-assembly-reload-required': {\n readonly module: string;\n readonly actual: string;\n readonly expected: string;\n };\n 'host-assembly-service-unavailable': { readonly service: string };\n 'host-assembly-stale-request': { readonly service: string; readonly generation: number };\n 'host-assembly-request-aborted': { readonly service: string };\n 'host-transport-failure': {\n readonly service: string;\n readonly reason: string;\n /** Business error code received from a remote host service, if any. */\n readonly remoteCode?: string;\n };\n 'host-assembly-not-ready': {\n readonly entryId: string;\n readonly fiberState: string;\n readonly failure?: HostErrorSummary;\n };\n}\n\nexport type HostAssemblyErrorCode = keyof HostAssemblyErrorDetailByCode;\n\nexport class HostAssemblyError<\n C extends HostAssemblyErrorCode = HostAssemblyErrorCode,\n> extends Error {\n readonly code: C;\n readonly expected: string;\n readonly hint: string;\n readonly detail: HostAssemblyErrorDetailByCode[C];\n\n constructor(code: C, expected: string, hint: string, detail: HostAssemblyErrorDetailByCode[C]) {\n super(`${code}: ${expected}`);\n this.name = 'HostAssemblyError';\n this.code = code;\n this.expected = expected;\n this.hint = hint;\n this.detail = detail;\n }\n}\n\n/**\n * Prove that the code selected by a local Catalog is the code named by an\n * assembly descriptor. An optional digest is still checked whenever either\n * side supplies one; an unrelated digest must never stand in for a version.\n */\nexport function assertHostModuleCatalogIdentity(\n module: HostModuleDescriptor,\n record: PluginCatalogRecord,\n): void {\n if (record.version !== undefined && record.version !== module.version) {\n throw new HostAssemblyError(\n 'host-assembly-module-version-mismatch',\n `module ${module.name} to load catalog version ${module.version}`,\n 'Regenerate the static Catalog from the same backend package revision.',\n { name: module.name, actual: record.version, expected: module.version },\n );\n }\n if (\n record.digest !== undefined &&\n module.digest !== undefined &&\n record.digest !== module.digest\n ) {\n throw new HostAssemblyError(\n 'host-assembly-module-version-mismatch',\n `module ${module.name} to load catalog digest ${module.digest ?? 'none'}`,\n 'Regenerate the static Catalog from the same backend package bytes.',\n { name: module.name, actual: record.digest, expected: module.digest ?? 'none' },\n );\n }\n const versionMatches = record.version !== undefined && record.version === module.version;\n const digestMatches =\n module.digest !== undefined && record.digest !== undefined && record.digest === module.digest;\n const staticWithoutIdentity =\n module.version === 'static' &&\n module.digest === undefined &&\n record.version === undefined &&\n record.digest === undefined;\n if (!versionMatches && !digestMatches && !staticWithoutIdentity) {\n throw new HostAssemblyError(\n 'host-assembly-module-version-mismatch',\n `module ${module.name} to have a matching catalog code identity for ${module.version}`,\n 'Add the generated module version or digest to the static Catalog.',\n {\n name: module.name,\n actual: record.version ?? record.digest ?? 'unknown',\n expected: module.version,\n },\n );\n }\n}\n\nexport interface HostAssemblyResult {\n readonly ok: true;\n readonly value: HostAssembly;\n}\n\nexport interface HostAssemblyFailure {\n readonly ok: false;\n readonly error: HostAssemblyError;\n}\n\nexport type HostAssemblyValidation = HostAssemblyResult | HostAssemblyFailure;\n\n/** JSON-stable projection used for revision identity and diagnostics. */\nexport function canonicalHostJson(value: unknown): string {\n if (value === undefined) return 'undefined';\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(canonicalHostJson).join(',')}]`;\n return `{${Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, item]) => `${JSON.stringify(key)}:${canonicalHostJson(item)}`)\n .join(',')}}`;\n}\n\n/** Small deterministic digest; it is an identity check, not a security hash. */\nexport function hostRevision(value: unknown): string {\n let hash = 2166136261;\n for (const char of canonicalHostJson(value)) {\n hash ^= char.codePointAt(0) ?? 0;\n hash = Math.imul(hash, 16777619);\n }\n return `fnv1a:${(hash >>> 0).toString(16).padStart(8, '0')}`;\n}\n\nfunction cloneEntry(entry: GamePluginEntry): GamePluginEntry {\n const config = entry.group\n ? (entry.config as readonly GamePluginEntry[] | undefined)?.map(cloneEntry)\n : entry.config;\n return {\n id: entry.id,\n name: entry.name,\n ...(config === undefined ? {} : { config }),\n ...(entry.group === undefined ? {} : { group: entry.group }),\n ...(entry.disabled === undefined ? {} : { disabled: entry.disabled }),\n ...(entry.inject === undefined ? {} : { inject: entry.inject }),\n ...(entry.realm === undefined ? {} : { realm: entry.realm }),\n };\n}\n\nfunction projectPairs(pairs: readonly HostPluginPair[]): {\n readonly entries: readonly GamePluginEntry[];\n readonly modules: readonly HostModuleDescriptor[];\n readonly projections: readonly HostAssemblyPair[];\n} {\n const entries: GamePluginEntry[] = [];\n const modules: HostModuleDescriptor[] = [];\n const projections: HostAssemblyPair[] = [];\n for (const pair of pairs) {\n if (\n pair.backend !== undefined &&\n pair.frontend !== undefined &&\n pair.backend.module.version !== pair.frontend.module.version\n ) {\n throw new HostAssemblyError(\n 'host-assembly-module-version-mismatch',\n `paired module ${pair.id} to use one code version on both hosts`,\n 'Resolve backend and frontend package entries from the same locked package revision.',\n {\n name: pair.id,\n actual: pair.backend.module.version,\n expected: pair.frontend.module.version,\n },\n );\n }\n if (pair.frontend === undefined) continue;\n entries.push(pair.frontend.entry);\n modules.push(pair.frontend.module);\n projections.push({\n id: pair.id,\n entryId: pair.frontend.entry.id,\n module: pair.frontend.module,\n });\n }\n return { entries, modules, projections };\n}\n\nfunction assemblyPairsFromInput(input: HostAssemblyInput): {\n readonly entries: readonly GamePluginEntry[];\n readonly modules: readonly HostModuleDescriptor[];\n readonly pairs: readonly HostAssemblyPair[];\n} {\n if (input.pairs !== undefined) {\n const projected = projectPairs(input.pairs);\n return {\n entries: input.entries ?? projected.entries,\n modules: input.modules ?? projected.modules,\n pairs: projected.projections,\n };\n }\n const entries = input.entries ?? [];\n const modules = [...(input.modules ?? [])];\n for (const [index, entry] of entries.entries()) {\n if (modules[index] !== undefined || modules.some((module) => module.name === entry.name))\n continue;\n modules.push({\n name: entry.name,\n realm: entry.realm ?? 'engine',\n version: 'unknown',\n });\n }\n return {\n entries,\n modules,\n pairs: entries.map((entry, index) => ({\n id: entry.id,\n entryId: entry.id,\n module:\n modules[index]?.name === entry.name\n ? modules[index]\n : (modules.find((module) => module.name === entry.name) ?? {\n name: entry.name,\n realm: entry.realm ?? 'engine',\n version: 'unknown',\n }),\n })),\n };\n}\n\n/** Build one disposable assembly projection from effective backend inputs. */\nexport function createHostAssembly(input: HostAssemblyInput): HostAssembly {\n const projected = assemblyPairsFromInput(input);\n const entries = projected.entries.map(cloneEntry);\n const modules = projected.modules.map((module) => ({ ...module }));\n const pairs = projected.pairs.map((pair) => ({ ...pair, module: { ...pair.module } }));\n const identity = {\n schemaVersion: HOST_ASSEMBLY_SCHEMA_VERSION,\n entries,\n modules,\n pairs,\n ...(input.config === undefined ? {} : { config: input.config }),\n };\n return {\n ...identity,\n revision: hostRevision(identity),\n };\n}\n\nfunction validateEntry(entry: EntryOptions, path: string): string | undefined {\n if (entry === null || typeof entry !== 'object') return `${path} must be an Entry object`;\n if (typeof entry.id !== 'string' || entry.id.length === 0) return `${path}.id must be non-empty`;\n if (typeof entry.name !== 'string' || entry.name.length === 0)\n return `${path}.name must be non-empty`;\n if (entry.group === true) {\n if (!Array.isArray(entry.config)) return `${path}.config must be an Entry array for a Group`;\n for (const [index, child] of entry.config.entries()) {\n const reason = validateEntry(child as EntryOptions, `${path}.config[${index}]`);\n if (reason !== undefined) return reason;\n }\n }\n return undefined;\n}\n\n/** Validate a received assembly before touching the native Loader. */\nexport function validateHostAssembly(assembly: HostAssembly): HostAssemblyValidation {\n if (assembly === null || typeof assembly !== 'object') {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'assembly to be an object',\n 'Regenerate the frontend assembly from the active backend authority.',\n { reason: 'assembly is not an object' },\n ),\n };\n }\n if (assembly.schemaVersion !== HOST_ASSEMBLY_SCHEMA_VERSION) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n `assembly schema ${HOST_ASSEMBLY_SCHEMA_VERSION}`,\n 'Regenerate the frontend assembly with the matching Engine host package.',\n { reason: `unsupported schema ${String(assembly.schemaVersion)}` },\n ),\n };\n }\n if (!Array.isArray(assembly.entries) || !Array.isArray(assembly.modules)) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'assembly entries and modules to be arrays',\n 'Regenerate the frontend assembly from the active backend authority.',\n { reason: 'entries or modules is not an array' },\n ),\n };\n }\n if (!Array.isArray(assembly.pairs)) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'assembly pairs to be an array',\n 'Regenerate the assembly from the backend host using the matching host package.',\n { reason: 'pairs is not an array' },\n ),\n };\n }\n const seen = new Set<string>();\n for (const [index, entry] of assembly.entries.entries()) {\n const reason = validateEntry(entry, `entries[${index}]`);\n if (reason !== undefined) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'all assembly entries to be valid native EntryOptions',\n 'Repair the backend Entry projection before publishing it to a browser.',\n { reason },\n ),\n };\n }\n if (seen.has(entry.id)) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'assembly Entry ids to be unique',\n 'Give repeated plugin instances independent stable ids.',\n { reason: `duplicate Entry id ${entry.id}` },\n ),\n };\n }\n seen.add(entry.id);\n }\n const seenModules = new Map<string, HostModuleDescriptor>();\n for (const [index, module] of assembly.modules.entries()) {\n if (\n module === null ||\n typeof module !== 'object' ||\n typeof module.name !== 'string' ||\n typeof module.realm !== 'string' ||\n typeof module.version !== 'string' ||\n module.name.length === 0 ||\n module.version.length === 0 ||\n (module.url !== undefined && typeof module.url !== 'string') ||\n (module.digest !== undefined &&\n (typeof module.digest !== 'string' || module.digest.length === 0))\n ) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'module names and versions to be non-empty',\n 'Regenerate the module projection from the resolved package metadata.',\n { reason: `invalid module at index ${index}` },\n ),\n };\n }\n const previousModule = seenModules.get(module.name);\n if (\n previousModule !== undefined &&\n (previousModule.realm !== module.realm ||\n previousModule.version !== module.version ||\n previousModule.url !== module.url ||\n previousModule.digest !== module.digest)\n ) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'assembly module identity to be consistent for repeated Entries',\n 'Reuse one resolved module identity when a package has multiple Entry instances.',\n { reason: `module ${module.name} has conflicting identities` },\n ),\n };\n }\n seenModules.set(module.name, module);\n }\n const seenPairIds = new Set<string>();\n for (const [index, pair] of assembly.pairs.entries()) {\n const pairModule = pair?.module;\n if (\n pair === null ||\n typeof pair !== 'object' ||\n typeof pair.id !== 'string' ||\n pair.id.length === 0 ||\n typeof pair.entryId !== 'string' ||\n pair.entryId.length === 0 ||\n pairModule === null ||\n pairModule === undefined ||\n typeof pairModule !== 'object' ||\n typeof pairModule.name !== 'string' ||\n typeof pairModule.realm !== 'string' ||\n typeof pairModule.version !== 'string' ||\n pairModule.name.length === 0 ||\n pairModule.version.length === 0 ||\n (pairModule.url !== undefined && typeof pairModule.url !== 'string') ||\n (pairModule.digest !== undefined &&\n (typeof pairModule.digest !== 'string' || pairModule.digest.length === 0))\n ) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'assembly pair identities and modules to be valid',\n 'Regenerate paired frontend entries from the backend package manifest.',\n { reason: `invalid pair at index ${index}` },\n ),\n };\n }\n if (seenPairIds.has(pair.id)) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n 'assembly pair ids to be unique',\n 'Give each paired package instance an independent stable id.',\n { reason: `duplicate pair ${pair.id}` },\n ),\n };\n }\n seenPairIds.add(pair.id);\n if (!assembly.entries.some((entry) => entry.id === pair.entryId)) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n `pair ${pair.id} to reference an assembly Entry`,\n 'Keep paired identity and frontend Entry projection under one backend authority.',\n { reason: `missing frontend Entry ${pair.entryId}` },\n ),\n };\n }\n const module = assembly.modules.find(\n (candidate) =>\n candidate.name === pairModule.name &&\n candidate.realm === pairModule.realm &&\n candidate.version === pairModule.version &&\n candidate.url === pairModule.url &&\n candidate.digest === pairModule.digest,\n );\n if (module === undefined) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-invalid',\n `pair ${pair.id} to reference a resolved frontend module`,\n 'Keep module/code identity in the backend-derived assembly projection.',\n { reason: `missing frontend module ${pairModule.name}` },\n ),\n };\n }\n }\n const expected = hostRevision({\n schemaVersion: assembly.schemaVersion,\n entries: assembly.entries,\n modules: assembly.modules,\n pairs: assembly.pairs,\n ...(assembly.config === undefined ? {} : { config: assembly.config }),\n });\n if (expected !== assembly.revision) {\n return {\n ok: false,\n error: new HostAssemblyError(\n 'host-assembly-revision-mismatch',\n 'assembly revision to match its entries and modules',\n 'Discard the stale response and request the current backend assembly again.',\n { actual: assembly.revision, expected },\n ),\n };\n }\n return { ok: true, value: assembly };\n}\n\n/** Derive a static module descriptor set from an existing native Catalog. */\nexport function modulesFromCatalog(\n catalog: PluginCatalog,\n realm: PluginRealm,\n version = 'static',\n): HostModuleDescriptor[] {\n return [...catalog.entries()]\n .filter(([, record]) => record.realm === realm)\n .map(([name, record]) => ({\n name,\n realm,\n version: record.version ?? version,\n ...(record.digest === undefined ? {} : { digest: record.digest }),\n }));\n}\n","import { Context, type Fiber, type Plugin } from '@forgeax/engine-plugin';\n\n/**\n * The product-neutral host bootstrap. It owns only a Cordis Context and the\n * supplied startup entries; assembly, transport, Project, and App are all\n * ordinary plugins layered above this seam.\n */\nexport interface HostStartupOptions {\n readonly context?: Context;\n readonly startupPlugins?: readonly Plugin[];\n}\n\nexport interface HostStartup {\n readonly context: Context;\n readonly ownedContext: boolean;\n readonly fibers: readonly Fiber[];\n dispose(): Promise<void>;\n}\n\nexport async function createHostStartup(options: HostStartupOptions = {}): Promise<HostStartup> {\n const context = options.context ?? new Context();\n const ownedContext = options.context === undefined;\n const fibers: Fiber[] = [];\n let disposed = false;\n try {\n for (const plugin of options.startupPlugins ?? []) fibers.push(await context.plugin(plugin));\n } catch (error) {\n for (const fiber of fibers.reverse()) await fiber.dispose();\n if (ownedContext) await context.fiber.dispose();\n throw error;\n }\n return {\n context,\n ownedContext,\n fibers,\n async dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n for (const fiber of [...fibers].reverse()) await fiber.dispose();\n if (ownedContext) await context.fiber.dispose();\n },\n };\n}\n","import { HostAssemblyError, type HostErrorSummary } from './protocol.js';\n\nexport const HOST_ASSEMBLY_SERVICE = 'host/assembly.get' as const;\nexport const HOST_ACTIVATION_REPORT_SERVICE = 'host/assembly.report' as const;\nexport const HOST_ASSEMBLY_CHANGED_TOPIC = 'host/assembly.changed' as const;\n\nexport interface HostRequestOptions {\n readonly signal?: AbortSignal;\n /** The service generation observed by the caller. */\n readonly generation?: number;\n}\n\nexport interface HostServiceRequest<T = unknown> {\n readonly service: string;\n readonly payload: T;\n readonly generation: number;\n readonly signal: AbortSignal;\n}\n\nexport type HostServiceHandler<TPayload = unknown, TResult = unknown> = (\n request: HostServiceRequest<TPayload>,\n) => Promise<TResult> | TResult;\n\nexport interface HostServiceSnapshot {\n readonly service: string;\n readonly generation: number;\n}\n\nexport interface HostTransportClient {\n readonly connected: boolean;\n readonly generation: number;\n request<TPayload, TResult>(\n service: string,\n payload: TPayload,\n options?: HostRequestOptions,\n ): Promise<TResult>;\n subscribe<T>(topic: string, listener: (payload: T) => void): () => void;\n /** Observe a terminal connection loss without issuing another request. */\n onDisconnect(listener: (error: HostAssemblyError) => void): () => void;\n close(reason?: unknown): void;\n}\n\nexport interface HostTransportServer {\n readonly connectedClients: number;\n register<TPayload, TResult>(\n service: string,\n handler: HostServiceHandler<TPayload, TResult>,\n ): () => void;\n invalidate(service: string): void;\n snapshot(service: string): HostServiceSnapshot | undefined;\n publish<T>(topic: string, payload: T): void;\n connect(): HostTransportClient;\n close(reason?: unknown): void;\n}\n\ninterface ServiceRecord {\n readonly identity: symbol;\n generation: number;\n handler: (request: HostServiceRequest<unknown>) => Promise<unknown> | unknown;\n pending: Set<AbortController>;\n}\n\ninterface ClientState {\n connected: boolean;\n readonly subscriptions: Map<string, Set<(payload: unknown) => void>>;\n readonly pending: Set<AbortController>;\n readonly disconnectListeners: Set<(error: HostAssemblyError) => void>;\n}\n\n/**\n * Create the small typed transport seam used by host plugins.\n *\n * This implementation is deliberately transport-neutral: the same request,\n * subscription, cancellation, and generation semantics can be adapted to a\n * WebSocket or MessagePort without moving business objects across the wire.\n * It is also useful for deterministic host and lifecycle tests.\n */\nexport function createHostTransport(): HostTransportServer {\n const services = new Map<string, ServiceRecord>();\n const generations = new Map<string, number>();\n const clients = new Set<ClientState>();\n let closed = false;\n\n const closeClient = (state: ClientState, reason?: unknown): void => {\n if (!state.connected) return;\n state.connected = false;\n for (const controller of state.pending) controller.abort();\n state.pending.clear();\n for (const callbacks of state.subscriptions.values()) callbacks.clear();\n state.subscriptions.clear();\n clients.delete(state);\n const error = new HostAssemblyError(\n 'host-transport-failure',\n 'the host connection to remain available',\n 'Reconnect the frontend host before issuing another request.',\n { service: 'host/socket', reason: String(reason ?? 'host connection closed') },\n );\n for (const listener of state.disconnectListeners) listener(error);\n state.disconnectListeners.clear();\n };\n\n const server: HostTransportServer = {\n get connectedClients() {\n return clients.size;\n },\n register(service, handler) {\n if (closed) throw new Error('host transport is closed');\n const previous = services.get(service);\n const generation = (generations.get(service) ?? 0) + 1;\n generations.set(service, generation);\n for (const controller of previous?.pending ?? []) controller.abort();\n const identity = Symbol(service);\n services.set(service, {\n identity,\n generation,\n handler: handler as unknown as (\n request: HostServiceRequest<unknown>,\n ) => Promise<unknown> | unknown,\n pending: new Set(),\n });\n return () => {\n const current = services.get(service);\n if (current?.identity !== identity) return;\n for (const controller of current.pending) controller.abort();\n generations.set(service, current.generation + 1);\n services.delete(service);\n };\n },\n invalidate(service) {\n const current = services.get(service);\n if (current === undefined) return;\n for (const controller of current.pending) controller.abort();\n generations.set(service, current.generation + 1);\n services.delete(service);\n },\n snapshot(service) {\n const current = services.get(service);\n return current === undefined ? undefined : { service, generation: current.generation };\n },\n publish(topic, payload) {\n for (const state of clients) {\n for (const listener of state.subscriptions.get(topic) ?? []) listener(payload);\n }\n },\n connect() {\n if (closed) throw new Error('host transport is closed');\n const state: ClientState = {\n connected: true,\n subscriptions: new Map(),\n pending: new Set(),\n disconnectListeners: new Set(),\n };\n clients.add(state);\n const client: HostTransportClient = {\n get connected() {\n return state.connected;\n },\n get generation() {\n let current = 0;\n for (const service of services.values()) current = Math.max(current, service.generation);\n return current;\n },\n async request(service, payload, options = {}) {\n if (!state.connected) {\n throw new HostAssemblyError(\n 'host-assembly-service-unavailable',\n `service ${service} to be available on the current connection`,\n 'Reconnect the frontend host before issuing another request.',\n { service },\n );\n }\n if (options.signal?.aborted) {\n throw new HostAssemblyError(\n 'host-assembly-request-aborted',\n `request ${service} to start with a live AbortSignal`,\n 'Start a fresh request with a live AbortSignal.',\n { service },\n );\n }\n const record = services.get(service);\n if (record === undefined) {\n const invalidatedGeneration = generations.get(service);\n if (\n options.generation !== undefined &&\n invalidatedGeneration !== undefined &&\n options.generation < invalidatedGeneration\n ) {\n throw new HostAssemblyError(\n 'host-assembly-stale-request',\n `request generation ${options.generation} to match the invalidated service ${service}`,\n 'Refresh the client capability after the backend service is enabled again.',\n { service, generation: options.generation },\n );\n }\n throw new HostAssemblyError(\n 'host-assembly-service-unavailable',\n `service ${service} to be registered`,\n 'Wait for the backend plugin to activate before using this capability.',\n { service },\n );\n }\n const generation = options.generation ?? record.generation;\n if (generation !== record.generation) {\n throw new HostAssemblyError(\n 'host-assembly-stale-request',\n `request generation ${generation} to match service ${service}`,\n 'Refresh the client capability and retry only when the owning business contract permits it.',\n { service, generation },\n );\n }\n const controller = new AbortController();\n const abortFromCaller = (): void => controller.abort();\n options.signal?.addEventListener('abort', abortFromCaller, { once: true });\n record.pending.add(controller);\n state.pending.add(controller);\n let removeAbortRequest: (() => void) | undefined;\n try {\n if (controller.signal.aborted) {\n throw new HostAssemblyError(\n 'host-assembly-request-aborted',\n `request ${service} not to be aborted before execution`,\n 'Start a fresh request with a live AbortSignal.',\n { service },\n );\n }\n let abortReject: ((reason: unknown) => void) | undefined;\n const aborted = new Promise<never>((_, reject) => {\n abortReject = reject;\n });\n const abortRequest = (): void => {\n abortReject?.(\n new HostAssemblyError(\n 'host-assembly-request-aborted',\n `request ${service} to finish before its service is closed or invalidated`,\n 'Treat the capability as withdrawn and refresh the service before retrying.',\n { service },\n ),\n );\n };\n controller.signal.addEventListener('abort', abortRequest, { once: true });\n removeAbortRequest = () => controller.signal.removeEventListener('abort', abortRequest);\n const result = await Promise.race([\n Promise.resolve(\n record.handler({\n service,\n payload,\n generation,\n signal: controller.signal,\n }),\n ),\n aborted,\n ]);\n if (controller.signal.aborted) {\n throw new HostAssemblyError(\n 'host-assembly-request-aborted',\n `request ${service} to finish before its service is invalidated`,\n 'Treat the capability as withdrawn and refresh the service before retrying.',\n { service },\n );\n }\n return result as never;\n } finally {\n removeAbortRequest?.();\n record.pending.delete(controller);\n state.pending.delete(controller);\n options.signal?.removeEventListener('abort', abortFromCaller);\n }\n },\n subscribe(topic, listener) {\n if (!state.connected) return () => {};\n const callbacks = state.subscriptions.get(topic) ?? new Set();\n callbacks.add(listener as (payload: unknown) => void);\n state.subscriptions.set(topic, callbacks);\n return () => {\n callbacks.delete(listener as (payload: unknown) => void);\n if (callbacks.size === 0) state.subscriptions.delete(topic);\n };\n },\n onDisconnect(listener) {\n if (!state.connected) {\n listener(\n new HostAssemblyError(\n 'host-transport-failure',\n 'the host connection to remain available',\n 'Reconnect the frontend host before issuing another request.',\n { service: 'host/socket', reason: 'host connection is already closed' },\n ),\n );\n return () => {};\n }\n state.disconnectListeners.add(listener);\n return () => state.disconnectListeners.delete(listener);\n },\n close(reason) {\n closeClient(state, reason);\n },\n };\n return client;\n },\n close(reason) {\n if (closed) return;\n closed = true;\n for (const service of services.values())\n for (const controller of service.pending) controller.abort();\n services.clear();\n for (const client of [...clients]) closeClient(client, reason);\n generations.clear();\n },\n };\n\n return server;\n}\n\n/** Minimal socket shape shared by browser WebSocket and Node `ws` instances. */\nexport interface HostSocketLike {\n readonly readyState?: number;\n send(data: string): void;\n close(code?: number, reason?: string): void;\n addEventListener?(type: string, listener: (...args: unknown[]) => void): void;\n removeEventListener?(type: string, listener: (...args: unknown[]) => void): void;\n on?(type: string, listener: (...args: unknown[]) => void): void;\n off?(type: string, listener: (...args: unknown[]) => void): void;\n}\n\ntype HostWireMessage =\n | {\n readonly kind: 'request';\n readonly id: string;\n readonly service: string;\n readonly payload: unknown;\n readonly generation?: number;\n }\n | { readonly kind: 'cancel'; readonly id: string }\n | { readonly kind: 'subscribe'; readonly topic: string }\n | { readonly kind: 'unsubscribe'; readonly topic: string }\n | {\n readonly kind: 'response';\n readonly id: string;\n readonly ok: boolean;\n readonly value?: unknown;\n readonly error?: HostErrorSummary;\n readonly generation?: number;\n }\n | { readonly kind: 'event'; readonly topic: string; readonly payload: unknown };\n\nfunction addSocketListener(\n socket: HostSocketLike,\n type: string,\n listener: (...args: unknown[]) => void,\n): () => void {\n if (socket.addEventListener !== undefined) {\n socket.addEventListener(type, listener);\n return () => socket.removeEventListener?.(type, listener);\n }\n socket.on?.(type, listener);\n return () => socket.off?.(type, listener);\n}\n\nfunction socketPayload(value: unknown): string | undefined {\n const data = Array.isArray(value) ? value[0] : value;\n if (typeof data === 'string') return data;\n if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);\n if (data instanceof Uint8Array) return new TextDecoder().decode(data);\n if (data !== null && typeof data === 'object' && 'data' in data)\n return socketPayload((data as { readonly data?: unknown }).data);\n return undefined;\n}\n\nfunction parseWire(value: unknown): HostWireMessage | undefined {\n const source = socketPayload(value);\n if (source === undefined) return undefined;\n try {\n const parsed = JSON.parse(source) as unknown;\n return parsed !== null &&\n typeof parsed === 'object' &&\n typeof (parsed as { kind?: unknown }).kind === 'string'\n ? (parsed as HostWireMessage)\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction serializeError(service: string, error: unknown): HostErrorSummary {\n if (\n error !== null &&\n typeof error === 'object' &&\n typeof (error as { code?: unknown }).code === 'string' &&\n typeof (error as { expected?: unknown }).expected === 'string' &&\n typeof (error as { hint?: unknown }).hint === 'string'\n ) {\n const detail = (error as { readonly detail?: unknown }).detail;\n return {\n code: (error as { readonly code: string }).code,\n expected: (error as { readonly expected: string }).expected,\n hint: (error as { readonly hint: string }).hint,\n detail:\n detail !== null && typeof detail === 'object'\n ? (detail as Readonly<Record<string, unknown>>)\n : { reason: String(detail ?? 'unknown failure') },\n };\n }\n return {\n code: 'host-transport-failure',\n expected: `service ${service} to complete without an exception`,\n hint: 'Inspect the backend host process and reconnect before retrying.',\n detail: { service, reason: error instanceof Error ? error.message : String(error) },\n };\n}\n\nfunction errorFromSummary(service: string, summary: HostErrorSummary): HostAssemblyError {\n const detail = summary.detail as Record<string, unknown>;\n const supported = new Set([\n 'host-assembly-invalid',\n 'host-assembly-revision-mismatch',\n 'host-assembly-module-missing',\n 'host-assembly-module-version-mismatch',\n 'host-assembly-reload-required',\n 'host-assembly-service-unavailable',\n 'host-assembly-stale-request',\n 'host-assembly-request-aborted',\n 'host-assembly-not-ready',\n 'host-transport-failure',\n ]);\n if (supported.has(summary.code)) {\n return new HostAssemblyError(\n summary.code as never,\n summary.expected,\n summary.hint,\n detail as never,\n );\n }\n return new HostAssemblyError('host-transport-failure', summary.expected, summary.hint, {\n ...detail,\n service,\n reason: summary.detail.reason ? String(summary.detail.reason) : summary.code,\n remoteCode: summary.code,\n });\n}\n\nfunction transportFailure(service: string, reason: string): HostAssemblyError {\n return new HostAssemblyError(\n 'host-transport-failure',\n `service ${service} to remain connected`,\n 'Reconnect the frontend host and inspect the backend transport diagnostics.',\n { service, reason },\n );\n}\n\nfunction sendWire(socket: HostSocketLike, message: HostWireMessage): void {\n socket.send(JSON.stringify(message));\n}\n\n/** Connect one browser WebSocket (or an already-open Node `ws`) to a host server. */\nexport async function createHostWebSocketClient(\n socket: HostSocketLike,\n): Promise<HostTransportClient> {\n if (socket.readyState !== undefined && socket.readyState !== 1) {\n await new Promise<void>((resolve, reject) => {\n const removeOpen = addSocketListener(socket, 'open', () => {\n removeOpen();\n removeError();\n resolve();\n });\n const removeError = addSocketListener(socket, 'error', (cause) => {\n removeOpen();\n removeError();\n reject(transportFailure('host/connect', String(cause ?? 'socket error')));\n });\n });\n }\n const pending = new Map<\n string,\n {\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n readonly cleanup: () => void;\n }\n >();\n const subscriptions = new Map<string, Set<(payload: unknown) => void>>();\n const disconnectListeners = new Set<(error: HostAssemblyError) => void>();\n let connected = true;\n let generation = 0;\n let sequence = 0;\n const disconnectError = (reason: unknown): HostAssemblyError =>\n transportFailure('host/socket', reason instanceof Error ? reason.message : String(reason));\n const failPending = (reason: unknown): void => {\n if (!connected) return;\n connected = false;\n for (const request of pending.values()) {\n request.cleanup();\n request.reject(reason);\n }\n pending.clear();\n subscriptions.clear();\n const error = disconnectError(reason);\n for (const listener of disconnectListeners) listener(error);\n disconnectListeners.clear();\n };\n const removeMessage = addSocketListener(socket, 'message', (event) => {\n const message = parseWire(event);\n if (message === undefined) return;\n if (message.kind === 'event') {\n for (const listener of subscriptions.get(message.topic) ?? []) listener(message.payload);\n return;\n }\n if (message.kind !== 'response') return;\n if (message.generation !== undefined) generation = Math.max(generation, message.generation);\n const request = pending.get(message.id);\n if (request === undefined) return;\n pending.delete(message.id);\n request.cleanup();\n if (message.ok) request.resolve(message.value);\n else\n request.reject(\n errorFromSummary(\n 'host/socket',\n message.error ?? serializeError('host/socket', 'unknown response failure'),\n ),\n );\n });\n const removeClose = addSocketListener(socket, 'close', (reason) => {\n removeMessage();\n removeClose();\n removeError();\n failPending(disconnectError(reason));\n });\n const removeError = addSocketListener(socket, 'error', (reason) => {\n failPending(disconnectError(reason));\n });\n const client: HostTransportClient = {\n get connected() {\n return connected;\n },\n get generation() {\n return generation;\n },\n request<TPayload, TResult>(\n service: string,\n payload: TPayload,\n options: HostRequestOptions = {},\n ): Promise<TResult> {\n if (!connected) return Promise.reject(disconnectError('socket is closed'));\n if (options.signal?.aborted)\n return Promise.reject(\n new HostAssemblyError(\n 'host-assembly-request-aborted',\n `request ${service} to start with a live AbortSignal`,\n 'Start a fresh request with a live AbortSignal.',\n { service },\n ),\n );\n sequence += 1;\n const id = `${Date.now().toString(36)}-${sequence.toString(36)}`;\n return new Promise<TResult>((resolve, reject) => {\n const abort = (): void => {\n const request = pending.get(id);\n if (request === undefined) return;\n pending.delete(id);\n request.cleanup();\n try {\n sendWire(socket, { kind: 'cancel', id });\n } catch {\n // The close/error listener reports the transport failure separately.\n }\n reject(\n new HostAssemblyError(\n 'host-assembly-request-aborted',\n `request ${service} to finish before cancellation`,\n 'Start a fresh request with a live AbortSignal.',\n { service },\n ),\n );\n };\n const cleanup = (): void => options.signal?.removeEventListener('abort', abort);\n pending.set(id, {\n resolve: resolve as unknown as (value: unknown) => void,\n reject,\n cleanup,\n });\n options.signal?.addEventListener('abort', abort, { once: true });\n if (options.signal?.aborted) {\n abort();\n return;\n }\n try {\n sendWire(socket, {\n kind: 'request',\n id,\n service,\n payload,\n ...(options.generation === undefined ? {} : { generation: options.generation }),\n });\n } catch (cause) {\n const request = pending.get(id);\n request?.cleanup();\n pending.delete(id);\n reject(disconnectError(cause));\n }\n });\n },\n subscribe(topic, listener) {\n if (!connected) return () => {};\n const listeners = subscriptions.get(topic) ?? new Set();\n listeners.add(listener as (payload: unknown) => void);\n subscriptions.set(topic, listeners);\n sendWire(socket, { kind: 'subscribe', topic });\n return () => {\n listeners.delete(listener as (payload: unknown) => void);\n if (listeners.size !== 0) return;\n subscriptions.delete(topic);\n sendWire(socket, { kind: 'unsubscribe', topic });\n };\n },\n onDisconnect(listener) {\n if (!connected) {\n listener(disconnectError('socket is already closed'));\n return () => {};\n }\n disconnectListeners.add(listener);\n return () => disconnectListeners.delete(listener);\n },\n close(reason) {\n if (!connected) return;\n failPending(disconnectError(reason ?? 'client closed the host connection'));\n removeMessage();\n removeClose();\n removeError();\n socket.close();\n },\n };\n return client;\n}\n\n/** Open a browser-native WebSocket and install the typed host client. */\nexport async function connectHostWebSocket(url: string): Promise<HostTransportClient> {\n const Constructor = globalThis.WebSocket;\n if (typeof Constructor !== 'function')\n throw transportFailure('host/connect', 'the current runtime does not provide WebSocket');\n return createHostWebSocketClient(new Constructor(url) as unknown as HostSocketLike);\n}\n\n/** Attach one accepted process-side socket to an Engine host transport server. */\nexport function attachHostWebSocketServer(\n socket: HostSocketLike,\n server: HostTransportServer,\n): () => void {\n const client = server.connect();\n const pending = new Map<string, AbortController>();\n const subscriptions = new Map<string, () => void>();\n let disposed = false;\n const removeMessage = addSocketListener(socket, 'message', (event) => {\n const message = parseWire(event);\n if (message === undefined || disposed) return;\n if (message.kind === 'cancel') {\n pending.get(message.id)?.abort();\n return;\n }\n if (message.kind === 'subscribe') {\n subscriptions.get(message.topic)?.();\n subscriptions.set(\n message.topic,\n client.subscribe(message.topic, (payload) => {\n if (!disposed) sendWire(socket, { kind: 'event', topic: message.topic, payload });\n }),\n );\n return;\n }\n if (message.kind === 'unsubscribe') {\n subscriptions.get(message.topic)?.();\n subscriptions.delete(message.topic);\n return;\n }\n if (message.kind !== 'request') return;\n const controller = new AbortController();\n pending.set(message.id, controller);\n void client\n .request(message.service, message.payload, {\n signal: controller.signal,\n ...(message.generation === undefined ? {} : { generation: message.generation }),\n })\n .then((value) => {\n if (!disposed)\n sendWire(socket, {\n kind: 'response',\n id: message.id,\n ok: true,\n value,\n generation: client.generation,\n });\n })\n .catch((error) => {\n if (!disposed)\n sendWire(socket, {\n kind: 'response',\n id: message.id,\n ok: false,\n error: serializeError(message.service, error),\n generation: client.generation,\n });\n })\n .finally(() => pending.delete(message.id));\n });\n const removeClose = addSocketListener(socket, 'close', () => dispose());\n const removeError = addSocketListener(socket, 'error', () => dispose());\n function dispose(): void {\n if (disposed) return;\n disposed = true;\n removeMessage();\n removeClose();\n removeError();\n for (const controller of pending.values()) controller.abort();\n pending.clear();\n for (const unsubscribe of subscriptions.values()) unsubscribe();\n subscriptions.clear();\n client.close('host socket disconnected');\n }\n return dispose;\n}\n","import { Context, type Fiber, inspectCatalogPlugins, type Plugin } from '@forgeax/engine-plugin';\nimport {\n type CatalogLoader,\n type GamePluginEntry,\n installCatalogLoader,\n type PluginCatalog,\n type PluginCatalogRecord,\n type PluginRealm,\n projectPluginEntries,\n} from '@forgeax/engine-plugin/loader';\nimport {\n assertHostModuleCatalogIdentity,\n createHostAssembly,\n type HostActivationEntry,\n type HostActivationReport,\n type HostAssembly,\n HostAssemblyError,\n type HostErrorSummary,\n modulesFromCatalog,\n validateHostAssembly,\n} from './protocol.js';\nimport { createHostStartup, type HostStartup } from './startup.js';\nimport {\n HOST_ACTIVATION_REPORT_SERVICE,\n HOST_ASSEMBLY_SERVICE,\n type HostTransportClient,\n} from './transport.js';\n\nexport type FrontendHostState = 'created' | 'loading' | 'active' | 'failed' | 'disposed';\n\nexport interface FrontendHostStatus {\n readonly state: FrontendHostState;\n readonly revision: string;\n readonly entries?: readonly HostActivationEntry[];\n readonly error?: unknown;\n}\n\nexport interface FrontendAssemblyState {\n readonly current: HostAssembly;\n readonly status: FrontendHostStatus;\n}\n\nexport interface FrontendHostOptions {\n /** App may provide its existing Engine Context; the host owns only its Fiber. */\n readonly context?: Context;\n readonly startupPlugins?: readonly Plugin[];\n readonly catalog?: PluginCatalog;\n /**\n * Optional local assembly snapshot used for the first staged activation.\n * When a transport is also present, the backend remains authoritative for\n * later updates; this snapshot lets callers activate provider-only entries\n * before their host-owned services are ready.\n */\n readonly assembly?: HostAssembly;\n readonly entries?: readonly GamePluginEntry[];\n readonly realm?: PluginRealm;\n readonly config?: unknown;\n readonly transport?: HostTransportClient;\n readonly moduleVersions?: ReadonlyMap<string, string>;\n readonly reportStatus?: (status: FrontendHostStatus) => void | Promise<void>;\n readonly autoActivate?: boolean;\n}\n\nexport interface FrontendHost {\n readonly context: Context;\n readonly loader?: CatalogLoader;\n readonly assembly: FrontendAssemblyState;\n readonly transport?: HostTransportClient;\n readonly ownedContext: boolean;\n readonly status: FrontendHostStatus;\n activate(assembly?: HostAssembly): Promise<void>;\n update(assembly: HostAssembly): Promise<void>;\n dispose(): Promise<void>;\n}\n\nfunction hostFoundationPlugin(\n assembly: FrontendAssemblyState,\n transport: HostTransportClient | undefined,\n): Plugin {\n return {\n name: 'forgeax:frontend-host-foundation',\n provide: ['hostAssembly', 'hostTransport'],\n apply(ctx) {\n ctx.provide('hostAssembly', assembly);\n if (transport !== undefined) ctx.provide('hostTransport', transport);\n },\n };\n}\n\nfunction dynamicModuleRecord(\n name: string,\n realm: PluginRealm,\n version: string,\n url: string | undefined,\n digest: string | undefined,\n): PluginCatalogRecord {\n if (url === undefined) {\n return {\n realm,\n version,\n ...(digest === undefined ? {} : { digest }),\n load: async () => {\n throw new HostAssemblyError(\n 'host-assembly-module-missing',\n `module ${name} to have a browser URL or static Catalog record`,\n 'Add the module to the frozen Catalog or publish its browser entry from the backend.',\n { name },\n );\n },\n };\n }\n return {\n realm,\n version,\n ...(digest === undefined ? {} : { digest }),\n load: () => import(/* @vite-ignore */ url),\n };\n}\n\nfunction catalogForAssembly(\n assembly: HostAssembly,\n staticCatalog: PluginCatalog | undefined,\n): PluginCatalog {\n const catalog = new Map<string, PluginCatalogRecord>();\n for (const module of assembly.modules) {\n const existing = staticCatalog?.get(module.name);\n if (existing !== undefined) {\n assertHostModuleCatalogIdentity(module, existing);\n catalog.set(module.name, existing);\n continue;\n }\n catalog.set(\n module.name,\n dynamicModuleRecord(module.name, module.realm, module.version, module.url, module.digest),\n );\n }\n for (const [name, record] of staticCatalog ?? []) {\n if (!catalog.has(name)) catalog.set(name, record);\n }\n return catalog;\n}\n\nfunction assertModuleVersions(\n assembly: HostAssembly,\n versions: ReadonlyMap<string, string> | undefined,\n): void {\n if (versions === undefined) return;\n for (const module of assembly.modules) {\n const actual = versions.get(module.name);\n if (actual === undefined || actual === module.version) continue;\n throw new HostAssemblyError(\n 'host-assembly-module-version-mismatch',\n `module ${module.name} to use version ${module.version}`,\n 'Refresh the browser module graph from the same backend assembly revision.',\n { name: module.name, actual, expected: module.version },\n );\n }\n}\n\nfunction moduleIdentity(module: {\n readonly version: string;\n readonly digest?: string;\n readonly url?: string;\n}): string {\n return `${module.version}@${module.digest ?? module.url ?? '<catalog>'}`;\n}\n\n/**\n * The native Loader keeps the imported module graph for its lifetime. A new\n * module URL or code identity therefore cannot be applied by Entry.update;\n * accepting it would report a new assembly while executing the old code.\n */\nfunction assertModuleReloadBoundary(previous: HostAssembly, next: HostAssembly): void {\n const previousModules = new Map(previous.modules.map((module) => [module.name, module]));\n const nextModules = new Map(next.modules.map((module) => [module.name, module]));\n const names = new Set([...previousModules.keys(), ...nextModules.keys()]);\n for (const name of names) {\n const before = previousModules.get(name);\n const after = nextModules.get(name);\n const beforeIdentity = before === undefined ? '<absent>' : moduleIdentity(before);\n const afterIdentity = after === undefined ? '<absent>' : moduleIdentity(after);\n if (\n before === undefined ||\n after === undefined ||\n before.realm !== after.realm ||\n beforeIdentity !== afterIdentity\n ) {\n throw new HostAssemblyError(\n 'host-assembly-reload-required',\n `module ${name} to keep its loaded code identity ${beforeIdentity}`,\n 'Reload the frontend host to install the new module graph before activating this assembly.',\n { module: name, actual: beforeIdentity, expected: afterIdentity },\n );\n }\n }\n}\n\nfunction staticAssembly(options: FrontendHostOptions, realm: PluginRealm): HostAssembly {\n const entries = options.entries ?? [];\n const modules =\n options.catalog === undefined ? [] : modulesFromCatalog(options.catalog, realm, 'static');\n return createHostAssembly({\n entries,\n modules,\n ...(options.config === undefined ? {} : { config: options.config }),\n });\n}\n\nfunction errorSummary(error: unknown): HostErrorSummary | undefined {\n if (\n error === null ||\n typeof error !== 'object' ||\n typeof (error as { code?: unknown }).code !== 'string' ||\n typeof (error as { expected?: unknown }).expected !== 'string' ||\n typeof (error as { hint?: unknown }).hint !== 'string'\n )\n return undefined;\n const detail = (error as { readonly detail?: unknown }).detail;\n return {\n code: (error as { readonly code: string }).code,\n expected: (error as { readonly expected: string }).expected,\n hint: (error as { readonly hint: string }).hint,\n detail:\n detail !== null && typeof detail === 'object'\n ? (detail as Readonly<Record<string, unknown>>)\n : { reason: String(detail ?? 'unknown failure') },\n };\n}\n\nasync function fetchInitialAssembly(\n options: FrontendHostOptions,\n realm: PluginRealm,\n): Promise<HostAssembly> {\n // An explicit assembly is an intentional bootstrap snapshot. DevKit uses\n // it to stage provider-only entries on reconnect before installing the\n // GameHost service; the transport still supplies the authoritative full\n // assembly immediately afterwards.\n if (options.assembly !== undefined) return options.assembly;\n if (options.transport !== undefined)\n return options.transport.request<undefined, HostAssembly>(HOST_ASSEMBLY_SERVICE, undefined);\n if (\n options.entries !== undefined ||\n options.catalog !== undefined ||\n options.config !== undefined\n )\n return staticAssembly(options, realm);\n throw new HostAssemblyError(\n 'host-assembly-service-unavailable',\n 'a static assembly or backend transport to be provided',\n 'Pass the frozen assembly for a static player or connect the frontend host to a backend host.',\n { service: HOST_ASSEMBLY_SERVICE },\n );\n}\n\nfunction readiness(loader: CatalogLoader): readonly HostActivationEntry[] {\n return inspectCatalogPlugins(loader).live.map((entry) => ({\n entryId: entry.entryId,\n fiberState: entry.fiberState,\n ...(entry.failure === undefined\n ? {}\n : {\n failure: {\n code: entry.failure.code,\n expected: entry.failure.expected,\n hint: entry.failure.hint,\n detail: entry.failure.detail,\n },\n }),\n }));\n}\n\nfunction assertReady(entries: readonly HostActivationEntry[]): void {\n const failed = entries.find(\n (entry) => entry.fiberState !== 'active' && entry.fiberState !== 'disabled',\n );\n if (failed === undefined) return;\n throw new HostAssemblyError(\n 'host-assembly-not-ready',\n `Entry ${failed.entryId} to reach active or disabled Fiber state`,\n 'Inspect the Entry failure or waiting dependency and repair the frontend package graph.',\n {\n entryId: failed.entryId,\n fiberState: failed.fiberState,\n ...(failed.failure === undefined ? {} : { failure: failed.failure }),\n },\n );\n}\n\n/** Start one independent browser-side manager and its native Cordis Loader. */\nexport async function createFrontendHost(options: FrontendHostOptions = {}): Promise<FrontendHost> {\n const realm = options.realm ?? 'engine';\n const initial = await fetchInitialAssembly(options, realm);\n const context = options.context ?? new Context();\n const ownedContext = options.context === undefined;\n const checked = validateHostAssembly(initial);\n if (!checked.ok) throw checked.error;\n let current = checked.value;\n let status: FrontendHostStatus = {\n state: 'created',\n revision: current.revision,\n };\n const state: FrontendAssemblyState = {\n get current() {\n return current;\n },\n get status() {\n return status;\n },\n };\n let startup: HostStartup | undefined;\n let loaderFiber: Fiber | undefined;\n let loader: CatalogLoader | undefined;\n let disposed = false;\n let removeTransportDisconnect: (() => void) | undefined;\n const report = async (next: FrontendHostStatus): Promise<void> => {\n status = next;\n await options.reportStatus?.(next);\n if (options.transport !== undefined) {\n const report: {\n state: HostActivationReport['state'];\n revision: string;\n entries?: readonly HostActivationEntry[];\n error?: HostErrorSummary;\n } = {\n state: next.state,\n revision: next.revision,\n };\n if (next.entries !== undefined) report.entries = next.entries;\n const failure = errorSummary(next.error);\n if (failure !== undefined) report.error = failure;\n try {\n await options.transport.request(HOST_ACTIVATION_REPORT_SERVICE, report);\n } catch (error) {\n const failed: FrontendHostStatus = {\n ...next,\n state: next.state === 'active' ? 'failed' : next.state,\n error,\n };\n status = failed;\n await options.reportStatus?.(failed);\n throw error;\n }\n }\n };\n if (options.transport !== undefined) {\n removeTransportDisconnect = options.transport.onDisconnect((error) => {\n if (disposed) return;\n const failed: FrontendHostStatus = {\n state: 'failed',\n revision: current.revision,\n error,\n };\n status = failed;\n void Promise.resolve(options.reportStatus?.(failed)).catch(() => {});\n });\n }\n\n try {\n startup = await createHostStartup({\n context,\n startupPlugins: [\n hostFoundationPlugin(state, options.transport),\n ...(options.startupPlugins ?? []),\n ],\n });\n if (options.autoActivate !== false) {\n // Activation is performed below through the returned host so its status\n // callback and failure rollback cover the first assembly as well.\n const host = {\n context,\n ...(options.transport === undefined ? {} : { transport: options.transport }),\n assembly: state,\n ...(ownedContext ? { ownedContext: true } : { ownedContext: false }),\n get status() {\n return status;\n },\n activate: async (_next?: HostAssembly) => {},\n update: async (_next: HostAssembly) => {},\n dispose: async () => {},\n } as FrontendHost;\n await activateFrontendHost(\n host,\n initial,\n options,\n realm,\n () => loader,\n (value) => {\n loader = value.loader;\n loaderFiber = value.fiber;\n },\n report,\n () => {\n current = initial;\n },\n );\n }\n } catch (error) {\n removeTransportDisconnect?.();\n await loaderFiber?.dispose();\n await startup?.dispose();\n throw error;\n }\n\n const host: FrontendHost = {\n context,\n ...(loader === undefined ? {} : { loader }),\n ...(options.transport === undefined ? {} : { transport: options.transport }),\n assembly: state,\n ownedContext,\n get status() {\n return status;\n },\n async activate(next = current) {\n await activateFrontendHost(\n host,\n next,\n options,\n realm,\n () => loader,\n (value) => {\n loader = value.loader;\n loaderFiber = value.fiber;\n (host as { loader?: CatalogLoader }).loader = value.loader;\n },\n report,\n () => {\n current = next;\n },\n );\n },\n async update(next) {\n await host.activate(next);\n },\n async dispose() {\n if (disposed) return;\n disposed = true;\n removeTransportDisconnect?.();\n await loaderFiber?.dispose();\n await startup?.dispose();\n status = { state: 'disposed', revision: current.revision };\n },\n };\n return host;\n}\n\nasync function activateFrontendHost(\n host: FrontendHost,\n next: HostAssembly,\n options: FrontendHostOptions,\n realm: PluginRealm,\n getLoader: () => CatalogLoader | undefined,\n setLoader: (value: { loader: CatalogLoader; fiber: Fiber }) => void,\n report: (status: FrontendHostStatus) => Promise<void>,\n commit: () => void,\n): Promise<void> {\n if (host.status.state === 'disposed') {\n throw new HostAssemblyError(\n 'host-assembly-service-unavailable',\n 'frontend host to remain active while activating an assembly',\n 'Create a new frontend host for the next browser connection.',\n { service: 'host-assembly' },\n );\n }\n const checked = validateHostAssembly(next);\n if (!checked.ok) {\n await report({ state: 'failed', revision: next.revision, error: checked.error });\n throw checked.error;\n }\n const activeLoader = getLoader();\n try {\n if (activeLoader !== undefined)\n assertModuleReloadBoundary(host.assembly.current, checked.value);\n await report({ state: 'loading', revision: next.revision });\n assertModuleVersions(checked.value, options.moduleVersions);\n let loader = activeLoader;\n if (loader === undefined) {\n const catalog = catalogForAssembly(checked.value, options.catalog);\n const installed = await installCatalogLoader(host.context, catalog, realm);\n loader = installed.loader;\n setLoader(installed);\n }\n const entries = projectPluginEntries(checked.value.entries, realm, realm);\n await loader.root.update(entries);\n await loader.await();\n const actualEntries = readiness(loader);\n assertReady(actualEntries);\n commit();\n await report({ state: 'active', revision: checked.value.revision, entries: actualEntries });\n } catch (error) {\n if (error instanceof HostAssemblyError && error.code === 'host-assembly-reload-required') {\n // The old Loader and its active Fibers are still authoritative. Do not\n // publish a failed status for the candidate revision or disguise a\n // required page reload as an in-place activation failure.\n throw error;\n }\n const activeLoader = getLoader();\n const actualEntries = activeLoader === undefined ? undefined : readiness(activeLoader);\n await report({\n state: 'failed',\n revision: next.revision,\n ...(actualEntries === undefined ? {} : { entries: actualEntries }),\n error,\n });\n throw error;\n }\n}\n\nexport { HostAssemblyError };\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -674,8 +674,10 @@ function errorFromSummary(service, summary) {
|
|
|
674
674
|
);
|
|
675
675
|
}
|
|
676
676
|
return new HostAssemblyError("host-transport-failure", summary.expected, summary.hint, {
|
|
677
|
+
...detail,
|
|
677
678
|
service,
|
|
678
|
-
reason: summary.detail.reason ? String(summary.detail.reason) : summary.code
|
|
679
|
+
reason: summary.detail.reason ? String(summary.detail.reason) : summary.code,
|
|
680
|
+
remoteCode: summary.code
|
|
679
681
|
});
|
|
680
682
|
}
|
|
681
683
|
function transportFailure(service, reason) {
|
|
@@ -1019,7 +1021,8 @@ async function createBackendHost(options = {}) {
|
|
|
1019
1021
|
assertBackendCatalogIdentity(catalog, backendModules);
|
|
1020
1022
|
const authority = authorityOf(checkedInitial.value);
|
|
1021
1023
|
const assembly = authority.authority;
|
|
1022
|
-
|
|
1024
|
+
let bootstrapRevision = checkedInitial.value.revision;
|
|
1025
|
+
const activationListeners = /* @__PURE__ */ new Set();
|
|
1023
1026
|
const transport = options.transport ?? createHostTransport();
|
|
1024
1027
|
let startup;
|
|
1025
1028
|
let loaderFiber;
|
|
@@ -1063,6 +1066,7 @@ async function createBackendHost(options = {}) {
|
|
|
1063
1066
|
);
|
|
1064
1067
|
}
|
|
1065
1068
|
await options.onActivationReport?.(report);
|
|
1069
|
+
for (const listener of activationListeners) await listener(report);
|
|
1066
1070
|
return { accepted: true };
|
|
1067
1071
|
}
|
|
1068
1072
|
);
|
|
@@ -1084,7 +1088,21 @@ async function createBackendHost(options = {}) {
|
|
|
1084
1088
|
assembly,
|
|
1085
1089
|
transport,
|
|
1086
1090
|
ownedContext: options.context === void 0,
|
|
1087
|
-
|
|
1091
|
+
subscribeActivationReports(listener) {
|
|
1092
|
+
if (disposed) {
|
|
1093
|
+
throw new HostAssemblyError(
|
|
1094
|
+
"host-assembly-service-unavailable",
|
|
1095
|
+
"the backend host to remain active while observing activation reports",
|
|
1096
|
+
"Subscribe on an active host instance.",
|
|
1097
|
+
{ service: HOST_ACTIVATION_REPORT_SERVICE }
|
|
1098
|
+
);
|
|
1099
|
+
}
|
|
1100
|
+
activationListeners.add(listener);
|
|
1101
|
+
return () => {
|
|
1102
|
+
activationListeners.delete(listener);
|
|
1103
|
+
};
|
|
1104
|
+
},
|
|
1105
|
+
async update(nextInput, updateOptions) {
|
|
1088
1106
|
if (disposed) {
|
|
1089
1107
|
throw new HostAssemblyError(
|
|
1090
1108
|
"host-assembly-service-unavailable",
|
|
@@ -1121,11 +1139,13 @@ async function createBackendHost(options = {}) {
|
|
|
1121
1139
|
await loader.await();
|
|
1122
1140
|
}
|
|
1123
1141
|
backendEntries = nextBackendEntries;
|
|
1142
|
+
if (updateOptions?.bootstrap === true) bootstrapRevision = checkedCandidate.value.revision;
|
|
1124
1143
|
return authority.publish(effectiveInput);
|
|
1125
1144
|
},
|
|
1126
1145
|
async dispose() {
|
|
1127
1146
|
if (disposed) return;
|
|
1128
1147
|
disposed = true;
|
|
1148
|
+
activationListeners.clear();
|
|
1129
1149
|
unsubscribeAssembly?.();
|
|
1130
1150
|
unregisterActivationService?.();
|
|
1131
1151
|
unregisterAssemblyService?.();
|