@mica-js/sdk 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +162 -24
  2. package/dist/build/cli.js +90 -26
  3. package/dist/build/config.d.ts +11 -0
  4. package/dist/build/config.js +15 -1
  5. package/dist/build/content.d.ts +2 -0
  6. package/dist/build/content.js +2 -1
  7. package/dist/build/prepare.d.ts +2 -0
  8. package/dist/build/prepare.js +2 -0
  9. package/dist/build/project.d.ts +6 -0
  10. package/dist/build/project.js +25 -8
  11. package/dist/build/unified-build.d.ts +38 -0
  12. package/dist/build/unified-build.js +65 -0
  13. package/dist/build/unified-defaults.d.ts +21 -0
  14. package/dist/build/unified-defaults.js +267 -0
  15. package/dist/build/unified-manifest.d.ts +34 -0
  16. package/dist/build/unified-manifest.js +113 -0
  17. package/dist/build/unified-package.d.ts +64 -0
  18. package/dist/build/unified-package.js +354 -0
  19. package/dist/build/unified-paths.d.ts +30 -0
  20. package/dist/build/unified-paths.js +94 -0
  21. package/dist/build/unified-prepare.d.ts +58 -0
  22. package/dist/build/unified-prepare.js +209 -0
  23. package/dist/build/unified-types.d.ts +20 -0
  24. package/dist/build/unified-types.js +253 -0
  25. package/dist/device.d.ts +13 -1
  26. package/dist/fused/agreement.d.ts +15 -0
  27. package/dist/fused/agreement.js +104 -0
  28. package/dist/fused/diagnostics.d.ts +51 -0
  29. package/dist/fused/diagnostics.js +97 -0
  30. package/dist/fused/firmware.d.ts +27 -0
  31. package/dist/fused/firmware.js +105 -0
  32. package/dist/fused/index.d.ts +29 -0
  33. package/dist/fused/index.js +11 -0
  34. package/dist/fused/model.d.ts +101 -0
  35. package/dist/fused/model.js +47 -0
  36. package/dist/fused/models.d.ts +113 -0
  37. package/dist/fused/models.js +445 -0
  38. package/dist/fused/node.d.ts +5 -0
  39. package/dist/fused/node.js +139 -0
  40. package/dist/fused/package.d.ts +40 -0
  41. package/dist/fused/package.js +270 -0
  42. package/dist/fused/prepare.d.ts +50 -0
  43. package/dist/fused/prepare.js +214 -0
  44. package/dist/fused/program-memory.d.ts +2 -0
  45. package/dist/fused/program-memory.js +174 -0
  46. package/dist/fused/program.d.ts +47 -0
  47. package/dist/fused/program.js +99 -0
  48. package/dist/fused/properties.d.ts +48 -0
  49. package/dist/fused/properties.js +465 -0
  50. package/dist/fused/runtime.d.ts +60 -0
  51. package/dist/fused/runtime.js +568 -0
  52. package/dist/fused/values.d.ts +27 -0
  53. package/dist/fused/values.js +98 -0
  54. package/package.json +20 -3
