@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,209 @@
1
+ import { existsSync, watch } from 'node:fs';
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { dirname, join, resolve, sep } from 'node:path';
4
+ import { loadDevicePackage } from './unified-manifest.js';
5
+ import { renderDeviceDeclaration, renderDeviceTypeScriptConfig } from './unified-types.js';
6
+ /** Directory below the project root that holds the generated type environment. */
7
+ export const DEVICE_TYPE_DIRECTORY = '.mica';
8
+ /** Generated global declaration file of a unified device project. */
9
+ export const DEVICE_DECLARATION_FILE = 'device.d.ts';
10
+ /** Generated TypeScript configuration that device projects extend. */
11
+ export const DEVICE_TSCONFIG_FILE = 'tsconfig.json';
12
+ const DEFAULT_DEBOUNCE_MS = 50;
13
+ /**
14
+ * Validates the device manifest and DDL and writes `.mica/device.d.ts` and `.mica/tsconfig.json`.
15
+ *
16
+ * Preparation never executes an author module: it reads JSON, compiles DDL and renders types. A
17
+ * file whose content is unchanged keeps its previous bytes and timestamp, so a watching compiler
18
+ * is not disturbed by repeated runs. A failing run reports the original manifest or DDL error and
19
+ * leaves the previous type environment in place; the build is still prevented from running.
20
+ */
21
+ export async function prepareDevice(options) {
22
+ const root = resolve(options.root);
23
+ const device = await loadDevicePackage({
24
+ root,
25
+ sourceDir: options.sourceDir,
26
+ manifest: options.manifest,
27
+ ...(options.model === undefined ? {} : { model: options.model }),
28
+ });
29
+ const declaration = renderDeviceDeclaration({
30
+ manifest: device.manifest,
31
+ ...(device.model === undefined ? {} : { model: device.model }),
32
+ manifestPath: options.manifest,
33
+ });
34
+ const directory = join(root, DEVICE_TYPE_DIRECTORY);
35
+ const declarationFile = join(directory, DEVICE_DECLARATION_FILE);
36
+ const tsconfigFile = join(directory, DEVICE_TSCONFIG_FILE);
37
+ await mkdir(directory, { recursive: true });
38
+ await writeIfChanged(declarationFile, declaration);
39
+ await writeIfChanged(tsconfigFile, renderDeviceTypeScriptConfig(options.sourceDir));
40
+ return { files: [declarationFile, tsconfigFile], device };
41
+ }
42
+ /**
43
+ * Regenerates the type environment whenever the manifest, the DDL model or the project config
44
+ * changes. Inputs are re-resolved on every run, so editing the config or renaming a declared file
45
+ * retargets the watchers. Generated writes never feed back into the loop.
46
+ */
47
+ export function watchDevice(options) {
48
+ return watchPreparation({
49
+ ...options,
50
+ inputs: (loaded) => [
51
+ resolve(loaded.root, loaded.manifest),
52
+ ...(loaded.model === undefined ? [] : [resolve(loaded.root, loaded.model)]),
53
+ ...(loaded.configFile === undefined ? [] : [loaded.configFile]),
54
+ ],
55
+ prepare: async (loaded) => (await prepareDevice(loaded)).files,
56
+ });
57
+ }
58
+ export function watchPreparation(options) {
59
+ const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
60
+ let disposed = false;
61
+ let queued = false;
62
+ let timer;
63
+ let current;
64
+ let targets = new Set();
65
+ const watchers = new Map();
66
+ const report = (error) => {
67
+ if (options.onError === undefined) {
68
+ console.error('mica prepare --watch:', error);
69
+ return;
70
+ }
71
+ try {
72
+ options.onError(error);
73
+ }
74
+ catch (reportingError) {
75
+ console.error('mica prepare --watch:', error);
76
+ console.error('mica prepare --watch error handler failed:', reportingError);
77
+ }
78
+ };
79
+ const syncWatchers = (files) => {
80
+ const next = new Set(files.map((file) => resolve(file)));
81
+ const directories = new Set([...next].map((file) => {
82
+ let directory = dirname(file);
83
+ while (!existsSync(directory) && dirname(directory) !== directory)
84
+ directory = dirname(directory);
85
+ return directory;
86
+ }));
87
+ for (const [directory, watcher] of watchers) {
88
+ if (directories.has(directory))
89
+ continue;
90
+ watcher.close();
91
+ watchers.delete(directory);
92
+ }
93
+ targets = next;
94
+ for (const directory of directories) {
95
+ if (watchers.has(directory))
96
+ continue;
97
+ let watcher;
98
+ try {
99
+ watcher = watch(directory, (_event, filename) => {
100
+ if (disposed)
101
+ return;
102
+ if (filename === null)
103
+ schedule();
104
+ else {
105
+ const changed = resolve(directory, filename.toString());
106
+ if ([...targets].some((file) => file === changed || file.startsWith(changed + sep)))
107
+ schedule();
108
+ }
109
+ });
110
+ }
111
+ catch (error) {
112
+ report(error);
113
+ continue;
114
+ }
115
+ watcher.on('error', (error) => {
116
+ if (!disposed)
117
+ report(error);
118
+ });
119
+ watchers.set(directory, watcher);
120
+ }
121
+ };
122
+ const scan = async () => {
123
+ let loaded;
124
+ try {
125
+ loaded = await options.load();
126
+ }
127
+ catch (error) {
128
+ if (!disposed)
129
+ report(error);
130
+ return [];
131
+ }
132
+ try {
133
+ syncWatchers(options.inputs(loaded));
134
+ const files = await options.prepare(loaded);
135
+ options.onPrepare?.(files);
136
+ return files;
137
+ }
138
+ catch (error) {
139
+ if (!disposed)
140
+ report(error);
141
+ return [];
142
+ }
143
+ };
144
+ const drain = async () => {
145
+ for (;;) {
146
+ queued = false;
147
+ const files = await scan();
148
+ if (!queued || disposed)
149
+ return files;
150
+ }
151
+ };
152
+ const schedule = () => {
153
+ if (disposed)
154
+ return;
155
+ if (timer !== undefined)
156
+ clearTimeout(timer);
157
+ timer = setTimeout(() => {
158
+ timer = undefined;
159
+ run();
160
+ }, debounceMs);
161
+ };
162
+ const start = () => {
163
+ const task = drain();
164
+ current = task;
165
+ void task.finally(() => {
166
+ if (current === task)
167
+ current = undefined;
168
+ if (queued && !disposed)
169
+ schedule();
170
+ });
171
+ return task;
172
+ };
173
+ const run = () => {
174
+ if (disposed)
175
+ return;
176
+ if (current)
177
+ queued = true;
178
+ else
179
+ start();
180
+ };
181
+ const ready = start();
182
+ return {
183
+ ready,
184
+ async dispose() {
185
+ if (disposed)
186
+ return;
187
+ disposed = true;
188
+ if (timer !== undefined) {
189
+ clearTimeout(timer);
190
+ timer = undefined;
191
+ }
192
+ for (const watcher of watchers.values())
193
+ watcher.close();
194
+ watchers.clear();
195
+ await current;
196
+ },
197
+ };
198
+ }
199
+ async function writeIfChanged(file, content) {
200
+ try {
201
+ if ((await readFile(file, 'utf8')) === content)
202
+ return;
203
+ }
204
+ catch (error) {
205
+ if (error.code !== 'ENOENT')
206
+ throw error;
207
+ }
208
+ await writeFile(file, content, 'utf8');
209
+ }
@@ -0,0 +1,20 @@
1
+ import { type DeviceIR } from '@mica-js/ddl';
2
+ import type { UnifiedDeviceManifest } from '@mica-js/document/fused';
3
+ /** Fixed global names of the generated device type environment. */
4
+ export declare const DEVICE_GLOBAL_TYPES: readonly ["DeviceProps", "DeviceMethods", "DeviceEvents", "DeviceModelContext", "DeviceFactory", "DeviceClient", "DevicePinId"];
5
+ /**
6
+ * Renders `.mica/device.d.ts`.
7
+ *
8
+ * The declaration provides the fixed global names of the device project. Property, method and
9
+ * event shapes come from the manifest; the input, memory and output projections of the core
10
+ * context come from the compiled DDL. The manifest is the only source of public types, so a model
11
+ * implementation and a display implementation share the same names.
12
+ */
13
+ export declare function renderDeviceDeclaration(input: {
14
+ readonly manifest: UnifiedDeviceManifest;
15
+ readonly model?: DeviceIR;
16
+ readonly manifestPath: string;
17
+ }): string;
18
+ /** Renders `.mica/tsconfig.json`, which every device project extends. */
19
+ export declare function renderDeviceTypeScriptConfig(sourceDir: string): string;
20
+ export declare function renderModelTypeNamespace(manifest: UnifiedDeviceManifest, name: string): string;
@@ -0,0 +1,253 @@
1
+ import { generateDeviceTypeScript } from '@mica-js/ddl';
2
+ /** Prefix of the DDL projection embedded in the generated declaration. */
3
+ const PROJECTION = 'Mica';
4
+ /** Fixed global names of the generated device type environment. */
5
+ export const DEVICE_GLOBAL_TYPES = [
6
+ 'DeviceProps',
7
+ 'DeviceMethods',
8
+ 'DeviceEvents',
9
+ 'DeviceModelContext',
10
+ 'DeviceFactory',
11
+ 'DeviceClient',
12
+ 'DevicePinId',
13
+ ];
14
+ const DEVICE_MODULE = '@mica-js/sdk/device';
15
+ /**
16
+ * Prefix of the aliases generated for `model.types`.
17
+ *
18
+ * Payload type names are author chosen, so they may collide with imported names, the generated
19
+ * `Batch` / `CoreContext` aliases, the global device names or TypeScript keywords. Every public
20
+ * payload name is therefore aliased; refs resolve through the same map.
21
+ */
22
+ const PAYLOAD_PREFIX = 'MicaPayload_';
23
+ /**
24
+ * Renders `.mica/device.d.ts`.
25
+ *
26
+ * The declaration provides the fixed global names of the device project. Property, method and
27
+ * event shapes come from the manifest; the input, memory and output projections of the core
28
+ * context come from the compiled DDL. The manifest is the only source of public types, so a model
29
+ * implementation and a display implementation share the same names.
30
+ */
31
+ export function renderDeviceDeclaration(input) {
32
+ const { manifest, model } = input;
33
+ const used = new Set([
34
+ 'DeviceBatch',
35
+ 'DeviceContext',
36
+ 'ModelClient',
37
+ 'ModelContext',
38
+ 'ModelInstance',
39
+ ]);
40
+ const props = renderProperties(manifest, used);
41
+ const methods = renderMethods(manifest);
42
+ const events = renderEvents(manifest);
43
+ const pinIds = Object.keys(manifest.pins ?? {});
44
+ const core = model === undefined
45
+ ? [
46
+ 'type Batch = DeviceBatch<Record<never, never>>;',
47
+ 'type CoreContext = DeviceContext<DeviceProps, Record<never, never>, Record<never, never>>;',
48
+ ]
49
+ : [
50
+ `type Batch = DeviceBatch<${PROJECTION}Outputs>;`,
51
+ `type CoreContext = DeviceContext<DeviceProps, ${PROJECTION}Inputs, ${PROJECTION}Memory>;`,
52
+ ];
53
+ // The DDL projection brings its own type-only imports; merge them into the single import
54
+ // statement below, because two import declarations binding the same name do not compile.
55
+ const projection = model === undefined
56
+ ? { imports: [], lines: [] }
57
+ : splitProjection(generateDeviceTypeScript(model, {
58
+ deviceModule: DEVICE_MODULE,
59
+ name: PROJECTION,
60
+ }).trimEnd());
61
+ for (const name of projection.imports)
62
+ used.add(name);
63
+ return [
64
+ `// Generated by @mica-js/sdk from ${input.manifestPath}; do not edit.`,
65
+ '// The global names below are available to every source file of this device project.',
66
+ '',
67
+ 'import type {',
68
+ ...[...used].sort().map((name) => ` ${name},`),
69
+ `} from '${DEVICE_MODULE}';`,
70
+ '',
71
+ ...projection.lines,
72
+ ...renderTypes(manifest),
73
+ ...core,
74
+ '',
75
+ 'declare global {',
76
+ ' type DeviceProps = {',
77
+ ...props.map((line) => ` ${line}`),
78
+ ' };',
79
+ ' type DeviceMethods = {',
80
+ ...methods.map((line) => ` ${line}`),
81
+ ' };',
82
+ ' type DeviceEvents = {',
83
+ ...events.map((line) => ` ${line}`),
84
+ ' };',
85
+ ' type DeviceModelContext = ModelContext<CoreContext, DeviceProps, DeviceEvents>;',
86
+ ' type DeviceFactory = (context: DeviceModelContext) => ModelInstance<DeviceMethods, Batch>;',
87
+ ' type DeviceClient = ModelClient<DeviceMethods, DeviceEvents>;',
88
+ ` type DevicePinId = ${pinIds.length === 0 ? 'never' : pinIds.map((pin) => JSON.stringify(pin)).join(' | ')};`,
89
+ '}',
90
+ '',
91
+ 'export {};',
92
+ '',
93
+ ].join('\n');
94
+ }
95
+ /** Renders `.mica/tsconfig.json`, which every device project extends. */
96
+ export function renderDeviceTypeScriptConfig(sourceDir) {
97
+ const include = `../${sourceDir.replaceAll('\\', '/').replace(/\/+$/, '')}`;
98
+ const config = {
99
+ compilerOptions: {
100
+ target: 'ES2022',
101
+ module: 'ESNext',
102
+ moduleResolution: 'Bundler',
103
+ customConditions: ['source'],
104
+ lib: ['ES2023', 'DOM'],
105
+ types: [],
106
+ strict: true,
107
+ noEmit: true,
108
+ skipLibCheck: true,
109
+ allowArbitraryExtensions: true,
110
+ verbatimModuleSyntax: true,
111
+ },
112
+ files: ['./device.d.ts'],
113
+ include: [include],
114
+ };
115
+ return `${JSON.stringify(config, null, 2)}\n`;
116
+ }
117
+ export function renderModelTypeNamespace(manifest, name) {
118
+ return [
119
+ `declare namespace ${name} {`,
120
+ ...renderTypes(manifest),
121
+ 'export type Methods = {',
122
+ ...renderMethods(manifest),
123
+ '};',
124
+ 'export type Events = {',
125
+ ...renderEvents(manifest),
126
+ '};',
127
+ '}',
128
+ ].join('\n');
129
+ }
130
+ /**
131
+ * Splits the DDL projection into its type-only import names and the remaining module body.
132
+ *
133
+ * The projection is generated by `@mica-js/ddl` and declares one single-line
134
+ * `import type { ... } from '<device module>';` statement.
135
+ */
136
+ function splitProjection(source) {
137
+ const imports = [];
138
+ const lines = [];
139
+ for (const line of source.split('\n')) {
140
+ const match = /^import type \{ (.*) \} from ["'][^"']*["'];$/.exec(line.trim());
141
+ if (match?.[1] !== undefined) {
142
+ for (const name of match[1].split(',')) {
143
+ const trimmed = name.trim();
144
+ if (trimmed.length > 0)
145
+ imports.push(trimmed);
146
+ }
147
+ continue;
148
+ }
149
+ lines.push(line);
150
+ }
151
+ while (lines.length > 0 && lines[0]?.trim() === '')
152
+ lines.shift();
153
+ return { imports, lines };
154
+ }
155
+ function renderProperties(manifest, used) {
156
+ return Object.entries(manifest.properties ?? {}).map(([name, property]) => `readonly ${name}: ${propertyType(property, used)};`);
157
+ }
158
+ function propertyType(property, used) {
159
+ let type;
160
+ switch (property.type) {
161
+ case 'number':
162
+ case 'integer':
163
+ type = 'number';
164
+ break;
165
+ case 'string':
166
+ case 'color':
167
+ type = 'string';
168
+ break;
169
+ case 'boolean':
170
+ type = 'boolean';
171
+ break;
172
+ case 'enum': {
173
+ const options = (property.options ?? []).map((option) => JSON.stringify(option.value));
174
+ type = options.length === 0 ? 'never' : options.join(' | ');
175
+ break;
176
+ }
177
+ case 'image':
178
+ case 'binary':
179
+ used.add('ReadonlyBytes');
180
+ type = 'ReadonlyBytes';
181
+ break;
182
+ case 'firmware':
183
+ used.add('FirmwareImage');
184
+ type = 'FirmwareImage';
185
+ break;
186
+ case 'program':
187
+ type = property.loader === 'filesystem' ? 'ProgramFiles' : 'MemoryProgram';
188
+ used.add(type);
189
+ break;
190
+ }
191
+ return property.nullable === true ? `${type} | null` : type;
192
+ }
193
+ function renderMethods(manifest) {
194
+ const types = payloadTypes(manifest);
195
+ return Object.entries(manifest.model?.methods ?? {}).map(([name, method]) => `readonly ${name}: (params: ${valueType(method.params, types, 0)}) => ${valueType(method.returns, types, 0)};`);
196
+ }
197
+ function renderEvents(manifest) {
198
+ const types = payloadTypes(manifest);
199
+ return Object.entries(manifest.model?.events ?? {}).map(([name, type]) => `readonly ${name}: ${valueType(type, types, 0)};`);
200
+ }
201
+ /** Public payload type names are ASCII identifiers, so the alias is always valid. */
202
+ const PAYLOAD_NAME = /^[A-Za-z][A-Za-z0-9]*$/;
203
+ function payloadAlias(name) {
204
+ if (!PAYLOAD_NAME.test(name))
205
+ throw new Error(`model.types: invalid payload type name '${name}'`);
206
+ return PAYLOAD_PREFIX + name;
207
+ }
208
+ function payloadTypes(manifest) {
209
+ return new Set(Object.keys(manifest.model?.types ?? {}));
210
+ }
211
+ /** Named payload types of `model.types`, in manifest order. */
212
+ function renderTypes(manifest) {
213
+ const lines = [];
214
+ for (const [name, type] of Object.entries(manifest.model?.types ?? {}))
215
+ lines.push(`type ${payloadAlias(name)} = ${valueType(type, payloadTypes(manifest), 0)};`, '');
216
+ return lines;
217
+ }
218
+ function valueType(type, types, level) {
219
+ if ('ref' in type) {
220
+ if (!types.has(type.ref))
221
+ throw new Error(`model.types: unknown payload type '${type.ref}'`);
222
+ return payloadAlias(type.ref);
223
+ }
224
+ switch (type.type) {
225
+ case 'null':
226
+ return 'null';
227
+ case 'boolean':
228
+ return 'boolean';
229
+ case 'number':
230
+ return 'number';
231
+ case 'string':
232
+ return 'string';
233
+ case 'binary':
234
+ return 'Uint8Array';
235
+ case 'array':
236
+ return `ReadonlyArray<${valueType(type.items, types, level)}>`;
237
+ case 'object': {
238
+ const indent = ' '.repeat(level + 1);
239
+ const optional = type.optional ?? [];
240
+ const members = Object.entries(type.properties).map(([key, item]) => `${indent}readonly ${JSON.stringify(key)}${optional.includes(key) ? '?' : ''}: ${valueType(item, types, level + 1)};`);
241
+ if (type.additionalProperties !== undefined) {
242
+ const index = new Set(Object.values(type.properties).map((item) => valueType(item, types, level + 1)));
243
+ if (optional.length > 0)
244
+ index.add('undefined');
245
+ index.add(valueType(type.additionalProperties, types, level + 1));
246
+ members.push(`${indent}readonly [key: string]: ${[...index].sort().join(' | ')};`);
247
+ }
248
+ if (members.length === 0)
249
+ return 'Readonly<Record<string, never>>';
250
+ return `{\n${members.join('\n')}\n${' '.repeat(level)}}`;
251
+ }
252
+ }
253
+ }
package/dist/device.d.ts CHANGED
@@ -1 +1,13 @@
1
- export type { BorrowedBytes, ReadonlyBytes, ChannelMessage, Notification, DeviceAdapter, DeviceBatch, DeviceContext, DeviceFactory, InputChannel, InputNotification, TopicBridge, TopicMessage, JitHost, JitOptions, JitTranslate, JitTranslateInput, InstructionHook, Disposable, Event, } from '@mica-js/simulator';
1
+ export type { BorrowedBytes, ReadonlyBytes, ChannelMessage, Notification, DeviceAdapter, DeviceBatch, DeviceContext, DeviceFactory, InputChannel, InputNotification, TopicBridge, TopicMessage, JitHost, JitOptions, JitTranslate, JitTranslateInput, JitDelay, JitPolling, InstructionHook, Disposable, Event, } from '@mica-js/simulator';
2
+ /**
3
+ * Author-facing contracts of the unified device model (RFC 0021) and its property values
4
+ * (RFC 0026).
5
+ *
6
+ * Model entries and display entries import the model context, instance, client and payload types
7
+ * from this entry. Runtime implementations (`createHeadlessRuntime`, `prepareFusedSession`,
8
+ * package opening, firmware decoding) and host preparation types stay in `@mica-js/sdk/fused`.
9
+ */
10
+ export type { AsyncMethods, EventListeners, Methods, ModelClient, ModelContext, ModelEvent, ModelEventEmitter, ModelEvents, ModelFactory, ModelInstance, ModelModule, Params, Result, Value, ValueType, } from './fused/model.js';
11
+ export type { MethodError } from './fused/model.js';
12
+ export type { FirmwareImage, FirmwareSegment } from '@mica-js/document/fused';
13
+ export type { MemoryProgram, ProgramFiles, ProgramSegment } from '@mica-js/document/fused';
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Cross-check of a compiled model IR against its manifest (RFC 0020 / RFC 0021).
3
+ *
4
+ * The rules mirror the SDK build (`build/unified-manifest.ts` `assertModelAgreement`), so a package
5
+ * the build accepts is accepted here and a hand-written module cannot quietly disagree with its
6
+ * manifest: pin sets are equal, every DDL property is declared with an equivalent type, the same
7
+ * nullability, the same enum members and the same default value. Defaults are evaluated with the
8
+ * build's own pure evaluator, so a default it can prove is proven here and a default it cannot
9
+ * prove is rejected explicitly instead of being trusted.
10
+ */
11
+ import type { DeviceIR } from '@mica-js/device-model';
12
+ import type { UnifiedDeviceManifest } from '@mica-js/document/fused';
13
+ import type { PreparationProblem } from './diagnostics.js';
14
+ /** Returns every disagreement between the manifest and the model IR. */
15
+ export declare function checkModelAgreement(manifest: UnifiedDeviceManifest, model: DeviceIR): PreparationProblem[];
@@ -0,0 +1,104 @@
1
+ import { evaluateConstant } from '../build/unified-defaults.js';
2
+ import { problem } from './diagnostics.js';
3
+ /** Manifest property types an IR property kind may map onto; identical to the build's table. */
4
+ const IR_PROPERTY_TYPES = {
5
+ number: ['number', 'integer'],
6
+ string: ['string', 'color'],
7
+ bool: ['boolean'],
8
+ bytes: ['binary', 'image'],
9
+ };
10
+ /** Returns every disagreement between the manifest and the model IR. */
11
+ export function checkModelAgreement(manifest, model) {
12
+ const problems = [];
13
+ const add = (message, pointer) => {
14
+ problems.push(problem('model/invalid-interface', message, pointer));
15
+ };
16
+ const irPins = model.declarations.flatMap((declaration) => declaration.kind === 'pin' ? [declaration.name] : []);
17
+ const manifestPins = Object.keys(manifest.pins ?? {});
18
+ const missing = irPins.filter((pin) => !manifestPins.includes(pin));
19
+ const undeclared = manifestPins.filter((pin) => !irPins.includes(pin));
20
+ if (missing.length > 0 || undeclared.length > 0) {
21
+ add(`Pins of ${manifest.publisher}:${manifest.name} differ between manifest and model IR ` +
22
+ `(model only: ${missing.join(', ') || 'none'}; manifest only: ${undeclared.join(', ') || 'none'}).`, '/pins');
23
+ }
24
+ const properties = manifest.properties ?? {};
25
+ // DDL `const` declarations stay available to a default expression.
26
+ const constants = new Map(model.declarations.flatMap((declaration) => declaration.kind === 'const' ? [[declaration.name, declaration.value]] : []));
27
+ const enums = new Map(model.declarations.flatMap((declaration) => declaration.kind === 'enum' ? [[declaration.name, declaration.members]] : []));
28
+ for (const declaration of model.declarations) {
29
+ if (declaration.kind !== 'property') {
30
+ continue;
31
+ }
32
+ const pointer = `/properties/${declaration.name}`;
33
+ const descriptor = properties[declaration.name];
34
+ if (descriptor === undefined) {
35
+ add(`The model IR declares the property "${declaration.name}" the manifest does not describe.`, pointer);
36
+ continue;
37
+ }
38
+ const optional = declaration.type.kind === 'optional';
39
+ const plain = optional ? declaration.type.inner : declaration.type;
40
+ if (plain.kind === 'enum') {
41
+ if (descriptor.type !== 'enum') {
42
+ add(`Property "${declaration.name}" is an enum in the model IR but ${descriptor.type} in the manifest.`, pointer);
43
+ }
44
+ else {
45
+ const expected = [...(enums.get(plain.name) ?? [])].sort().join('\u0000');
46
+ const actual = (descriptor.options ?? [])
47
+ .map((option) => option.value)
48
+ .sort()
49
+ .join('\u0000');
50
+ if (expected !== actual) {
51
+ add(`Options of property "${declaration.name}" must match the model enum members.`, pointer);
52
+ }
53
+ }
54
+ }
55
+ else if (!IR_PROPERTY_TYPES[plain.kind]?.includes(descriptor.type)) {
56
+ add(`Property "${declaration.name}" is ${plain.kind} in the model IR but ${descriptor.type} in the manifest.`, pointer);
57
+ }
58
+ if (optional !== (descriptor.nullable === true)) {
59
+ add(optional
60
+ ? `Property "${declaration.name}" is optional in the model IR but the manifest does not set nullable.`
61
+ : `Property "${declaration.name}" is not optional in the model IR but the manifest sets nullable.`, pointer);
62
+ }
63
+ const hasDefault = Object.hasOwn(descriptor, 'default');
64
+ // Both sides must agree on whether a default exists at all (same rule as the SDK build).
65
+ if ((declaration.default === undefined) === hasDefault) {
66
+ add(declaration.default === undefined
67
+ ? `The manifest declares a default for "${declaration.name}" the model IR does not.`
68
+ : `The model IR declares a default for "${declaration.name}" the manifest does not.`, `${pointer}/default`);
69
+ continue;
70
+ }
71
+ if (declaration.default === undefined) {
72
+ continue;
73
+ }
74
+ const evaluation = evaluateConstant(declaration.default, constants);
75
+ if (!evaluation.known) {
76
+ add(`The default of "${declaration.name}" cannot be verified before a factory runs: ${evaluation.reason}.`, `${pointer}/default`);
77
+ continue;
78
+ }
79
+ if (!sameValue(evaluation.value, descriptor.default)) {
80
+ add(`The manifest default of "${declaration.name}" must equal the model IR default.`, `${pointer}/default`);
81
+ }
82
+ }
83
+ return problems;
84
+ }
85
+ /** Equality used by the build: `Object.is` for numbers, deep data comparison otherwise. */
86
+ function sameValue(left, right) {
87
+ if (typeof left === 'number' && typeof right === 'number') {
88
+ return Object.is(left, right);
89
+ }
90
+ if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') {
91
+ return left === right;
92
+ }
93
+ if (Array.isArray(left) || Array.isArray(right)) {
94
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) {
95
+ return false;
96
+ }
97
+ return left.every((item, index) => sameValue(item, right[index]));
98
+ }
99
+ const keys = Object.keys(left);
100
+ if (keys.length !== Object.keys(right).length) {
101
+ return false;
102
+ }
103
+ return keys.every((key) => sameValue(left[key], right[key]));
104
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * One host-visible runtime diagnostic.
3
+ *
4
+ * `code` is a stable contract code (RFC 0020 / 0021 / 0024 / 0025 / 0026). `message` is meant for
5
+ * humans and carries the instance id, property name or package path that caused the problem.
6
+ */
7
+ export interface RuntimeDiagnostic {
8
+ readonly code: string;
9
+ readonly message: string;
10
+ readonly instanceId?: string;
11
+ }
12
+ export type DiagnosticSink = (diagnostic: RuntimeDiagnostic) => void;
13
+ export declare function diagnostic(code: string, message: string, instanceId?: string): RuntimeDiagnostic;
14
+ /** One preparation problem before it is attributed to an instance. */
15
+ export interface PreparationProblem {
16
+ readonly code: string;
17
+ readonly message: string;
18
+ /** JSON Pointer of the offending member; empty when the problem has no document location. */
19
+ readonly pointer: string;
20
+ }
21
+ /** Thrown while preparing a session; carries every problem found before failing. */
22
+ export declare class PreparationError extends Error {
23
+ readonly problems: readonly PreparationProblem[];
24
+ constructor(problems: readonly PreparationProblem[]);
25
+ get code(): string;
26
+ }
27
+ /** Thrown by {@link createHeadlessRuntime} when preparation fails; carries all diagnostics. */
28
+ export declare class FusedPreparationError extends Error {
29
+ readonly code: string;
30
+ readonly diagnostics: readonly RuntimeDiagnostic[];
31
+ constructor(diagnostics: readonly RuntimeDiagnostic[]);
32
+ }
33
+ export declare function problem(code: string, message: string, pointer?: string): PreparationProblem;
34
+ /**
35
+ * Normalizes a thrown value into preparation problems.
36
+ *
37
+ * Contract violations of `@mica-js/document/fused` already carry a code and a JSON Pointer per
38
+ * problem, so they are forwarded one to one instead of being flattened into one message.
39
+ */
40
+ export declare function asPreparation(cause: unknown, fallbackCode: string): readonly PreparationProblem[];
41
+ /** Collects the problems of one preparation phase and attributes them to an instance. */
42
+ export declare class DiagnosticBatch {
43
+ readonly problems: PreparationProblem[];
44
+ readonly instanceIds: (string | undefined)[];
45
+ add(cause: unknown, fallbackCode: string, instanceId?: string): void;
46
+ addProblem(entry: PreparationProblem, instanceId?: string): void;
47
+ fail(cause: unknown, fallbackCode: string, instanceId?: string): void;
48
+ get empty(): boolean;
49
+ /** Every collected problem as a host diagnostic, then clears the batch. */
50
+ drain(): RuntimeDiagnostic[];
51
+ }