@forgeax/engine-host 0.1.27

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.
@@ -0,0 +1,586 @@
1
+ import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader';
2
+ import type {
3
+ GamePluginEntry,
4
+ PluginCatalog,
5
+ PluginCatalogRecord,
6
+ PluginRealm,
7
+ } from '@forgeax/engine-plugin/loader';
8
+
9
+ declare module '@forgeax/engine-plugin' {
10
+ interface EngineContextServices {
11
+ hostAssembly:
12
+ | import('./backend.js').BackendAssemblyAuthority
13
+ | import('./frontend.js').FrontendAssemblyState;
14
+ hostTransport:
15
+ | import('./transport.js').HostTransportServer
16
+ | import('./transport.js').HostTransportClient;
17
+ }
18
+ }
19
+
20
+ /** Wire version for the backend-derived browser assembly. */
21
+ export const HOST_ASSEMBLY_SCHEMA_VERSION = 1 as const;
22
+
23
+ export type HostAssemblySchemaVersion = typeof HOST_ASSEMBLY_SCHEMA_VERSION;
24
+
25
+ export interface HostModuleDescriptor {
26
+ /** The exact module name used by a Cordis Entry. */
27
+ readonly name: string;
28
+ /** Physical ForgeaX realm expected by the CatalogLoader. */
29
+ readonly realm: PluginRealm;
30
+ /** Code identity. The backend and browser must agree on this value. */
31
+ readonly version: string;
32
+ /** Optional content identity for a static or generated catalog. */
33
+ readonly digest?: string;
34
+ /** URL used by a live browser host. Static builds omit it and use a Catalog. */
35
+ readonly url?: string;
36
+ }
37
+
38
+ /** One package's explicitly paired backend/frontend Entry projections. */
39
+ export interface HostPluginPair {
40
+ readonly id: string;
41
+ readonly backend?: HostPluginEndpoint;
42
+ readonly frontend?: HostPluginEndpoint;
43
+ }
44
+
45
+ export interface HostPluginEndpoint {
46
+ readonly entry: GamePluginEntry;
47
+ readonly module: HostModuleDescriptor;
48
+ }
49
+
50
+ /** Safe identity projection; backend Entry configuration never crosses the wire. */
51
+ export interface HostAssemblyPair {
52
+ readonly id: string;
53
+ readonly entryId: string;
54
+ readonly module: HostModuleDescriptor;
55
+ }
56
+
57
+ /**
58
+ * A serializable projection of the entries that a frontend may activate.
59
+ * `EntryOptions` is intentionally retained so nested Groups and repeated Entry
60
+ * instances keep native Loader identity and reconciliation semantics.
61
+ */
62
+ export interface HostAssembly {
63
+ readonly schemaVersion: HostAssemblySchemaVersion;
64
+ /** Digest of entries, modules and explicitly projected configuration. */
65
+ readonly revision: string;
66
+ readonly entries: readonly GamePluginEntry[];
67
+ readonly modules: readonly HostModuleDescriptor[];
68
+ readonly pairs: readonly HostAssemblyPair[];
69
+ /** Safe, frontend-visible configuration only. */
70
+ readonly config?: unknown;
71
+ }
72
+
73
+ export interface HostAssemblyInput {
74
+ /** Backend Entries are local authority and are never serialized. */
75
+ readonly backendEntries?: readonly GamePluginEntry[];
76
+ readonly entries?: readonly GamePluginEntry[];
77
+ readonly modules?: readonly HostModuleDescriptor[];
78
+ readonly pairs?: readonly HostPluginPair[];
79
+ readonly config?: unknown;
80
+ }
81
+
82
+ export interface HostActivationEntry {
83
+ readonly entryId: string;
84
+ readonly fiberState: string;
85
+ readonly failure?: HostErrorSummary;
86
+ }
87
+
88
+ export interface HostErrorSummary {
89
+ readonly code: string;
90
+ readonly expected: string;
91
+ readonly hint: string;
92
+ readonly detail: Readonly<Record<string, unknown>>;
93
+ }
94
+
95
+ export interface HostActivationReport {
96
+ readonly state: 'created' | 'loading' | 'active' | 'failed' | 'disposed';
97
+ readonly revision: string;
98
+ readonly entries?: readonly HostActivationEntry[];
99
+ readonly error?: HostErrorSummary;
100
+ }
101
+
102
+ export interface HostAssemblyErrorDetailByCode {
103
+ 'host-assembly-invalid': { readonly reason: string };
104
+ 'host-assembly-revision-mismatch': { readonly actual: string; readonly expected: string };
105
+ 'host-assembly-module-missing': { readonly name: string };
106
+ 'host-assembly-module-version-mismatch': {
107
+ readonly name: string;
108
+ readonly actual: string;
109
+ readonly expected: string;
110
+ };
111
+ 'host-assembly-reload-required': {
112
+ readonly module: string;
113
+ readonly actual: string;
114
+ readonly expected: string;
115
+ };
116
+ 'host-assembly-service-unavailable': { readonly service: string };
117
+ 'host-assembly-stale-request': { readonly service: string; readonly generation: number };
118
+ 'host-assembly-request-aborted': { readonly service: string };
119
+ 'host-transport-failure': { readonly service: string; readonly reason: string };
120
+ 'host-assembly-not-ready': {
121
+ readonly entryId: string;
122
+ readonly fiberState: string;
123
+ readonly failure?: HostErrorSummary;
124
+ };
125
+ }
126
+
127
+ export type HostAssemblyErrorCode = keyof HostAssemblyErrorDetailByCode;
128
+
129
+ export class HostAssemblyError<
130
+ C extends HostAssemblyErrorCode = HostAssemblyErrorCode,
131
+ > extends Error {
132
+ readonly code: C;
133
+ readonly expected: string;
134
+ readonly hint: string;
135
+ readonly detail: HostAssemblyErrorDetailByCode[C];
136
+
137
+ constructor(code: C, expected: string, hint: string, detail: HostAssemblyErrorDetailByCode[C]) {
138
+ super(`${code}: ${expected}`);
139
+ this.name = 'HostAssemblyError';
140
+ this.code = code;
141
+ this.expected = expected;
142
+ this.hint = hint;
143
+ this.detail = detail;
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Prove that the code selected by a local Catalog is the code named by an
149
+ * assembly descriptor. An optional digest is still checked whenever either
150
+ * side supplies one; an unrelated digest must never stand in for a version.
151
+ */
152
+ export function assertHostModuleCatalogIdentity(
153
+ module: HostModuleDescriptor,
154
+ record: PluginCatalogRecord,
155
+ ): void {
156
+ if (record.version !== undefined && record.version !== module.version) {
157
+ throw new HostAssemblyError(
158
+ 'host-assembly-module-version-mismatch',
159
+ `module ${module.name} to load catalog version ${module.version}`,
160
+ 'Regenerate the static Catalog from the same backend package revision.',
161
+ { name: module.name, actual: record.version, expected: module.version },
162
+ );
163
+ }
164
+ if (
165
+ record.digest !== undefined &&
166
+ module.digest !== undefined &&
167
+ record.digest !== module.digest
168
+ ) {
169
+ throw new HostAssemblyError(
170
+ 'host-assembly-module-version-mismatch',
171
+ `module ${module.name} to load catalog digest ${module.digest ?? 'none'}`,
172
+ 'Regenerate the static Catalog from the same backend package bytes.',
173
+ { name: module.name, actual: record.digest, expected: module.digest ?? 'none' },
174
+ );
175
+ }
176
+ const versionMatches = record.version !== undefined && record.version === module.version;
177
+ const digestMatches =
178
+ module.digest !== undefined && record.digest !== undefined && record.digest === module.digest;
179
+ const staticWithoutIdentity =
180
+ module.version === 'static' &&
181
+ module.digest === undefined &&
182
+ record.version === undefined &&
183
+ record.digest === undefined;
184
+ if (!versionMatches && !digestMatches && !staticWithoutIdentity) {
185
+ throw new HostAssemblyError(
186
+ 'host-assembly-module-version-mismatch',
187
+ `module ${module.name} to have a matching catalog code identity for ${module.version}`,
188
+ 'Add the generated module version or digest to the static Catalog.',
189
+ {
190
+ name: module.name,
191
+ actual: record.version ?? record.digest ?? 'unknown',
192
+ expected: module.version,
193
+ },
194
+ );
195
+ }
196
+ }
197
+
198
+ export interface HostAssemblyResult {
199
+ readonly ok: true;
200
+ readonly value: HostAssembly;
201
+ }
202
+
203
+ export interface HostAssemblyFailure {
204
+ readonly ok: false;
205
+ readonly error: HostAssemblyError;
206
+ }
207
+
208
+ export type HostAssemblyValidation = HostAssemblyResult | HostAssemblyFailure;
209
+
210
+ /** JSON-stable projection used for revision identity and diagnostics. */
211
+ export function canonicalHostJson(value: unknown): string {
212
+ if (value === undefined) return 'undefined';
213
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
214
+ if (Array.isArray(value)) return `[${value.map(canonicalHostJson).join(',')}]`;
215
+ return `{${Object.entries(value as Record<string, unknown>)
216
+ .sort(([left], [right]) => left.localeCompare(right))
217
+ .map(([key, item]) => `${JSON.stringify(key)}:${canonicalHostJson(item)}`)
218
+ .join(',')}}`;
219
+ }
220
+
221
+ /** Small deterministic digest; it is an identity check, not a security hash. */
222
+ export function hostRevision(value: unknown): string {
223
+ let hash = 2166136261;
224
+ for (const char of canonicalHostJson(value)) {
225
+ hash ^= char.codePointAt(0) ?? 0;
226
+ hash = Math.imul(hash, 16777619);
227
+ }
228
+ return `fnv1a:${(hash >>> 0).toString(16).padStart(8, '0')}`;
229
+ }
230
+
231
+ function cloneEntry(entry: GamePluginEntry): GamePluginEntry {
232
+ const config = entry.group
233
+ ? (entry.config as readonly GamePluginEntry[] | undefined)?.map(cloneEntry)
234
+ : entry.config;
235
+ return {
236
+ id: entry.id,
237
+ name: entry.name,
238
+ ...(config === undefined ? {} : { config }),
239
+ ...(entry.group === undefined ? {} : { group: entry.group }),
240
+ ...(entry.disabled === undefined ? {} : { disabled: entry.disabled }),
241
+ ...(entry.inject === undefined ? {} : { inject: entry.inject }),
242
+ ...(entry.realm === undefined ? {} : { realm: entry.realm }),
243
+ };
244
+ }
245
+
246
+ function projectPairs(pairs: readonly HostPluginPair[]): {
247
+ readonly entries: readonly GamePluginEntry[];
248
+ readonly modules: readonly HostModuleDescriptor[];
249
+ readonly projections: readonly HostAssemblyPair[];
250
+ } {
251
+ const entries: GamePluginEntry[] = [];
252
+ const modules: HostModuleDescriptor[] = [];
253
+ const projections: HostAssemblyPair[] = [];
254
+ for (const pair of pairs) {
255
+ if (
256
+ pair.backend !== undefined &&
257
+ pair.frontend !== undefined &&
258
+ pair.backend.module.version !== pair.frontend.module.version
259
+ ) {
260
+ throw new HostAssemblyError(
261
+ 'host-assembly-module-version-mismatch',
262
+ `paired module ${pair.id} to use one code version on both hosts`,
263
+ 'Resolve backend and frontend package entries from the same locked package revision.',
264
+ {
265
+ name: pair.id,
266
+ actual: pair.backend.module.version,
267
+ expected: pair.frontend.module.version,
268
+ },
269
+ );
270
+ }
271
+ if (pair.frontend === undefined) continue;
272
+ entries.push(pair.frontend.entry);
273
+ modules.push(pair.frontend.module);
274
+ projections.push({
275
+ id: pair.id,
276
+ entryId: pair.frontend.entry.id,
277
+ module: pair.frontend.module,
278
+ });
279
+ }
280
+ return { entries, modules, projections };
281
+ }
282
+
283
+ function assemblyPairsFromInput(input: HostAssemblyInput): {
284
+ readonly entries: readonly GamePluginEntry[];
285
+ readonly modules: readonly HostModuleDescriptor[];
286
+ readonly pairs: readonly HostAssemblyPair[];
287
+ } {
288
+ if (input.pairs !== undefined) {
289
+ const projected = projectPairs(input.pairs);
290
+ return {
291
+ entries: input.entries ?? projected.entries,
292
+ modules: input.modules ?? projected.modules,
293
+ pairs: projected.projections,
294
+ };
295
+ }
296
+ const entries = input.entries ?? [];
297
+ const modules = [...(input.modules ?? [])];
298
+ for (const [index, entry] of entries.entries()) {
299
+ if (modules[index] !== undefined || modules.some((module) => module.name === entry.name))
300
+ continue;
301
+ modules.push({
302
+ name: entry.name,
303
+ realm: entry.realm ?? 'engine',
304
+ version: 'unknown',
305
+ });
306
+ }
307
+ return {
308
+ entries,
309
+ modules,
310
+ pairs: entries.map((entry, index) => ({
311
+ id: entry.id,
312
+ entryId: entry.id,
313
+ module:
314
+ modules[index]?.name === entry.name
315
+ ? modules[index]
316
+ : (modules.find((module) => module.name === entry.name) ?? {
317
+ name: entry.name,
318
+ realm: entry.realm ?? 'engine',
319
+ version: 'unknown',
320
+ }),
321
+ })),
322
+ };
323
+ }
324
+
325
+ /** Build one disposable assembly projection from effective backend inputs. */
326
+ export function createHostAssembly(input: HostAssemblyInput): HostAssembly {
327
+ const projected = assemblyPairsFromInput(input);
328
+ const entries = projected.entries.map(cloneEntry);
329
+ const modules = projected.modules.map((module) => ({ ...module }));
330
+ const pairs = projected.pairs.map((pair) => ({ ...pair, module: { ...pair.module } }));
331
+ const identity = {
332
+ schemaVersion: HOST_ASSEMBLY_SCHEMA_VERSION,
333
+ entries,
334
+ modules,
335
+ pairs,
336
+ ...(input.config === undefined ? {} : { config: input.config }),
337
+ };
338
+ return {
339
+ ...identity,
340
+ revision: hostRevision(identity),
341
+ };
342
+ }
343
+
344
+ function validateEntry(entry: EntryOptions, path: string): string | undefined {
345
+ if (entry === null || typeof entry !== 'object') return `${path} must be an Entry object`;
346
+ if (typeof entry.id !== 'string' || entry.id.length === 0) return `${path}.id must be non-empty`;
347
+ if (typeof entry.name !== 'string' || entry.name.length === 0)
348
+ return `${path}.name must be non-empty`;
349
+ if (entry.group === true) {
350
+ if (!Array.isArray(entry.config)) return `${path}.config must be an Entry array for a Group`;
351
+ for (const [index, child] of entry.config.entries()) {
352
+ const reason = validateEntry(child as EntryOptions, `${path}.config[${index}]`);
353
+ if (reason !== undefined) return reason;
354
+ }
355
+ }
356
+ return undefined;
357
+ }
358
+
359
+ /** Validate a received assembly before touching the native Loader. */
360
+ export function validateHostAssembly(assembly: HostAssembly): HostAssemblyValidation {
361
+ if (assembly === null || typeof assembly !== 'object') {
362
+ return {
363
+ ok: false,
364
+ error: new HostAssemblyError(
365
+ 'host-assembly-invalid',
366
+ 'assembly to be an object',
367
+ 'Regenerate the frontend assembly from the active backend authority.',
368
+ { reason: 'assembly is not an object' },
369
+ ),
370
+ };
371
+ }
372
+ if (assembly.schemaVersion !== HOST_ASSEMBLY_SCHEMA_VERSION) {
373
+ return {
374
+ ok: false,
375
+ error: new HostAssemblyError(
376
+ 'host-assembly-invalid',
377
+ `assembly schema ${HOST_ASSEMBLY_SCHEMA_VERSION}`,
378
+ 'Regenerate the frontend assembly with the matching Engine host package.',
379
+ { reason: `unsupported schema ${String(assembly.schemaVersion)}` },
380
+ ),
381
+ };
382
+ }
383
+ if (!Array.isArray(assembly.entries) || !Array.isArray(assembly.modules)) {
384
+ return {
385
+ ok: false,
386
+ error: new HostAssemblyError(
387
+ 'host-assembly-invalid',
388
+ 'assembly entries and modules to be arrays',
389
+ 'Regenerate the frontend assembly from the active backend authority.',
390
+ { reason: 'entries or modules is not an array' },
391
+ ),
392
+ };
393
+ }
394
+ if (!Array.isArray(assembly.pairs)) {
395
+ return {
396
+ ok: false,
397
+ error: new HostAssemblyError(
398
+ 'host-assembly-invalid',
399
+ 'assembly pairs to be an array',
400
+ 'Regenerate the assembly from the backend host using the matching host package.',
401
+ { reason: 'pairs is not an array' },
402
+ ),
403
+ };
404
+ }
405
+ const seen = new Set<string>();
406
+ for (const [index, entry] of assembly.entries.entries()) {
407
+ const reason = validateEntry(entry, `entries[${index}]`);
408
+ if (reason !== undefined) {
409
+ return {
410
+ ok: false,
411
+ error: new HostAssemblyError(
412
+ 'host-assembly-invalid',
413
+ 'all assembly entries to be valid native EntryOptions',
414
+ 'Repair the backend Entry projection before publishing it to a browser.',
415
+ { reason },
416
+ ),
417
+ };
418
+ }
419
+ if (seen.has(entry.id)) {
420
+ return {
421
+ ok: false,
422
+ error: new HostAssemblyError(
423
+ 'host-assembly-invalid',
424
+ 'assembly Entry ids to be unique',
425
+ 'Give repeated plugin instances independent stable ids.',
426
+ { reason: `duplicate Entry id ${entry.id}` },
427
+ ),
428
+ };
429
+ }
430
+ seen.add(entry.id);
431
+ }
432
+ const seenModules = new Map<string, HostModuleDescriptor>();
433
+ for (const [index, module] of assembly.modules.entries()) {
434
+ if (
435
+ module === null ||
436
+ typeof module !== 'object' ||
437
+ typeof module.name !== 'string' ||
438
+ typeof module.realm !== 'string' ||
439
+ typeof module.version !== 'string' ||
440
+ module.name.length === 0 ||
441
+ module.version.length === 0 ||
442
+ (module.url !== undefined && typeof module.url !== 'string') ||
443
+ (module.digest !== undefined &&
444
+ (typeof module.digest !== 'string' || module.digest.length === 0))
445
+ ) {
446
+ return {
447
+ ok: false,
448
+ error: new HostAssemblyError(
449
+ 'host-assembly-invalid',
450
+ 'module names and versions to be non-empty',
451
+ 'Regenerate the module projection from the resolved package metadata.',
452
+ { reason: `invalid module at index ${index}` },
453
+ ),
454
+ };
455
+ }
456
+ const previousModule = seenModules.get(module.name);
457
+ if (
458
+ previousModule !== undefined &&
459
+ (previousModule.realm !== module.realm ||
460
+ previousModule.version !== module.version ||
461
+ previousModule.url !== module.url ||
462
+ previousModule.digest !== module.digest)
463
+ ) {
464
+ return {
465
+ ok: false,
466
+ error: new HostAssemblyError(
467
+ 'host-assembly-invalid',
468
+ 'assembly module identity to be consistent for repeated Entries',
469
+ 'Reuse one resolved module identity when a package has multiple Entry instances.',
470
+ { reason: `module ${module.name} has conflicting identities` },
471
+ ),
472
+ };
473
+ }
474
+ seenModules.set(module.name, module);
475
+ }
476
+ const seenPairIds = new Set<string>();
477
+ for (const [index, pair] of assembly.pairs.entries()) {
478
+ const pairModule = pair?.module;
479
+ if (
480
+ pair === null ||
481
+ typeof pair !== 'object' ||
482
+ typeof pair.id !== 'string' ||
483
+ pair.id.length === 0 ||
484
+ typeof pair.entryId !== 'string' ||
485
+ pair.entryId.length === 0 ||
486
+ pairModule === null ||
487
+ pairModule === undefined ||
488
+ typeof pairModule !== 'object' ||
489
+ typeof pairModule.name !== 'string' ||
490
+ typeof pairModule.realm !== 'string' ||
491
+ typeof pairModule.version !== 'string' ||
492
+ pairModule.name.length === 0 ||
493
+ pairModule.version.length === 0 ||
494
+ (pairModule.url !== undefined && typeof pairModule.url !== 'string') ||
495
+ (pairModule.digest !== undefined &&
496
+ (typeof pairModule.digest !== 'string' || pairModule.digest.length === 0))
497
+ ) {
498
+ return {
499
+ ok: false,
500
+ error: new HostAssemblyError(
501
+ 'host-assembly-invalid',
502
+ 'assembly pair identities and modules to be valid',
503
+ 'Regenerate paired frontend entries from the backend package manifest.',
504
+ { reason: `invalid pair at index ${index}` },
505
+ ),
506
+ };
507
+ }
508
+ if (seenPairIds.has(pair.id)) {
509
+ return {
510
+ ok: false,
511
+ error: new HostAssemblyError(
512
+ 'host-assembly-invalid',
513
+ 'assembly pair ids to be unique',
514
+ 'Give each paired package instance an independent stable id.',
515
+ { reason: `duplicate pair ${pair.id}` },
516
+ ),
517
+ };
518
+ }
519
+ seenPairIds.add(pair.id);
520
+ if (!assembly.entries.some((entry) => entry.id === pair.entryId)) {
521
+ return {
522
+ ok: false,
523
+ error: new HostAssemblyError(
524
+ 'host-assembly-invalid',
525
+ `pair ${pair.id} to reference an assembly Entry`,
526
+ 'Keep paired identity and frontend Entry projection under one backend authority.',
527
+ { reason: `missing frontend Entry ${pair.entryId}` },
528
+ ),
529
+ };
530
+ }
531
+ const module = assembly.modules.find(
532
+ (candidate) =>
533
+ candidate.name === pairModule.name &&
534
+ candidate.realm === pairModule.realm &&
535
+ candidate.version === pairModule.version &&
536
+ candidate.url === pairModule.url &&
537
+ candidate.digest === pairModule.digest,
538
+ );
539
+ if (module === undefined) {
540
+ return {
541
+ ok: false,
542
+ error: new HostAssemblyError(
543
+ 'host-assembly-invalid',
544
+ `pair ${pair.id} to reference a resolved frontend module`,
545
+ 'Keep module/code identity in the backend-derived assembly projection.',
546
+ { reason: `missing frontend module ${pairModule.name}` },
547
+ ),
548
+ };
549
+ }
550
+ }
551
+ const expected = hostRevision({
552
+ schemaVersion: assembly.schemaVersion,
553
+ entries: assembly.entries,
554
+ modules: assembly.modules,
555
+ pairs: assembly.pairs,
556
+ ...(assembly.config === undefined ? {} : { config: assembly.config }),
557
+ });
558
+ if (expected !== assembly.revision) {
559
+ return {
560
+ ok: false,
561
+ error: new HostAssemblyError(
562
+ 'host-assembly-revision-mismatch',
563
+ 'assembly revision to match its entries and modules',
564
+ 'Discard the stale response and request the current backend assembly again.',
565
+ { actual: assembly.revision, expected },
566
+ ),
567
+ };
568
+ }
569
+ return { ok: true, value: assembly };
570
+ }
571
+
572
+ /** Derive a static module descriptor set from an existing native Catalog. */
573
+ export function modulesFromCatalog(
574
+ catalog: PluginCatalog,
575
+ realm: PluginRealm,
576
+ version = 'static',
577
+ ): HostModuleDescriptor[] {
578
+ return [...catalog.entries()]
579
+ .filter(([, record]) => record.realm === realm)
580
+ .map(([name, record]) => ({
581
+ name,
582
+ realm,
583
+ version: record.version ?? version,
584
+ ...(record.digest === undefined ? {} : { digest: record.digest }),
585
+ }));
586
+ }