@@ -0,0 +1,568 @@
1
+ /**
2
+ * Production headless runtime of the fused device contract (RFC 0025).
3
+ *
4
+ * The runtime owns one document snapshot, one prepared set of package bytes and one simulator
5
+ * board. It runs in the caller's thread, reuses the production simulator and its electrical solver,
6
+ * loads models through the caller-supplied `loadModule` and serializes every state change at a safe
7
+ * boundary: method calls, `step`, `resume`, `pause`, `reset` and `dispose` never interleave.
8
+ */
9
+ import { MAX_TIME_PS, timePs } from '@mica-js/core';
10
+ import { Emitter } from '@mica-js/core/lifecycle';
11
+ import { SimulationError, createBoard, createDeviceLibrary } from '@mica-js/simulator';
12
+ import { diagnostic } from './diagnostics.js';
13
+ import { ModelBinding, ModelDisconnectedError, ModelFault } from './models.js';
14
+ import { MethodError, isMethodError } from './model.js';
15
+ import { MICA_HOST_API_VERSION } from './package.js';
16
+ import { prepareFusedSession } from './prepare.js';
17
+ import { snapshotValue } from './values.js';
18
+ /** Thrown or rejected by runtime operations; `code` is a stable contract code. */
19
+ export class FusedRuntimeError extends Error {
20
+ code;
21
+ instanceId;
22
+ constructor(code, message, instanceId) {
23
+ super(message);
24
+ this.name = 'FusedRuntimeError';
25
+ this.code = code;
26
+ if (instanceId !== undefined) {
27
+ this.instanceId = instanceId;
28
+ }
29
+ }
30
+ }
31
+ const DISCONNECTED = 'model/disconnected';
32
+ class Session {
33
+ board;
34
+ #bindings = new Map();
35
+ constructor(prepared, hooks) {
36
+ const pending = new Map();
37
+ for (const instance of prepared.instances) {
38
+ const device = prepared.devices.get(instance.deviceId);
39
+ const definition = device?.package.manifest.model;
40
+ if (device?.model === undefined || definition === undefined) {
41
+ continue;
42
+ }
43
+ const binding = new ModelBinding({
44
+ instanceId: instance.instanceId,
45
+ methods: definition.methods ?? {},
46
+ events: definition.events ?? {},
47
+ types: definition.types ?? {},
48
+ props: instance.props,
49
+ factory: device.model.create,
50
+ report: hooks.report,
51
+ blocked: hooks.blocked,
52
+ now: hooks.now,
53
+ ...(hooks.observer === undefined ? {} : { observer: hooks.observer }),
54
+ });
55
+ this.#bindings.set(instance.instanceId, binding);
56
+ const queue = pending.get(instance.deviceId);
57
+ if (queue === undefined) {
58
+ pending.set(instance.deviceId, [binding]);
59
+ }
60
+ else {
61
+ queue.push(binding);
62
+ }
63
+ }
64
+ const entries = [];
65
+ for (const [deviceId, device] of prepared.devices) {
66
+ if (device.model === undefined) {
67
+ continue;
68
+ }
69
+ entries.push({
70
+ id: deviceId,
71
+ model: device.model.ir,
72
+ create: (context) => {
73
+ // The board creates instances in description order, which is document order, so each
74
+ // device type consumes its prepared bindings in the same order.
75
+ const binding = pending.get(deviceId)?.shift();
76
+ if (binding === undefined) {
77
+ throw new Error(`Unexpected model factory call for "${deviceId}"`);
78
+ }
79
+ return binding.create(context);
80
+ },
81
+ });
82
+ }
83
+ const description = {
84
+ instances: prepared.instances.map((instance) => ({
85
+ id: instance.instanceId,
86
+ type: instance.deviceId,
87
+ props: { ...instance.boardProps },
88
+ })),
89
+ nets: prepared.nets.map((net) => ({
90
+ id: net.id,
91
+ pins: net.pins.map((pin) => ({ instance: pin.instance, pin: pin.pin })),
92
+ ...(net.voltage === undefined ? {} : { voltage: net.voltage }),
93
+ })),
94
+ };
95
+ this.board = createBoard(createDeviceLibrary(entries), description);
96
+ }
97
+ binding(instanceId) {
98
+ return this.#bindings.get(instanceId);
99
+ }
100
+ invalidate() {
101
+ for (const binding of this.#bindings.values()) {
102
+ binding.invalidate();
103
+ }
104
+ this.#bindings.clear();
105
+ }
106
+ }
107
+ class HeadlessRuntimeImpl {
108
+ #prepared;
109
+ #step;
110
+ #onModelEvent;
111
+ #onDiagnostic;
112
+ #stateEmitter = new Emitter();
113
+ #diagnosticEmitter = new Emitter();
114
+ #queue = [];
115
+ #status = 'paused';
116
+ #session;
117
+ #pumping = false;
118
+ #pumpDone;
119
+ #modelInputAllowed = false;
120
+ onDidChangeState = this.#stateEmitter.event;
121
+ onDidReportDiagnostic = this.#diagnosticEmitter.event;
122
+ constructor(prepared, options, step) {
123
+ this.#prepared = prepared;
124
+ this.#step = step;
125
+ this.#onModelEvent = options.onModelEvent;
126
+ this.#onDiagnostic = options.onDiagnostic;
127
+ this.#session = this.#createSession();
128
+ }
129
+ getState() {
130
+ const simTime = timePs(this.#session?.board.time ?? 0);
131
+ return Object.freeze({ status: this.#status, simTime });
132
+ }
133
+ getModel(instanceId) {
134
+ if (this.#status === 'disposed') {
135
+ throw new FusedRuntimeError(DISCONNECTED, 'The runtime is disposed; no model client is available.', instanceId);
136
+ }
137
+ const binding = this.#session?.binding(instanceId);
138
+ if (binding === undefined) {
139
+ throw new FusedRuntimeError('model/unknown-instance', `No live model for instance "${instanceId}"; modeled instance ids are declared by the document.`, instanceId);
140
+ }
141
+ return binding.client((name, params) => this.#invokeFromClient(binding, name, params));
142
+ }
143
+ async step() {
144
+ this.#assertAdvanceAllowed('step');
145
+ if (this.#status === 'running') {
146
+ throw new FusedRuntimeError('runtime/unavailable-state', 'step requires the paused state; pause the runtime first.');
147
+ }
148
+ await this.#schedule(() => this.#advance());
149
+ }
150
+ async resume() {
151
+ this.#assertAdvanceAllowed('resume');
152
+ if (this.#status === 'running') {
153
+ return;
154
+ }
155
+ this.#setStatus('running');
156
+ await this.#schedule(() => {
157
+ if (this.#status === 'running') {
158
+ this.#advance();
159
+ }
160
+ });
161
+ }
162
+ pause() {
163
+ if (this.#status === 'running') {
164
+ this.#setStatus('paused');
165
+ }
166
+ }
167
+ async reset() {
168
+ if (this.#status === 'disposed') {
169
+ throw new FusedRuntimeError('runtime/unavailable-state', 'The runtime is disposed.');
170
+ }
171
+ this.#setStatus('paused');
172
+ await this.#settle();
173
+ const previous = this.#session;
174
+ this.#session = undefined;
175
+ if (previous !== undefined) {
176
+ // The board owns the adapters, so it disposes the models before the clients go stale.
177
+ let cleanup;
178
+ try {
179
+ previous.board.dispose();
180
+ }
181
+ catch (cause) {
182
+ cleanup = new FusedRuntimeError('runtime/model-failed', `Board cleanup failed during reset: ${messageOf(cause)}`, cause instanceof SimulationError ? cause.diagnostic.instanceId : undefined);
183
+ }
184
+ finally {
185
+ previous.invalidate();
186
+ }
187
+ if (cleanup !== undefined) {
188
+ // A half-released session must not be reported as a successful reset.
189
+ this.#fault(cleanup, true);
190
+ throw cleanup;
191
+ }
192
+ }
193
+ this.#session = this.#createSession();
194
+ this.#emitState();
195
+ }
196
+ async dispose() {
197
+ if (this.#status === 'disposed') {
198
+ return;
199
+ }
200
+ this.#setStatus('disposed');
201
+ await this.#settle();
202
+ const session = this.#session;
203
+ this.#session = undefined;
204
+ const problems = [];
205
+ if (session !== undefined) {
206
+ try {
207
+ session.board.dispose();
208
+ }
209
+ catch (cause) {
210
+ const fault = modelFaultOf(cause);
211
+ problems.push(diagnostic(fault?.code ?? 'runtime/model-failed', `Board cleanup failed: ${messageOf(cause)}`));
212
+ }
213
+ session.invalidate();
214
+ }
215
+ this.#stateEmitter.dispose();
216
+ this.#diagnosticEmitter.dispose();
217
+ for (const entry of problems) {
218
+ this.#onDiagnostic?.(entry);
219
+ }
220
+ if (problems.length > 0) {
221
+ throw new FusedRuntimeError(problems[0].code, problems.map((entry) => entry.message).join('; '));
222
+ }
223
+ }
224
+ #createSession() {
225
+ // Factories and their initial events run inside the board initialization phase.
226
+ this.#modelInputAllowed = true;
227
+ try {
228
+ return new Session(this.#prepared, {
229
+ report: (entry) => this.#report(entry),
230
+ blocked: () => this.#modelInputAllowed && (this.#status === 'paused' || this.#status === 'running')
231
+ ? undefined
232
+ : 'model input is only allowed during initialization, method calls, sync and advance',
233
+ now: () => timePs(this.#session?.board.time ?? 0),
234
+ ...(this.#onModelEvent === undefined ? {} : { observer: this.#onModelEvent }),
235
+ });
236
+ }
237
+ finally {
238
+ this.#modelInputAllowed = false;
239
+ }
240
+ }
241
+ #assertAdvanceAllowed(operation) {
242
+ if (this.#status === 'disposed') {
243
+ throw new FusedRuntimeError('runtime/unavailable-state', `${operation} is not allowed after dispose.`);
244
+ }
245
+ if (this.#status === 'faulted') {
246
+ throw new FusedRuntimeError('runtime/model-failed', `${operation} is not allowed while the runtime is faulted; call reset first.`);
247
+ }
248
+ }
249
+ #advance() {
250
+ const session = this.#session;
251
+ if (session === undefined) {
252
+ throw new FusedRuntimeError('runtime/unavailable-state', 'No session is prepared.');
253
+ }
254
+ const from = session.board.time;
255
+ const target = from + this.#step;
256
+ if (target > MAX_TIME_PS) {
257
+ const error = new FusedRuntimeError('runtime/invalid-time', `Advancing ${this.#step} ps from ${from} ps exceeds the supported simulation time range.`);
258
+ this.#report(diagnostic(error.code, error.message));
259
+ if (this.#status === 'running') {
260
+ this.#setStatus('paused');
261
+ }
262
+ throw error;
263
+ }
264
+ this.#modelInputAllowed = true;
265
+ try {
266
+ session.board.runUntil(target);
267
+ }
268
+ catch (cause) {
269
+ throw this.#faultFrom(cause);
270
+ }
271
+ finally {
272
+ this.#modelInputAllowed = false;
273
+ }
274
+ this.#emitState();
275
+ }
276
+ #invokeFromClient(binding, name, params) {
277
+ if (!binding.live) {
278
+ return Promise.reject(new ModelDisconnectedError());
279
+ }
280
+ let captured;
281
+ try {
282
+ captured = binding.prepareParams(name, params);
283
+ }
284
+ catch (cause) {
285
+ return Promise.reject(cause instanceof Error ? cause : new Error(String(cause)));
286
+ }
287
+ if (this.#status === 'disposed') {
288
+ return Promise.reject(new FusedRuntimeError(DISCONNECTED, 'The runtime is disposed.', binding.instanceId));
289
+ }
290
+ return this.#schedule(() => this.#execute(binding, name, captured));
291
+ }
292
+ #execute(binding, name, params) {
293
+ if (!binding.live) {
294
+ throw new ModelDisconnectedError();
295
+ }
296
+ if (this.#status === 'faulted') {
297
+ throw new FusedRuntimeError('runtime/model-failed', 'The runtime is faulted; method calls are rejected until reset.', binding.instanceId);
298
+ }
299
+ this.#modelInputAllowed = true;
300
+ try {
301
+ const result = binding.invoke(name, params);
302
+ return binding.captureResult(name, result);
303
+ }
304
+ catch (cause) {
305
+ throw this.#callFailure(binding, name, cause);
306
+ }
307
+ finally {
308
+ this.#modelInputAllowed = false;
309
+ }
310
+ }
311
+ #callFailure(binding, name, cause) {
312
+ if (isMethodError(cause)) {
313
+ // Declared business rejection: the model keeps running and only this call rejects.
314
+ return this.#businessRejection(binding, name, cause);
315
+ }
316
+ if (cause instanceof ModelDisconnectedError || cause instanceof FusedRuntimeError) {
317
+ return cause;
318
+ }
319
+ if (cause instanceof ModelFault) {
320
+ const error = new FusedRuntimeError(cause.code, cause.message, binding.instanceId);
321
+ this.#fault(error, false);
322
+ return error;
323
+ }
324
+ const error = new FusedRuntimeError('model/execution-failed', `Method "${name}" failed: ${messageOf(cause)}`, binding.instanceId);
325
+ this.#fault(error, true);
326
+ return error;
327
+ }
328
+ /**
329
+ * Rebuilds a business rejection as this SDK's `MethodError`.
330
+ *
331
+ * A bundled model artifact constructs its own copy of the class, so the fields are carried over
332
+ * and `details` is captured as an independent value; the caller always sees a class of this
333
+ * runtime and the model keeps running.
334
+ */
335
+ #businessRejection(binding, name, cause) {
336
+ const details = cause.details;
337
+ if (details === undefined) {
338
+ return new MethodError(cause.code, cause.message);
339
+ }
340
+ try {
341
+ return new MethodError(cause.code, cause.message, snapshotValue(details));
342
+ }
343
+ catch (failure) {
344
+ this.#report(diagnostic('model/invalid-result', `Details of the rejection "${cause.code}" of method "${name}" are not a model value: ${messageOf(failure)}`, binding.instanceId));
345
+ return new MethodError(cause.code, cause.message);
346
+ }
347
+ }
348
+ #faultFrom(cause) {
349
+ const fault = modelFaultOf(cause);
350
+ const board = cause instanceof SimulationError ? cause.diagnostic : undefined;
351
+ const instanceId = board?.instanceId;
352
+ const detail = board === undefined
353
+ ? messageOf(cause)
354
+ : `${board.code} at ${String(board.time)} ps: ${board.message}`;
355
+ const error = new FusedRuntimeError('runtime/model-failed', detail, instanceId);
356
+ // A model fault already reported itself with its own contract code.
357
+ this.#fault(error, fault === undefined);
358
+ return error;
359
+ }
360
+ #fault(error, report) {
361
+ if (report) {
362
+ this.#report(diagnostic(error.code, error.message, error.instanceId));
363
+ }
364
+ if (this.#status === 'running' || this.#status === 'paused') {
365
+ this.#setStatus('faulted');
366
+ }
367
+ }
368
+ /**
369
+ * Delivers one diagnostic.
370
+ *
371
+ * Delivery problems are surfaced instead of swallowed: a failing sink or listener is logged as a
372
+ * secondary host failure, and a failing listener is additionally reported to the sink.
373
+ */
374
+ #report(entry) {
375
+ const sink = this.#onDiagnostic;
376
+ if (sink !== undefined) {
377
+ try {
378
+ sink(entry);
379
+ }
380
+ catch (cause) {
381
+ this.#fallback('the onDiagnostic sink', cause);
382
+ }
383
+ }
384
+ try {
385
+ this.#diagnosticEmitter.fire(entry);
386
+ }
387
+ catch (cause) {
388
+ const secondary = diagnostic('runtime/presentation-failed', `A diagnostic listener failed: ${messageOf(cause)}`, entry.instanceId);
389
+ if (sink === undefined) {
390
+ this.#fallback('a diagnostic listener', cause);
391
+ return;
392
+ }
393
+ try {
394
+ sink(secondary);
395
+ }
396
+ catch (nested) {
397
+ this.#fallback('the onDiagnostic sink', nested);
398
+ }
399
+ }
400
+ }
401
+ /** Last resort of reporting: a failure must never silently disappear. */
402
+ #fallback(what, cause) {
403
+ try {
404
+ console.error(`[mica fused] ${what} failed:`, cause);
405
+ }
406
+ catch {
407
+ /* Nothing else can carry the failure at this point. */
408
+ }
409
+ }
410
+ #setStatus(status) {
411
+ if (this.#status === status) {
412
+ return;
413
+ }
414
+ this.#status = status;
415
+ this.#emitState();
416
+ }
417
+ #emitState() {
418
+ const state = this.getState();
419
+ try {
420
+ this.#stateEmitter.fire(state);
421
+ }
422
+ catch (cause) {
423
+ this.#report(diagnostic('runtime/presentation-failed', `A state listener failed: ${messageOf(cause)}`));
424
+ }
425
+ }
426
+ #schedule(task) {
427
+ if (this.#status === 'disposed') {
428
+ return Promise.reject(new FusedRuntimeError(DISCONNECTED, 'The runtime is disposed.'));
429
+ }
430
+ return new Promise((resolve, reject) => {
431
+ this.#queue.push(() => {
432
+ try {
433
+ resolve(task());
434
+ }
435
+ catch (cause) {
436
+ reject(cause instanceof Error ? cause : new Error(String(cause)));
437
+ }
438
+ });
439
+ this.#start();
440
+ });
441
+ }
442
+ #start() {
443
+ if (this.#pumping || this.#status === 'disposed') {
444
+ return;
445
+ }
446
+ this.#pumping = true;
447
+ let settle = () => { };
448
+ this.#pumpDone = new Promise((resolve) => {
449
+ settle = resolve;
450
+ });
451
+ const done = settle;
452
+ void this.#pump(done);
453
+ }
454
+ async #pump(done) {
455
+ try {
456
+ for (;;) {
457
+ const command = this.#queue.shift();
458
+ if (command !== undefined) {
459
+ command();
460
+ // Let the settled promise of this command run its continuations before the next
461
+ // command (and therefore its events) is produced: a query response is applied before
462
+ // an event caused by a later call, as RFC 0021 requires.
463
+ await nextMicrotaskBoundary();
464
+ continue;
465
+ }
466
+ if (this.#status !== 'running' || this.#session === undefined) {
467
+ break;
468
+ }
469
+ try {
470
+ this.#advance();
471
+ }
472
+ catch {
473
+ if (this.#status !== 'running') {
474
+ break;
475
+ }
476
+ }
477
+ await yieldToHost();
478
+ }
479
+ }
480
+ finally {
481
+ this.#pumping = false;
482
+ this.#pumpDone = undefined;
483
+ done();
484
+ }
485
+ }
486
+ async #settle() {
487
+ while (this.#pumping) {
488
+ const done = this.#pumpDone;
489
+ if (done === undefined) {
490
+ break;
491
+ }
492
+ await done;
493
+ }
494
+ }
495
+ }
496
+ function modelFaultOf(cause) {
497
+ if (cause instanceof ModelFault) {
498
+ return cause;
499
+ }
500
+ if (cause instanceof SimulationError) {
501
+ return modelFaultOf(cause.diagnostic.cause);
502
+ }
503
+ return undefined;
504
+ }
505
+ /**
506
+ * One queued microtask boundary.
507
+ *
508
+ * The resolution callback is enqueued with `queueMicrotask`, so it sits *behind* the reaction a
509
+ * caller attached to the settled command promise in the same job: that reaction applies the result
510
+ * before the pump resumes with the next command and its events. Handlers chained later or behind an
511
+ * `await` are the receiver's ordering responsibility, as RFC 0021 states.
512
+ */
513
+ function nextMicrotaskBoundary() {
514
+ return new Promise((resolve) => {
515
+ queueMicrotask(resolve);
516
+ });
517
+ }
518
+ function yieldToHost() {
519
+ return new Promise((resolve) => {
520
+ setTimeout(resolve, 0);
521
+ });
522
+ }
523
+ function messageOf(cause) {
524
+ return cause instanceof Error ? cause.message : String(cause);
525
+ }
526
+ /**
527
+ * Creates one headless runtime.
528
+ *
529
+ * Resolves paused, at simulation time zero, with models initialized and their initial events
530
+ * already delivered to `onModelEvent`. Rejects with {@link FusedPreparationError} without running
531
+ * any model factory when the document, a package, the topology, a resource or a model interface is
532
+ * invalid.
533
+ */
534
+ export async function createHeadlessRuntime(options) {
535
+ if (options === null || typeof options !== 'object') {
536
+ throw new TypeError('createHeadlessRuntime expects an options object');
537
+ }
538
+ if (typeof options.loadModule !== 'function') {
539
+ throw new TypeError('options.loadModule must be a function');
540
+ }
541
+ if (options.registry === null || typeof options.registry?.open !== 'function') {
542
+ throw new TypeError('options.registry must open locked device packages');
543
+ }
544
+ let step;
545
+ try {
546
+ step = timePs(options.step);
547
+ }
548
+ catch (cause) {
549
+ const entry = diagnostic('runtime/invalid-time', messageOf(cause));
550
+ options.onDiagnostic?.(entry);
551
+ throw new FusedRuntimeError(entry.code, entry.message);
552
+ }
553
+ if (step <= 0) {
554
+ const entry = diagnostic('runtime/invalid-time', 'options.step must be a positive TimePs value');
555
+ options.onDiagnostic?.(entry);
556
+ throw new FusedRuntimeError(entry.code, entry.message);
557
+ }
558
+ const prepared = await prepareFusedSession({
559
+ document: options.document,
560
+ registry: options.registry,
561
+ loadModule: options.loadModule,
562
+ hostApiVersion: MICA_HOST_API_VERSION,
563
+ ...(options.resolveResource === undefined ? {} : { resolveResource: options.resolveResource }),
564
+ ...(options.programs === undefined ? {} : { programs: options.programs }),
565
+ ...(options.onDiagnostic === undefined ? {} : { onDiagnostic: options.onDiagnostic }),
566
+ });
567
+ return new HeadlessRuntimeImpl(prepared, options, step);
568
+ }
@@ -0,0 +1,27 @@
1
+ /** Value-domain helpers of the fused model API (RFC 0021). */
2
+ import type { Value } from '@mica-js/document/fused';
3
+ /** Whether `value` is a thenable; model hooks must stay synchronous. */
4
+ export declare function isThenable(value: unknown): value is PromiseLike<unknown>;
5
+ export declare function valuePath(path: readonly string[]): string;
6
+ export declare function describeValue(value: unknown): string;
7
+ /**
8
+ * Captures an independent immutable snapshot of one model value.
9
+ *
10
+ * Bytes are copied, arrays and objects are re-created and frozen, so later changes of the source
11
+ * cannot reach the returned value. Non-value shapes (functions, `undefined`, class instances,
12
+ * cycles, non-finite numbers) are rejected with the value path that violated the domain.
13
+ */
14
+ export declare function snapshotValue(value: unknown, path?: readonly string[]): Value;
15
+ /** Copies an already captured value so every receiver owns independent bytes. */
16
+ export declare function copyValue(value: Value): Value;
17
+ /** One `Uint8Array` member of a captured value together with its index path. */
18
+ export interface ByteView {
19
+ readonly view: Uint8Array;
20
+ readonly path: readonly string[];
21
+ }
22
+ /**
23
+ * Collects every `Uint8Array` member of a captured value.
24
+ *
25
+ * `fireTransferred` uses it to prove that the caller handed over complete buffers.
26
+ */
27
+ export declare function byteViews(value: unknown, path?: readonly string[], found?: ByteView[]): ByteView[];
@@ -0,0 +1,98 @@
1
+ /** Whether `value` is a thenable; model hooks must stay synchronous. */
2
+ export function isThenable(value) {
3
+ return (typeof value === 'object' &&
4
+ value !== null &&
5
+ typeof value.then === 'function');
6
+ }
7
+ export function valuePath(path) {
8
+ return path.length === 0 ? '$' : `$${path.map((key) => `[${JSON.stringify(key)}]`).join('')}`;
9
+ }
10
+ export function describeValue(value) {
11
+ if (value === null) {
12
+ return 'null';
13
+ }
14
+ if (Array.isArray(value)) {
15
+ return 'array';
16
+ }
17
+ if (value instanceof Uint8Array) {
18
+ return 'Uint8Array';
19
+ }
20
+ return typeof value;
21
+ }
22
+ /**
23
+ * Captures an independent immutable snapshot of one model value.
24
+ *
25
+ * Bytes are copied, arrays and objects are re-created and frozen, so later changes of the source
26
+ * cannot reach the returned value. Non-value shapes (functions, `undefined`, class instances,
27
+ * cycles, non-finite numbers) are rejected with the value path that violated the domain.
28
+ */
29
+ export function snapshotValue(value, path = []) {
30
+ return clone(value, path, new Set());
31
+ }
32
+ /** Copies an already captured value so every receiver owns independent bytes. */
33
+ export function copyValue(value) {
34
+ return clone(value, [], new Set());
35
+ }
36
+ function clone(value, path, stack) {
37
+ switch (typeof value) {
38
+ case 'string':
39
+ case 'boolean':
40
+ return value;
41
+ case 'number':
42
+ if (!Number.isFinite(value)) {
43
+ throw new TypeError(`${valuePath(path)}: a model value number must be finite`);
44
+ }
45
+ return value;
46
+ case 'object':
47
+ break;
48
+ default:
49
+ throw new TypeError(`${valuePath(path)}: ${typeof value} is not part of the model value domain`);
50
+ }
51
+ if (value === null) {
52
+ return null;
53
+ }
54
+ if (value instanceof Uint8Array) {
55
+ return value.slice();
56
+ }
57
+ if (stack.has(value)) {
58
+ throw new TypeError(`${valuePath(path)}: a model value must not contain a cycle`);
59
+ }
60
+ stack.add(value);
61
+ try {
62
+ if (Array.isArray(value)) {
63
+ return Object.freeze(value.map((item, index) => clone(item, [...path, String(index)], stack)));
64
+ }
65
+ if (!isPlainObject(value)) {
66
+ throw new TypeError(`${valuePath(path)}: only plain objects are part of the model value domain`);
67
+ }
68
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clone(item, [...path, key], stack)])));
69
+ }
70
+ finally {
71
+ stack.delete(value);
72
+ }
73
+ }
74
+ function isPlainObject(value) {
75
+ const prototype = Object.getPrototypeOf(value);
76
+ return prototype === Object.prototype || prototype === null;
77
+ }
78
+ /**
79
+ * Collects every `Uint8Array` member of a captured value.
80
+ *
81
+ * `fireTransferred` uses it to prove that the caller handed over complete buffers.
82
+ */
83
+ export function byteViews(value, path = [], found = []) {
84
+ if (value instanceof Uint8Array) {
85
+ found.push({ view: value, path });
86
+ return found;
87
+ }
88
+ if (Array.isArray(value)) {
89
+ value.forEach((item, index) => byteViews(item, [...path, String(index)], found));
90
+ return found;
91
+ }
92
+ if (typeof value === 'object' && value !== null && isPlainObject(value)) {
93
+ for (const [key, item] of Object.entries(value)) {
94
+ byteViews(item, [...path, key], found);
95
+ }
96
+ }
97
+ return found;
98
+ }