@mica-js/sdk 0.3.2 → 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.
- package/README.md +162 -24
- package/dist/build/cli.js +90 -26
- package/dist/build/config.d.ts +11 -0
- package/dist/build/config.js +15 -1
- package/dist/build/content.d.ts +2 -0
- package/dist/build/content.js +2 -1
- package/dist/build/prepare.d.ts +2 -0
- package/dist/build/prepare.js +2 -0
- package/dist/build/project.d.ts +6 -0
- package/dist/build/project.js +25 -8
- package/dist/build/unified-build.d.ts +38 -0
- package/dist/build/unified-build.js +65 -0
- package/dist/build/unified-defaults.d.ts +21 -0
- package/dist/build/unified-defaults.js +267 -0
- package/dist/build/unified-manifest.d.ts +34 -0
- package/dist/build/unified-manifest.js +113 -0
- package/dist/build/unified-package.d.ts +64 -0
- package/dist/build/unified-package.js +354 -0
- package/dist/build/unified-paths.d.ts +30 -0
- package/dist/build/unified-paths.js +94 -0
- package/dist/build/unified-prepare.d.ts +58 -0
- package/dist/build/unified-prepare.js +209 -0
- package/dist/build/unified-types.d.ts +20 -0
- package/dist/build/unified-types.js +253 -0
- package/dist/device.d.ts +13 -1
- package/dist/fused/agreement.d.ts +15 -0
- package/dist/fused/agreement.js +104 -0
- package/dist/fused/diagnostics.d.ts +51 -0
- package/dist/fused/diagnostics.js +97 -0
- package/dist/fused/firmware.d.ts +27 -0
- package/dist/fused/firmware.js +105 -0
- package/dist/fused/index.d.ts +29 -0
- package/dist/fused/index.js +11 -0
- package/dist/fused/model.d.ts +101 -0
- package/dist/fused/model.js +47 -0
- package/dist/fused/models.d.ts +113 -0
- package/dist/fused/models.js +445 -0
- package/dist/fused/node.d.ts +5 -0
- package/dist/fused/node.js +139 -0
- package/dist/fused/package.d.ts +40 -0
- package/dist/fused/package.js +270 -0
- package/dist/fused/prepare.d.ts +50 -0
- package/dist/fused/prepare.js +214 -0
- package/dist/fused/program-memory.d.ts +2 -0
- package/dist/fused/program-memory.js +174 -0
- package/dist/fused/program.d.ts +47 -0
- package/dist/fused/program.js +99 -0
- package/dist/fused/properties.d.ts +48 -0
- package/dist/fused/properties.js +465 -0
- package/dist/fused/runtime.d.ts +60 -0
- package/dist/fused/runtime.js +568 -0
- package/dist/fused/values.d.ts +27 -0
- package/dist/fused/values.js +98 -0
- package/package.json +20 -3
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
import { Emitter, toDisposable } from '@mica-js/core/lifecycle';
|
|
2
|
+
import { validateModelValue } from '@mica-js/document/fused';
|
|
3
|
+
import { isMethodError } from './model.js';
|
|
4
|
+
import { diagnostic } from './diagnostics.js';
|
|
5
|
+
import { byteViews, copyValue, isThenable, snapshotValue } from './values.js';
|
|
6
|
+
/** A model contract violation: its interface, payloads or execution are wrong. */
|
|
7
|
+
export class ModelFault extends Error {
|
|
8
|
+
code;
|
|
9
|
+
constructor(code, message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = 'ModelFault';
|
|
12
|
+
this.code = code;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** Raised for a client whose model was replaced, faulted or disposed. */
|
|
16
|
+
export class ModelDisconnectedError extends Error {
|
|
17
|
+
/** Contract diagnostic code (RFC 0021 `model/disconnected`). */
|
|
18
|
+
code = 'model/disconnected';
|
|
19
|
+
constructor(message = 'The model client is disconnected from any live model') {
|
|
20
|
+
super(message);
|
|
21
|
+
this.name = 'ModelDisconnectedError';
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* One declared event outlet.
|
|
26
|
+
*
|
|
27
|
+
* Dispatch uses the core {@link Emitter}; each receiver gets its own snapshot of the payload and a
|
|
28
|
+
* failing receiver is reported and removed instead of disturbing the other listeners or the model.
|
|
29
|
+
*/
|
|
30
|
+
class Channel {
|
|
31
|
+
name;
|
|
32
|
+
#emitter = new Emitter();
|
|
33
|
+
#report;
|
|
34
|
+
constructor(name, report) {
|
|
35
|
+
this.name = name;
|
|
36
|
+
this.#report = report;
|
|
37
|
+
}
|
|
38
|
+
event = (listener, thisArgs, disposables) => {
|
|
39
|
+
const handle = {};
|
|
40
|
+
let removed = false;
|
|
41
|
+
const remove = () => {
|
|
42
|
+
if (removed) {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
removed = true;
|
|
46
|
+
handle.subscription?.dispose();
|
|
47
|
+
};
|
|
48
|
+
handle.subscription = this.#emitter.event((payload) => {
|
|
49
|
+
if (removed) {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
let result;
|
|
53
|
+
try {
|
|
54
|
+
result = listener.call(thisArgs, {
|
|
55
|
+
value: copyValue(payload.value),
|
|
56
|
+
simTime: payload.simTime,
|
|
57
|
+
sequence: payload.sequence,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
catch (cause) {
|
|
61
|
+
this.#report(cause, `listener of event "${this.name}"`);
|
|
62
|
+
remove();
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
if (isThenable(result)) {
|
|
66
|
+
void Promise.resolve(result).catch((cause) => {
|
|
67
|
+
this.#report(cause, `listener of event "${this.name}"`);
|
|
68
|
+
remove();
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
return result;
|
|
72
|
+
});
|
|
73
|
+
const disposable = toDisposable(remove);
|
|
74
|
+
disposables?.push(disposable);
|
|
75
|
+
return disposable;
|
|
76
|
+
};
|
|
77
|
+
fire(payload) {
|
|
78
|
+
this.#emitter.fire(payload);
|
|
79
|
+
}
|
|
80
|
+
clear() {
|
|
81
|
+
this.#emitter.dispose();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export class ModelBinding {
|
|
85
|
+
#channels = new Map();
|
|
86
|
+
#methods = new Map();
|
|
87
|
+
#declaredMethods;
|
|
88
|
+
#options;
|
|
89
|
+
#adapter;
|
|
90
|
+
#sequence = 0;
|
|
91
|
+
#live = true;
|
|
92
|
+
#client;
|
|
93
|
+
constructor(options) {
|
|
94
|
+
this.#options = options;
|
|
95
|
+
this.#declaredMethods = Object.keys(options.methods);
|
|
96
|
+
for (const name of Object.keys(options.events)) {
|
|
97
|
+
this.#channels.set(name, new Channel(name, (cause, what) => {
|
|
98
|
+
options.report(diagnostic('runtime/presentation-failed', `${messageOf(cause)} (${what} on ${options.instanceId})`, options.instanceId));
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
get instanceId() {
|
|
103
|
+
return this.#options.instanceId;
|
|
104
|
+
}
|
|
105
|
+
get live() {
|
|
106
|
+
return this.#live;
|
|
107
|
+
}
|
|
108
|
+
/** Parameter and result types of one declared method, or `undefined` for an unknown name. */
|
|
109
|
+
methodDefinition(name) {
|
|
110
|
+
return this.#options.methods[name];
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Creates the adapter the board registers for this instance.
|
|
114
|
+
*
|
|
115
|
+
* The factory runs here, so interface checks and initial events happen during the board's
|
|
116
|
+
* initialization phase.
|
|
117
|
+
*/
|
|
118
|
+
create(base) {
|
|
119
|
+
if (!this.#live) {
|
|
120
|
+
throw new ModelDisconnectedError();
|
|
121
|
+
}
|
|
122
|
+
const context = this.#createContext(base);
|
|
123
|
+
let instance;
|
|
124
|
+
try {
|
|
125
|
+
instance = this.#options.factory(context);
|
|
126
|
+
}
|
|
127
|
+
catch (cause) {
|
|
128
|
+
throw this.#unwrap(cause, 'model/execution-failed', `Model factory of ${this.instanceId} failed`);
|
|
129
|
+
}
|
|
130
|
+
if (isThenable(instance)) {
|
|
131
|
+
throw this.#fault('model/async-handler', `Model factory of ${this.instanceId} returned a thenable`);
|
|
132
|
+
}
|
|
133
|
+
const adapter = this.#validateInstance(instance);
|
|
134
|
+
this.#adapter = adapter;
|
|
135
|
+
return {
|
|
136
|
+
sync: (batch) => {
|
|
137
|
+
this.#sync(batch);
|
|
138
|
+
},
|
|
139
|
+
dispose: () => {
|
|
140
|
+
this.#disposeAdapter();
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
/** Synchronous invocation used at a serialized safe boundary. */
|
|
145
|
+
invoke(name, params) {
|
|
146
|
+
if (!this.#live || this.#adapter === undefined) {
|
|
147
|
+
throw new ModelDisconnectedError();
|
|
148
|
+
}
|
|
149
|
+
const method = this.#methods.get(name);
|
|
150
|
+
if (method === undefined) {
|
|
151
|
+
throw new ModelFault('model/unknown-method', `Model ${this.instanceId} has no method "${name}".`);
|
|
152
|
+
}
|
|
153
|
+
const result = method(params);
|
|
154
|
+
if (isThenable(result)) {
|
|
155
|
+
throw new ModelFault('model/async-handler', `Method "${name}" of ${this.instanceId} returned a thenable; model hooks must be synchronous.`);
|
|
156
|
+
}
|
|
157
|
+
return result;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Captures and validates one method parameter value before it is queued.
|
|
161
|
+
*
|
|
162
|
+
* Parameter failures reject the call without executing the handler and without faulting the
|
|
163
|
+
* model, so they are reported to the caller only.
|
|
164
|
+
*/
|
|
165
|
+
prepareParams(name, value) {
|
|
166
|
+
const definition = this.methodDefinition(name);
|
|
167
|
+
if (definition === undefined) {
|
|
168
|
+
throw new ModelFault('model/unknown-method', `Model ${this.instanceId} has no method "${name}".`);
|
|
169
|
+
}
|
|
170
|
+
let snapshot;
|
|
171
|
+
try {
|
|
172
|
+
snapshot = snapshotValue(value);
|
|
173
|
+
}
|
|
174
|
+
catch (cause) {
|
|
175
|
+
throw new ModelFault('model/invalid-params', `Parameters of "${name}" on ${this.instanceId} are not a model value: ${messageOf(cause)}`);
|
|
176
|
+
}
|
|
177
|
+
try {
|
|
178
|
+
validateModelValue(snapshot, definition.params, this.#options.types);
|
|
179
|
+
}
|
|
180
|
+
catch (cause) {
|
|
181
|
+
throw new ModelFault('model/invalid-params', `Parameters of "${name}" on ${this.instanceId} do not match the declared type: ${messageOf(cause)}`);
|
|
182
|
+
}
|
|
183
|
+
return snapshot;
|
|
184
|
+
}
|
|
185
|
+
/** Captures an independent snapshot of one method result and validates it. */
|
|
186
|
+
captureResult(name, value) {
|
|
187
|
+
const definition = this.methodDefinition(name);
|
|
188
|
+
if (definition === undefined) {
|
|
189
|
+
throw new ModelFault('model/unknown-method', `Model ${this.instanceId} has no method "${name}".`);
|
|
190
|
+
}
|
|
191
|
+
return this.#capture('model/invalid-result', `Method "${name}" of ${this.instanceId}`, value, definition.returns);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Host client of this instance.
|
|
195
|
+
*
|
|
196
|
+
* `invoke` is the runtime scheduler entry point: every declared method resolves to a function
|
|
197
|
+
* that validates its parameters, waits for the next safe boundary and returns the result value.
|
|
198
|
+
*/
|
|
199
|
+
client(invoke) {
|
|
200
|
+
if (this.#client !== undefined) {
|
|
201
|
+
return this.#client;
|
|
202
|
+
}
|
|
203
|
+
const methods = {};
|
|
204
|
+
for (const name of this.#declaredMethods) {
|
|
205
|
+
methods[name] = (params) => invoke(name, params);
|
|
206
|
+
}
|
|
207
|
+
const events = {};
|
|
208
|
+
for (const [name, channel] of this.#channels) {
|
|
209
|
+
events[name] = channel.event;
|
|
210
|
+
}
|
|
211
|
+
const client = Object.freeze({
|
|
212
|
+
methods: Object.freeze(methods),
|
|
213
|
+
events: Object.freeze(events),
|
|
214
|
+
});
|
|
215
|
+
this.#client = client;
|
|
216
|
+
return client;
|
|
217
|
+
}
|
|
218
|
+
/** Marks the binding dead after its model was replaced or released. */
|
|
219
|
+
invalidate() {
|
|
220
|
+
this.#live = false;
|
|
221
|
+
this.#adapter = undefined;
|
|
222
|
+
this.#methods.clear();
|
|
223
|
+
for (const channel of this.#channels.values()) {
|
|
224
|
+
channel.clear();
|
|
225
|
+
}
|
|
226
|
+
this.#client = undefined;
|
|
227
|
+
}
|
|
228
|
+
#createContext(base) {
|
|
229
|
+
const props = this.#options.props;
|
|
230
|
+
const outlets = {};
|
|
231
|
+
for (const name of this.#channels.keys()) {
|
|
232
|
+
outlets[name] = Object.freeze({
|
|
233
|
+
fire: (value) => {
|
|
234
|
+
this.#emit(name, value, undefined);
|
|
235
|
+
},
|
|
236
|
+
fireTransferred: (value, buffers) => {
|
|
237
|
+
this.#emit(name, value, buffers);
|
|
238
|
+
},
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
const context = {
|
|
242
|
+
get props() {
|
|
243
|
+
return props;
|
|
244
|
+
},
|
|
245
|
+
get inputs() {
|
|
246
|
+
return base.inputs;
|
|
247
|
+
},
|
|
248
|
+
get memory() {
|
|
249
|
+
return base.memory;
|
|
250
|
+
},
|
|
251
|
+
reportError: (error) => base.reportError(error),
|
|
252
|
+
attachJit: (options) => base.attachJit(options),
|
|
253
|
+
loadBytes: (memory, bytes, offset) => offset === undefined
|
|
254
|
+
? base.loadBytes(memory, bytes)
|
|
255
|
+
: base.loadBytes(memory, bytes, offset),
|
|
256
|
+
events: Object.freeze(outlets),
|
|
257
|
+
};
|
|
258
|
+
return Object.freeze(context);
|
|
259
|
+
}
|
|
260
|
+
#validateInstance(instance) {
|
|
261
|
+
if (typeof instance !== 'object' || instance === null) {
|
|
262
|
+
throw this.#fault('model/invalid-interface', `Model ${this.instanceId} factory returned no instance`);
|
|
263
|
+
}
|
|
264
|
+
const candidate = instance;
|
|
265
|
+
if (typeof candidate.sync !== 'function' || typeof candidate.dispose !== 'function') {
|
|
266
|
+
throw this.#fault('model/invalid-interface', `Model ${this.instanceId} must expose "sync" and "dispose" functions`);
|
|
267
|
+
}
|
|
268
|
+
const table = candidate.methods;
|
|
269
|
+
if (typeof table !== 'object' || table === null) {
|
|
270
|
+
throw this.#fault('model/invalid-interface', `Model ${this.instanceId} exposes no methods object`);
|
|
271
|
+
}
|
|
272
|
+
const descriptors = Object.getOwnPropertyDescriptors(table);
|
|
273
|
+
const names = Object.keys(descriptors);
|
|
274
|
+
for (const name of names) {
|
|
275
|
+
const descriptor = descriptors[name];
|
|
276
|
+
if (!('value' in descriptor) ||
|
|
277
|
+
typeof descriptor.value !== 'function' ||
|
|
278
|
+
!descriptor.enumerable) {
|
|
279
|
+
throw this.#fault('model/invalid-interface', `Method "${name}" of ${this.instanceId} must be an own enumerable function`);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
const declared = new Set(this.#declaredMethods);
|
|
283
|
+
for (const name of names) {
|
|
284
|
+
if (!declared.has(name)) {
|
|
285
|
+
throw this.#fault('model/invalid-interface', `Model ${this.instanceId} implements the undeclared method "${name}"`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
for (const name of declared) {
|
|
289
|
+
const descriptor = descriptors[name];
|
|
290
|
+
if (descriptor === undefined || !('value' in descriptor)) {
|
|
291
|
+
throw this.#fault('model/invalid-interface', `Model ${this.instanceId} does not implement the declared method "${name}"`);
|
|
292
|
+
}
|
|
293
|
+
const method = descriptor.value;
|
|
294
|
+
this.#methods.set(name, (params) => method.call(table, params));
|
|
295
|
+
}
|
|
296
|
+
return candidate;
|
|
297
|
+
}
|
|
298
|
+
#sync(batch) {
|
|
299
|
+
const adapter = this.#adapter;
|
|
300
|
+
if (adapter === undefined || !this.#live) {
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
let result;
|
|
304
|
+
try {
|
|
305
|
+
result = adapter.sync(batch);
|
|
306
|
+
}
|
|
307
|
+
catch (cause) {
|
|
308
|
+
throw this.#unwrap(cause, 'model/execution-failed', `sync of ${this.instanceId} failed`);
|
|
309
|
+
}
|
|
310
|
+
if (isThenable(result)) {
|
|
311
|
+
throw this.#fault('model/async-handler', `sync of ${this.instanceId} returned a thenable; model hooks must be synchronous.`);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
#disposeAdapter() {
|
|
315
|
+
const adapter = this.#adapter;
|
|
316
|
+
this.#adapter = undefined;
|
|
317
|
+
this.#live = false;
|
|
318
|
+
let failure;
|
|
319
|
+
try {
|
|
320
|
+
const result = adapter?.dispose();
|
|
321
|
+
if (isThenable(result)) {
|
|
322
|
+
// Every model hook is synchronous, `dispose` included: a thenable is an implementation bug.
|
|
323
|
+
void Promise.resolve(result).catch(() => { });
|
|
324
|
+
failure = new ModelFault('model/async-handler', `dispose of ${this.instanceId} returned a thenable; model hooks must be synchronous.`);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
catch (cause) {
|
|
328
|
+
failure = cause;
|
|
329
|
+
}
|
|
330
|
+
this.#methods.clear();
|
|
331
|
+
for (const channel of this.#channels.values()) {
|
|
332
|
+
channel.clear();
|
|
333
|
+
}
|
|
334
|
+
if (failure !== undefined) {
|
|
335
|
+
this.#options.report(diagnostic(failure instanceof ModelFault ? failure.code : 'model/execution-failed', `${messageOf(failure)} (dispose of ${this.instanceId})`, this.instanceId));
|
|
336
|
+
throw failure;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
#emit(name, value, buffers) {
|
|
340
|
+
const blocked = this.#options.blocked();
|
|
341
|
+
if (blocked !== undefined || !this.#live) {
|
|
342
|
+
throw this.#fault('model/invalid-phase', `Model ${this.instanceId} fired "${name}" outside an allowed phase: ${blocked ?? 'model is not live'}`);
|
|
343
|
+
}
|
|
344
|
+
const channel = this.#channels.get(name);
|
|
345
|
+
const type = this.#options.events[name];
|
|
346
|
+
if (channel === undefined || type === undefined) {
|
|
347
|
+
throw this.#fault('model/unknown-event', `Model ${this.instanceId} fired the undeclared event "${name}"`);
|
|
348
|
+
}
|
|
349
|
+
let source = value;
|
|
350
|
+
if (buffers !== undefined) {
|
|
351
|
+
try {
|
|
352
|
+
assertTransfer(value, buffers);
|
|
353
|
+
source = structuredClone(value, { transfer: [...buffers] });
|
|
354
|
+
}
|
|
355
|
+
catch (cause) {
|
|
356
|
+
if (cause instanceof ModelFault) {
|
|
357
|
+
this.#options.report(diagnostic(cause.code, cause.message, this.instanceId));
|
|
358
|
+
throw cause;
|
|
359
|
+
}
|
|
360
|
+
throw this.#fault('model/invalid-event', `Event "${name}" of ${this.instanceId} cannot transfer its buffers`, cause);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
const captured = this.#capture('model/invalid-event', `Event "${name}" of ${this.instanceId}`, source, type);
|
|
364
|
+
this.#sequence += 1;
|
|
365
|
+
const payload = Object.freeze({
|
|
366
|
+
value: captured,
|
|
367
|
+
simTime: this.#options.now(),
|
|
368
|
+
sequence: this.#sequence,
|
|
369
|
+
});
|
|
370
|
+
channel.fire(payload);
|
|
371
|
+
const observer = this.#options.observer;
|
|
372
|
+
if (observer !== undefined) {
|
|
373
|
+
try {
|
|
374
|
+
observer({
|
|
375
|
+
instanceId: this.instanceId,
|
|
376
|
+
event: name,
|
|
377
|
+
payload: {
|
|
378
|
+
value: copyValue(captured),
|
|
379
|
+
simTime: payload.simTime,
|
|
380
|
+
sequence: payload.sequence,
|
|
381
|
+
},
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
catch (cause) {
|
|
385
|
+
this.#options.report(diagnostic('runtime/presentation-failed', `${messageOf(cause)} (onModelEvent observer of ${this.instanceId})`, this.instanceId));
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
#capture(code, what, value, type) {
|
|
390
|
+
let snapshot;
|
|
391
|
+
try {
|
|
392
|
+
snapshot = snapshotValue(value);
|
|
393
|
+
}
|
|
394
|
+
catch (cause) {
|
|
395
|
+
throw this.#fault(code, `${what} produced an invalid value: ${messageOf(cause)}`);
|
|
396
|
+
}
|
|
397
|
+
try {
|
|
398
|
+
validateModelValue(snapshot, type, this.#options.types);
|
|
399
|
+
}
|
|
400
|
+
catch (cause) {
|
|
401
|
+
throw this.#fault(code, `${what} does not match the declared type: ${messageOf(cause)}`);
|
|
402
|
+
}
|
|
403
|
+
return snapshot;
|
|
404
|
+
}
|
|
405
|
+
/** Model faults and business rejections pass through; anything else becomes a fault. */
|
|
406
|
+
#unwrap(cause, code, message) {
|
|
407
|
+
if (cause instanceof ModelFault || isMethodError(cause)) {
|
|
408
|
+
return cause;
|
|
409
|
+
}
|
|
410
|
+
return this.#fault(code, message, cause);
|
|
411
|
+
}
|
|
412
|
+
#fault(code, message, cause) {
|
|
413
|
+
const failure = new ModelFault(code, cause === undefined ? message : `${message}: ${messageOf(cause)}`);
|
|
414
|
+
this.#options.report(diagnostic(code, failure.message, this.instanceId));
|
|
415
|
+
return failure;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
function assertTransfer(value, buffers) {
|
|
419
|
+
if (!Array.isArray(buffers)) {
|
|
420
|
+
throw new ModelFault('model/invalid-event', 'fireTransferred needs an array of buffers');
|
|
421
|
+
}
|
|
422
|
+
const seen = new Set();
|
|
423
|
+
for (const buffer of buffers) {
|
|
424
|
+
if (!(buffer instanceof ArrayBuffer)) {
|
|
425
|
+
throw new ModelFault('model/invalid-event', 'fireTransferred buffers must be ArrayBuffers');
|
|
426
|
+
}
|
|
427
|
+
if (seen.has(buffer)) {
|
|
428
|
+
throw new ModelFault('model/invalid-event', 'fireTransferred buffer is listed twice');
|
|
429
|
+
}
|
|
430
|
+
seen.add(buffer);
|
|
431
|
+
}
|
|
432
|
+
const views = byteViews(value);
|
|
433
|
+
for (const buffer of buffers) {
|
|
434
|
+
const covering = views.filter((entry) => entry.view.buffer === buffer);
|
|
435
|
+
if (covering.length === 0) {
|
|
436
|
+
throw new ModelFault('model/invalid-event', 'fireTransferred buffer is not part of the event payload');
|
|
437
|
+
}
|
|
438
|
+
if (!covering.some((entry) => entry.view.byteOffset === 0 && entry.view.byteLength === buffer.byteLength)) {
|
|
439
|
+
throw new ModelFault('model/invalid-event', 'fireTransferred buffer must be covered completely by one Uint8Array of the payload');
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
function messageOf(cause) {
|
|
444
|
+
return cause instanceof Error ? cause.message : String(cause);
|
|
445
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { DeviceRegistry, PackageFiles } from '@mica-js/document/fused';
|
|
2
|
+
import { type ProgramFile } from './program.js';
|
|
3
|
+
export declare function readProgramDirectory(directory: string, src: string): Promise<readonly ProgramFile[]>;
|
|
4
|
+
export declare function readDirectoryPackage(directory: string): Promise<PackageFiles>;
|
|
5
|
+
export declare function createDirectoryRegistry(directories: Readonly<Record<string, string>>): DeviceRegistry;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { lstat, open, readFile, readdir, realpath, stat } from 'node:fs/promises';
|
|
2
|
+
import { isAbsolute, relative, resolve } from 'node:path';
|
|
3
|
+
import { parseStrictJson } from '@mica-js/document/fused';
|
|
4
|
+
import { isPackagePath, releaseIntegrity } from './package.js';
|
|
5
|
+
import { checkProgramPath, PROGRAM_LIMITS, ProgramError } from './program.js';
|
|
6
|
+
export async function readProgramDirectory(directory, src) {
|
|
7
|
+
checkProgramPath(src);
|
|
8
|
+
const root = await realpath(directory);
|
|
9
|
+
let selected = root;
|
|
10
|
+
for (const part of src.split('/')) {
|
|
11
|
+
selected = resolve(selected, part);
|
|
12
|
+
const info = await lstat(selected);
|
|
13
|
+
if (info.isSymbolicLink() || !info.isDirectory())
|
|
14
|
+
throw new ProgramError('program/source-resolve-failed', `Program root ${src} must contain only ordinary directories.`);
|
|
15
|
+
}
|
|
16
|
+
const files = [];
|
|
17
|
+
let total = 0;
|
|
18
|
+
let visited = 0;
|
|
19
|
+
const visit = async (current, prefix) => {
|
|
20
|
+
const entries = await readdir(current, { withFileTypes: true });
|
|
21
|
+
for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
|
|
22
|
+
const path = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
|
|
23
|
+
checkProgramPath(path);
|
|
24
|
+
if (++visited > PROGRAM_LIMITS.maxFiles * PROGRAM_LIMITS.maxDepth)
|
|
25
|
+
throw new ProgramError('program/resource-limit', 'Program directory traversal exceeds the fixed limit.');
|
|
26
|
+
const file = resolve(current, entry.name);
|
|
27
|
+
if (entry.isDirectory())
|
|
28
|
+
await visit(file, path);
|
|
29
|
+
else if (entry.isFile()) {
|
|
30
|
+
if (files.length >= PROGRAM_LIMITS.maxFiles)
|
|
31
|
+
throw new ProgramError('program/resource-limit', 'Program file count exceeds the fixed limit.');
|
|
32
|
+
const actual = await realpath(file);
|
|
33
|
+
const child = relative(selected, actual);
|
|
34
|
+
if (isAbsolute(child) ||
|
|
35
|
+
child === '..' ||
|
|
36
|
+
child.startsWith('..\\') ||
|
|
37
|
+
child.startsWith('../'))
|
|
38
|
+
throw new ProgramError('program/source-resolve-failed', `Program file ${path} leaves its root.`);
|
|
39
|
+
const handle = await open(file, 'r');
|
|
40
|
+
try {
|
|
41
|
+
const info = await handle.stat();
|
|
42
|
+
if (!info.isFile())
|
|
43
|
+
throw new ProgramError('program/source-resolve-failed', `Program file ${path} is not a regular file.`);
|
|
44
|
+
const capacity = Math.min(PROGRAM_LIMITS.maxFileBytes, PROGRAM_LIMITS.maxTotalBytes - total);
|
|
45
|
+
if (info.size > capacity)
|
|
46
|
+
throw new ProgramError('program/resource-limit', `Program file ${path} exceeds the fixed byte limits.`);
|
|
47
|
+
const data = new Uint8Array(info.size);
|
|
48
|
+
let read = 0;
|
|
49
|
+
while (read < data.length) {
|
|
50
|
+
const result = await handle.read(data, read, data.length - read, read);
|
|
51
|
+
if (result.bytesRead === 0)
|
|
52
|
+
throw new ProgramError('program/source-resolve-failed', `Program file ${path} changed while reading.`);
|
|
53
|
+
read += result.bytesRead;
|
|
54
|
+
}
|
|
55
|
+
if ((await handle.read(new Uint8Array(1), 0, 1, read)).bytesRead !== 0)
|
|
56
|
+
throw new ProgramError('program/source-resolve-failed', `Program file ${path} changed while reading.`);
|
|
57
|
+
total += data.length;
|
|
58
|
+
files.push({ path, data });
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
await handle.close();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
else
|
|
65
|
+
throw new ProgramError('program/source-resolve-failed', `Program path ${path} is a link or special file.`);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
await visit(selected, '');
|
|
69
|
+
return files;
|
|
70
|
+
}
|
|
71
|
+
function record(value) {
|
|
72
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
73
|
+
}
|
|
74
|
+
export async function readDirectoryPackage(directory) {
|
|
75
|
+
const root = await realpath(directory);
|
|
76
|
+
const release = parseStrictJson(await readFile(resolve(root, 'release.json'), 'utf8'));
|
|
77
|
+
if (!record(release) ||
|
|
78
|
+
typeof release.id !== 'string' ||
|
|
79
|
+
typeof release.version !== 'string' ||
|
|
80
|
+
!record(release.files) ||
|
|
81
|
+
Object.keys(release).some((key) => !['id', 'version', 'files'].includes(key))) {
|
|
82
|
+
throw new Error(`Invalid release.json in ${root}`);
|
|
83
|
+
}
|
|
84
|
+
const files = Object.create(null);
|
|
85
|
+
for (const [path, file] of Object.entries(release.files)) {
|
|
86
|
+
if (!isPackagePath(path) ||
|
|
87
|
+
!record(file) ||
|
|
88
|
+
typeof file.size !== 'number' ||
|
|
89
|
+
!Number.isSafeInteger(file.size) ||
|
|
90
|
+
file.size < 0 ||
|
|
91
|
+
typeof file.integrity !== 'string' ||
|
|
92
|
+
!/^sha256:[a-f0-9]{64}$/.test(file.integrity) ||
|
|
93
|
+
Object.keys(file).some((key) => !['size', 'integrity'].includes(key))) {
|
|
94
|
+
throw new Error(`Invalid release file ${path} in ${root}`);
|
|
95
|
+
}
|
|
96
|
+
files[path] = Object.freeze({ size: file.size, integrity: file.integrity });
|
|
97
|
+
}
|
|
98
|
+
const identity = { id: release.id, version: release.version, files: Object.freeze(files) };
|
|
99
|
+
const lock = Object.freeze({
|
|
100
|
+
id: identity.id,
|
|
101
|
+
version: identity.version,
|
|
102
|
+
integrity: await releaseIntegrity(identity),
|
|
103
|
+
});
|
|
104
|
+
return Object.freeze({
|
|
105
|
+
lock,
|
|
106
|
+
files: identity.files,
|
|
107
|
+
async read(path) {
|
|
108
|
+
if (!isPackagePath(path) || !Object.hasOwn(files, path))
|
|
109
|
+
throw new Error(`Undeclared package file ${path}`);
|
|
110
|
+
const file = await realpath(resolve(root, ...path.split('/')));
|
|
111
|
+
const child = relative(root, file);
|
|
112
|
+
if (isAbsolute(child) ||
|
|
113
|
+
child === '..' ||
|
|
114
|
+
child.startsWith('..\\') ||
|
|
115
|
+
child.startsWith('../') ||
|
|
116
|
+
!(await stat(file)).isFile()) {
|
|
117
|
+
throw new Error(`Package file ${path} escapes ${root} or is not a regular file`);
|
|
118
|
+
}
|
|
119
|
+
return new Uint8Array(await readFile(file));
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
export function createDirectoryRegistry(directories) {
|
|
124
|
+
const roots = { ...directories };
|
|
125
|
+
return {
|
|
126
|
+
async open(lock) {
|
|
127
|
+
const directory = Object.hasOwn(roots, lock.id) ? roots[lock.id] : undefined;
|
|
128
|
+
if (directory === undefined)
|
|
129
|
+
throw new Error(`No local package configured for ${lock.id}`);
|
|
130
|
+
const source = await readDirectoryPackage(directory);
|
|
131
|
+
if (source.lock.id !== lock.id ||
|
|
132
|
+
source.lock.version !== lock.version ||
|
|
133
|
+
source.lock.integrity !== lock.integrity) {
|
|
134
|
+
throw new Error(`Local package ${lock.id} differs from its dependency lock; refresh the dependency lock explicitly`);
|
|
135
|
+
}
|
|
136
|
+
return source;
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { DeviceLock, DeviceRegistry, PackageFile, PackageFiles, UnifiedDeviceManifest } from '@mica-js/document/fused';
|
|
2
|
+
/**
|
|
3
|
+
* Host API version this runtime implements.
|
|
4
|
+
*
|
|
5
|
+
* `engines.mica` names the host API, not the npm version of this package: the fused device runtime
|
|
6
|
+
* implements API `1.0.0`, so manifests declare ranges such as `^1.0.0`. A package outside the range
|
|
7
|
+
* is rejected before anything is loaded.
|
|
8
|
+
*/
|
|
9
|
+
export declare const MICA_HOST_API_VERSION = "1.0.0";
|
|
10
|
+
/** One locked package whose identity and files were verified against the lock. */
|
|
11
|
+
export interface VerifiedPackage {
|
|
12
|
+
readonly lock: DeviceLock;
|
|
13
|
+
readonly manifest: UnifiedDeviceManifest;
|
|
14
|
+
/** Verified read interface handed to the caller-supplied module loader. */
|
|
15
|
+
readonly source: PackageFiles;
|
|
16
|
+
/** Snapshot of the declared release file list, keyed by package-root relative path. */
|
|
17
|
+
readonly files: Readonly<Record<string, PackageFile>>;
|
|
18
|
+
/** Reads and verifies one declared file; every call returns independent bytes. */
|
|
19
|
+
read(path: string, maxBytes?: number): Promise<Uint8Array>;
|
|
20
|
+
}
|
|
21
|
+
/** Whether `path` is a normalized package-root relative POSIX path (RFC 0020). */
|
|
22
|
+
export declare function isPackagePath(path: string): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Opens one locked package and verifies everything that does not need code execution.
|
|
25
|
+
*
|
|
26
|
+
* @throws {PreparationError} with the RFC 0020 diagnostic codes of every problem found.
|
|
27
|
+
*/
|
|
28
|
+
export declare function openDevicePackage(registry: DeviceRegistry, lock: DeviceLock, hostApiVersion?: string): Promise<VerifiedPackage>;
|
|
29
|
+
export declare function releaseIntegrity(release: {
|
|
30
|
+
readonly id: string;
|
|
31
|
+
readonly version: string;
|
|
32
|
+
readonly files: Readonly<Record<string, PackageFile>>;
|
|
33
|
+
}): Promise<string>;
|
|
34
|
+
/**
|
|
35
|
+
* Whether `version` satisfies the SemVer range of `engines.mica`.
|
|
36
|
+
*
|
|
37
|
+
* Delegates to the `semver` package, so prereleases, X-ranges, hyphen ranges and partial versions
|
|
38
|
+
* follow the standard semantics instead of an approximation.
|
|
39
|
+
*/
|
|
40
|
+
export declare function satisfiesRange(version: string, range: string): boolean;
|