@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,354 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
3
+ import { isBuiltin } from 'node:module';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, parse, resolve } from 'node:path';
6
+ import { build, normalizePath } from 'vite';
7
+ import { assertSelfContained, modelExpression, stripModelSource } from './content.js';
8
+ import { readProgramDirectory } from '../fused/node.js';
9
+ import { findSource, isContained, isFile, packagePath, sourceCandidates, sourcePaths, } from './unified-paths.js';
10
+ const HTML_REFERENCE = /\b(?:src|href)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gi;
11
+ const CSS_URL = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"\s]+))\s*\)/gi;
12
+ const CSS_IMPORT = /@import\s+(?:url\(\s*)?(?:"([^"]*)"|'([^']*)')/gi;
13
+ /**
14
+ * Builds every package file of a unified device.
15
+ *
16
+ * Each declared JS entry becomes one self-contained ESM module; declared and referenced assets are
17
+ * copied at their package path; HTML is copied together with its relative resources, and a
18
+ * referenced script module is bundled like any other entry. The authored manifest is emitted as
19
+ * the package manifest, so the package never ships different content than the validated manifest.
20
+ */
21
+ export async function collectDevicePackage(options) {
22
+ const sourceRoot = resolve(options.root, options.sourceDir);
23
+ const device = options.device;
24
+ const manifest = device.manifest;
25
+ const claims = new Map();
26
+ const scanned = new Set();
27
+ const claim = (path, origin, data) => {
28
+ packagePath(path, 'package file');
29
+ const existing = claims.get(path);
30
+ if (existing !== undefined) {
31
+ if (existing.origin === origin)
32
+ return;
33
+ throw new Error(`Two sources produce the package file '${path}': ${existing.origin} and ${origin}`);
34
+ }
35
+ claims.set(path, { origin, data });
36
+ };
37
+ const claimSource = async (path, field) => {
38
+ const source = await findSource(sourceRoot, path, field);
39
+ claim(path, source, new Uint8Array(await readFile(source)));
40
+ };
41
+ const emitModule = async (input) => {
42
+ const source = input.virtual === undefined
43
+ ? await findSource(sourceRoot, input.artifact, input.label)
44
+ : undefined;
45
+ const bundled = await bundleModule({
46
+ root: options.root,
47
+ ...(options.aliases === undefined ? {} : { aliases: options.aliases }),
48
+ minify: options.minify ?? true,
49
+ label: input.label,
50
+ input: source ?? '',
51
+ ...(input.virtual === undefined ? {} : { virtual: input.virtual }),
52
+ });
53
+ const missing = input.requiredNamed.filter((name) => !bundled.exports.includes(name));
54
+ if (missing.length > 0)
55
+ throw new Error(`${input.label}: the module must export ${missing.join(', ')}`);
56
+ if (input.defaultExport === true && !bundled.exports.includes('default'))
57
+ throw new Error(`${input.label}: the module must have a default export`);
58
+ claim(input.artifact, source ?? `${input.label} (generated)`, Buffer.from(bundled.code));
59
+ };
60
+ const emitReference = async (from, raw, label) => {
61
+ const target = resolveReference(from, raw, label);
62
+ if (target === undefined || scanned.has(target))
63
+ return;
64
+ scanned.add(target);
65
+ if (/\.m?js$/i.test(target)) {
66
+ await emitModule({
67
+ artifact: target,
68
+ label: `module '${target}' referenced by ${label}`,
69
+ requiredNamed: [],
70
+ });
71
+ return;
72
+ }
73
+ const source = await findSource(sourceRoot, target, `resource '${target}' referenced by ${label}`);
74
+ const data = new Uint8Array(await readFile(source));
75
+ claim(target, source, data);
76
+ if (/\.css$/i.test(target)) {
77
+ for (const reference of cssReferences(Buffer.from(data).toString('utf8')))
78
+ await emitReference(packageDirectory(target), reference, `stylesheet '${target}'`);
79
+ }
80
+ };
81
+ claim('package.json', 'device manifest', Buffer.from(`${JSON.stringify(device.authored, null, 2)}\n`));
82
+ const model = manifest.model;
83
+ if (model !== undefined) {
84
+ if (device.model === undefined) {
85
+ await emitModule({
86
+ artifact: model.entry,
87
+ label: `model entry '${model.entry}'`,
88
+ requiredNamed: ['model', 'create'],
89
+ });
90
+ }
91
+ else {
92
+ const adapter = await findOptionalSource(sourceRoot, model.entry);
93
+ const ir = modelExpression(stripModelSource(device.model));
94
+ const declaresMembers = Object.keys(model.methods ?? {}).length > 0 || Object.keys(model.events ?? {}).length > 0;
95
+ if (adapter === undefined && declaresMembers)
96
+ throw new Error(`model entry '${model.entry}': the manifest declares model methods or events, so the entry needs an implementation module (expected ${sourceCandidates(model.entry).join(' or ')} in ${sourceRoot})`);
97
+ const virtual = adapter === undefined
98
+ ? `export const model = ${ir};\nexport function create() {\n return { methods: {}, sync() {}, dispose() {} };\n}\n`
99
+ : `export const model = ${ir};\nexport { create } from ${JSON.stringify(normalizePath(adapter))};\n`;
100
+ await emitModule({
101
+ artifact: model.entry,
102
+ label: `model entry '${model.entry}'`,
103
+ requiredNamed: ['model', 'create'],
104
+ virtual,
105
+ });
106
+ }
107
+ }
108
+ if (manifest.view2d?.entry !== undefined)
109
+ await emitModule({
110
+ artifact: manifest.view2d.entry,
111
+ label: `view2d entry '${manifest.view2d.entry}'`,
112
+ requiredNamed: [],
113
+ defaultExport: true,
114
+ });
115
+ const view3d = manifest.entries?.view3d;
116
+ if (view3d !== undefined)
117
+ await emitModule({
118
+ artifact: view3d,
119
+ label: `view3d entry '${view3d}'`,
120
+ requiredNamed: [],
121
+ });
122
+ if (device.geometryFile !== undefined)
123
+ await claimSource(device.geometryFile, 'view2d.geometry');
124
+ if (device.geometry?.bodyImage !== undefined)
125
+ await claimSource(device.geometry.bodyImage, 'view2d.geometry.bodyImage');
126
+ if (manifest.icon !== undefined)
127
+ await claimSource(manifest.icon, 'icon');
128
+ for (const [name, property] of Object.entries(manifest.properties ?? {})) {
129
+ const reference = property.default;
130
+ if (reference === null || typeof reference !== 'object')
131
+ continue;
132
+ if (reference.mode !== 'package' || typeof reference.src !== 'string')
133
+ continue;
134
+ if (property.type === 'program' && property.loader === 'filesystem') {
135
+ const files = await readProgramDirectory(sourceRoot, reference.src);
136
+ if (files.length === 0)
137
+ throw new Error(`Program default directory '${reference.src}' has no files to publish.`);
138
+ for (const file of files) {
139
+ const path = `${reference.src}/${file.path}`;
140
+ claim(path, resolve(sourceRoot, ...path.split('/')), file.data);
141
+ }
142
+ continue;
143
+ }
144
+ await claimSource(reference.src, `properties.${name}.default`);
145
+ }
146
+ for (const path of await listAssets(resolve(sourceRoot, 'assets')))
147
+ await claimSource(`assets/${path}`, 'assets');
148
+ for (const [id, view] of Object.entries(manifest.view ?? {})) {
149
+ await emitHtml(view.entry, `view '${id}'`);
150
+ }
151
+ async function emitHtml(entry, label) {
152
+ const source = await findSource(sourceRoot, entry, label);
153
+ const data = new Uint8Array(await readFile(source));
154
+ claim(entry, source, data);
155
+ for (const reference of htmlReferences(Buffer.from(data).toString('utf8')))
156
+ await emitReference(packageDirectory(entry), reference, label);
157
+ }
158
+ return [...claims.entries()]
159
+ .map(([path, value]) => ({ path, data: value.data }))
160
+ .sort((left, right) => compare(left.path, right.path));
161
+ }
162
+ /** Builds the release file list with real byte sizes and SHA-256 digests. */
163
+ export function createRelease(manifest, files) {
164
+ const entries = [...files].sort((left, right) => compare(left.path, right.path));
165
+ const records = {};
166
+ for (const file of entries)
167
+ records[file.path] = {
168
+ size: file.data.byteLength,
169
+ integrity: `sha256:${createHash('sha256').update(file.data).digest('hex')}`,
170
+ };
171
+ return {
172
+ id: `${manifest.publisher}:${manifest.name}`,
173
+ version: manifest.version,
174
+ files: records,
175
+ };
176
+ }
177
+ export function renderRelease(release) {
178
+ return `${JSON.stringify(release, null, 2)}\n`;
179
+ }
180
+ /**
181
+ * Validates an output directory that is going to be deleted and recreated.
182
+ *
183
+ * The directory may not be a filesystem root, the home directory or one of its ancestors, and it
184
+ * may not contain any protected path such as the project root, the source directory or the
185
+ * manifest. Returns the resolved directory.
186
+ *
187
+ * @throws When resetting the directory could remove sources, tooling state or user data.
188
+ */
189
+ export function assertSafeOutput(outDir, protect = []) {
190
+ const target = resolve(outDir);
191
+ if (target === parse(target).root)
192
+ throw new Error(`Refusing to use the filesystem root as outDir: ${target}`);
193
+ const home = resolve(homedir());
194
+ if (isContained(target, home))
195
+ throw new Error(`Refusing to use ${target} as outDir: it contains the home directory`);
196
+ for (const path of protect) {
197
+ const guarded = resolve(path);
198
+ if (guarded === target)
199
+ throw new Error(`Refusing to use ${target} as outDir: it is a protected path`);
200
+ if (isContained(target, guarded))
201
+ throw new Error(`Refusing to use ${target} as outDir: it contains ${guarded}`);
202
+ }
203
+ return target;
204
+ }
205
+ /**
206
+ * Replaces the output directory with the package files and writes `release.json` beside them.
207
+ *
208
+ * The release file itself is not part of `files`, so it never describes itself. The directory is
209
+ * validated by {@link assertSafeOutput} before anything is removed.
210
+ */
211
+ export async function writeDevicePackage(options) {
212
+ const outDir = assertSafeOutput(options.outDir, options.protect ?? []);
213
+ const { files, release } = options;
214
+ await rm(outDir, { recursive: true, force: true });
215
+ for (const file of files) {
216
+ const target = resolve(outDir, ...file.path.split('/'));
217
+ if (!isContained(outDir, target) || target === resolve(outDir))
218
+ throw new Error(`Package file '${file.path}' resolves outside ${outDir}`);
219
+ await mkdir(dirname(target), { recursive: true });
220
+ await writeFile(target, file.data);
221
+ }
222
+ await writeFile(resolve(outDir, 'release.json'), renderRelease(release), 'utf8');
223
+ }
224
+ const VIRTUAL_ENTRY = 'mica-unified-entry';
225
+ /** Bundles one entry into a single self-contained ESM module. */
226
+ async function bundleModule(request) {
227
+ const entry = request.virtual === undefined ? request.input : VIRTUAL_ENTRY;
228
+ const bundled = await build({
229
+ configFile: false,
230
+ root: request.root,
231
+ publicDir: false,
232
+ logLevel: 'silent',
233
+ resolve: {
234
+ ...(request.aliases === undefined ? {} : { alias: request.aliases }),
235
+ conditions: ['source', 'module', 'browser', 'production'],
236
+ },
237
+ plugins: [
238
+ {
239
+ name: 'mica:unified-entry',
240
+ enforce: 'pre',
241
+ resolveId(id) {
242
+ if (isBuiltin(id))
243
+ throw new Error(`${request.label}: Node built-ins are unavailable in a device module: ${id}`);
244
+ if (id === VIRTUAL_ENTRY)
245
+ return '\0' + VIRTUAL_ENTRY;
246
+ },
247
+ load(id) {
248
+ if (id === '\0' + VIRTUAL_ENTRY)
249
+ return request.virtual;
250
+ },
251
+ },
252
+ ],
253
+ build: {
254
+ write: false,
255
+ target: 'es2022',
256
+ sourcemap: false,
257
+ minify: request.minify,
258
+ lib: { entry, formats: ['es'], fileName: () => 'module.js' },
259
+ rolldownOptions: {
260
+ input: entry,
261
+ output: { codeSplitting: false },
262
+ onwarn(warning, warn) {
263
+ if (warning.code === 'UNRESOLVED_IMPORT')
264
+ throw new Error(`${request.label}: ${warning.message}`);
265
+ warn(warning);
266
+ },
267
+ },
268
+ },
269
+ });
270
+ if ('close' in bundled)
271
+ throw new Error(`${request.label}: watch builds are not supported inside a package build`);
272
+ const outputs = (Array.isArray(bundled) ? bundled : [bundled]).flatMap((result) => result.output);
273
+ const chunk = outputs[0];
274
+ if (outputs.length !== 1 || chunk?.type !== 'chunk')
275
+ throw new Error(`${request.label}: the entry must produce exactly one JavaScript module (${outputs.map((item) => item.fileName).join(', ') || 'no output'})`);
276
+ if (chunk.imports.length > 0 || chunk.dynamicImports.some((name) => name !== chunk.fileName))
277
+ throw new Error(`${request.label}: the module must be self-contained (imports: ${[...chunk.imports, ...chunk.dynamicImports].join(', ')})`);
278
+ assertSelfContained(chunk.code, request.label);
279
+ return { code: chunk.code, exports: chunk.exports };
280
+ }
281
+ async function findOptionalSource(sourceRoot, artifact) {
282
+ for (const candidate of sourcePaths(sourceRoot, artifact))
283
+ if (await isFile(candidate))
284
+ return candidate;
285
+ return undefined;
286
+ }
287
+ /** Resolves an HTML or CSS reference into a package path, or `undefined` for external URLs. */
288
+ function resolveReference(from, raw, label) {
289
+ const value = raw.trim();
290
+ if (value.length === 0 || value.startsWith('#') || value.startsWith('//'))
291
+ return undefined;
292
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(value))
293
+ return undefined;
294
+ if (value.startsWith('/'))
295
+ throw new Error(`${label}: '${raw}' must be a relative reference inside the package`);
296
+ const path = value.split(/[?#]/).shift() ?? '';
297
+ const segments = from.length === 0 ? [] : from.split('/');
298
+ for (const segment of path.split('/')) {
299
+ if (segment === '' || segment === '.')
300
+ continue;
301
+ if (segment === '..') {
302
+ if (segments.length === 0)
303
+ throw new Error(`${label}: '${raw}' resolves outside the package root`);
304
+ segments.pop();
305
+ continue;
306
+ }
307
+ segments.push(segment);
308
+ }
309
+ if (segments.length === 0)
310
+ throw new Error(`${label}: '${raw}' does not name a package file`);
311
+ return packagePath(segments.join('/'), label);
312
+ }
313
+ function htmlReferences(text) {
314
+ return [...text.matchAll(HTML_REFERENCE)].map((match) => match[1] ?? match[2] ?? match[3] ?? '');
315
+ }
316
+ function cssReferences(text) {
317
+ const references = [...text.matchAll(CSS_URL)].map((match) => match[1] ?? match[2] ?? match[3] ?? '');
318
+ for (const match of text.matchAll(CSS_IMPORT))
319
+ references.push(match[1] ?? match[2] ?? '');
320
+ return references;
321
+ }
322
+ function packageDirectory(path) {
323
+ const index = path.lastIndexOf('/');
324
+ return index === -1 ? '' : path.slice(0, index);
325
+ }
326
+ /** Lists every regular file below `directory` as a POSIX path relative to it. */
327
+ async function listAssets(directory) {
328
+ const found = [];
329
+ const visit = async (current, prefix) => {
330
+ let entries;
331
+ try {
332
+ entries = await readdir(current, { withFileTypes: true });
333
+ }
334
+ catch (error) {
335
+ if (error.code === 'ENOENT')
336
+ return;
337
+ throw error;
338
+ }
339
+ for (const entry of entries.sort((left, right) => compare(left.name, right.name))) {
340
+ const path = prefix.length === 0 ? entry.name : `${prefix}/${entry.name}`;
341
+ if (entry.isDirectory())
342
+ await visit(resolve(current, entry.name), path);
343
+ else if (entry.isFile())
344
+ found.push(path);
345
+ else
346
+ throw new Error(`assets/${path}: only regular files are published`);
347
+ }
348
+ };
349
+ await visit(directory, '');
350
+ return found;
351
+ }
352
+ function compare(left, right) {
353
+ return left < right ? -1 : left > right ? 1 : 0;
354
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * True when `child` is `parent` itself or lies below it, using path-segment comparison so that
3
+ * sibling directories with a shared prefix are rejected.
4
+ */
5
+ export declare function isContained(parent: string, child: string): boolean;
6
+ /**
7
+ * Validates a package-root-relative POSIX path and returns it unchanged.
8
+ *
9
+ * Package paths are the artifact paths declared by the manifest: no backslashes, no drive or URL
10
+ * prefix, no empty, `.` or `..` segment, and no leading or trailing slash.
11
+ */
12
+ export declare function packagePath(path: string, field: string): string;
13
+ /**
14
+ * Authoring sources tried for an artifact path, in order.
15
+ *
16
+ * The declared artifact path wins when the source already uses it; otherwise a `.js` (or
17
+ * `.mjs` / `.jsx`) artifact also accepts the matching TypeScript source.
18
+ */
19
+ export declare function sourceCandidates(path: string): readonly string[];
20
+ /** Absolute candidate paths of an artifact path inside the source directory. */
21
+ export declare function sourcePaths(sourceRoot: string, path: string): readonly string[];
22
+ /** Resolves a package path below the source directory without leaving it. */
23
+ export declare function resolveSource(sourceRoot: string, path: string): string;
24
+ export declare function isFile(path: string): Promise<boolean>;
25
+ /**
26
+ * Resolves the authoring source of an artifact path.
27
+ *
28
+ * @throws When no candidate exists; the message lists the tried paths and the declaring field.
29
+ */
30
+ export declare function findSource(sourceRoot: string, path: string, field: string): Promise<string>;
@@ -0,0 +1,94 @@
1
+ import { stat } from 'node:fs/promises';
2
+ import { isAbsolute, relative, resolve } from 'node:path';
3
+ /**
4
+ * True when `child` is `parent` itself or lies below it, using path-segment comparison so that
5
+ * sibling directories with a shared prefix are rejected.
6
+ */
7
+ export function isContained(parent, child) {
8
+ const path = relative(resolve(parent), resolve(child));
9
+ return (path === '' ||
10
+ (!isAbsolute(path) && path !== '..' && !path.startsWith('..\\') && !path.startsWith('../')));
11
+ }
12
+ /**
13
+ * Validates a package-root-relative POSIX path and returns it unchanged.
14
+ *
15
+ * Package paths are the artifact paths declared by the manifest: no backslashes, no drive or URL
16
+ * prefix, no empty, `.` or `..` segment, and no leading or trailing slash.
17
+ */
18
+ export function packagePath(path, field) {
19
+ const invalid = (reason) => {
20
+ throw new Error(`Invalid ${field} path '${path}': ${reason}`);
21
+ };
22
+ if (path.length === 0)
23
+ invalid('the path is empty');
24
+ if (path.includes('\\'))
25
+ invalid('package paths use forward slashes');
26
+ if (path.startsWith('/'))
27
+ invalid('the path is absolute');
28
+ if (path.endsWith('/'))
29
+ invalid('the path names a directory');
30
+ if (/:/.test(path))
31
+ invalid('the path contains a drive or URL separator');
32
+ for (const segment of path.split('/')) {
33
+ if (segment.length === 0)
34
+ invalid('the path contains an empty segment');
35
+ if (segment === '.' || segment === '..')
36
+ invalid(`the path contains a '${segment}' segment`);
37
+ }
38
+ return path;
39
+ }
40
+ /**
41
+ * Authoring sources tried for an artifact path, in order.
42
+ *
43
+ * The declared artifact path wins when the source already uses it; otherwise a `.js` (or
44
+ * `.mjs` / `.jsx`) artifact also accepts the matching TypeScript source.
45
+ */
46
+ export function sourceCandidates(path) {
47
+ const candidates = [path];
48
+ if (path.endsWith('.js')) {
49
+ const stem = path.slice(0, -'.js'.length);
50
+ candidates.push(`${stem}.ts`, `${stem}.tsx`, `${stem}.mts`);
51
+ }
52
+ else if (path.endsWith('.mjs')) {
53
+ candidates.push(`${path.slice(0, -'.mjs'.length)}.mts`);
54
+ }
55
+ else if (path.endsWith('.jsx')) {
56
+ candidates.push(`${path.slice(0, -'.jsx'.length)}.tsx`);
57
+ }
58
+ return candidates;
59
+ }
60
+ /** Absolute candidate paths of an artifact path inside the source directory. */
61
+ export function sourcePaths(sourceRoot, path) {
62
+ return sourceCandidates(path).map((candidate) => resolveSource(sourceRoot, candidate));
63
+ }
64
+ /** Resolves a package path below the source directory without leaving it. */
65
+ export function resolveSource(sourceRoot, path) {
66
+ const file = resolve(sourceRoot, ...path.split('/'));
67
+ if (!isContained(sourceRoot, file))
68
+ throw new Error(`Source path '${path}' escapes ${sourceRoot}`);
69
+ return file;
70
+ }
71
+ export async function isFile(path) {
72
+ try {
73
+ return (await stat(path)).isFile();
74
+ }
75
+ catch (error) {
76
+ const code = error.code;
77
+ if (code === 'ENOENT' || code === 'ENOTDIR')
78
+ return false;
79
+ throw error;
80
+ }
81
+ }
82
+ /**
83
+ * Resolves the authoring source of an artifact path.
84
+ *
85
+ * @throws When no candidate exists; the message lists the tried paths and the declaring field.
86
+ */
87
+ export async function findSource(sourceRoot, path, field) {
88
+ const candidates = sourcePaths(sourceRoot, path);
89
+ for (const candidate of candidates)
90
+ if (await isFile(candidate))
91
+ return candidate;
92
+ const tried = candidates.map((candidate) => relative(sourceRoot, candidate)).join(', ');
93
+ throw new Error(`Cannot find the source of ${field} '${path}': expected one of ${tried} inside ${sourceRoot}`);
94
+ }
@@ -0,0 +1,58 @@
1
+ import type { PrepareWatcher } from './prepare.js';
2
+ import { type LoadedDevicePackage } from './unified-manifest.js';
3
+ /** Directory below the project root that holds the generated type environment. */
4
+ export declare const DEVICE_TYPE_DIRECTORY = ".mica";
5
+ /** Generated global declaration file of a unified device project. */
6
+ export declare const DEVICE_DECLARATION_FILE = "device.d.ts";
7
+ /** Generated TypeScript configuration that device projects extend. */
8
+ export declare const DEVICE_TSCONFIG_FILE = "tsconfig.json";
9
+ export interface PrepareDeviceOptions {
10
+ /** Project root holding `mica.config.ts`; defaults to the current directory. */
11
+ readonly root: string;
12
+ /** Source directory whose contents form the package root. */
13
+ readonly sourceDir: string;
14
+ /** Manifest path relative to the project root. */
15
+ readonly manifest: string;
16
+ /** DDL model source path relative to the project root. */
17
+ readonly model?: string;
18
+ /** Project config file, watched when prepare runs in watch mode. */
19
+ readonly configFile?: string;
20
+ }
21
+ export interface PreparedDevice {
22
+ /** Absolute paths of the written type environment files. */
23
+ readonly files: readonly string[];
24
+ readonly device: LoadedDevicePackage;
25
+ }
26
+ export interface WatchDeviceOptions {
27
+ /** Resolves the current preparation inputs; called again after every change. */
28
+ readonly load: () => Promise<PrepareDeviceOptions>;
29
+ /** Coalescing window between a file event and the regeneration; defaults to 50 ms. */
30
+ readonly debounceMs?: number;
31
+ readonly onPrepare?: (files: readonly string[]) => void;
32
+ /** Receives watch failures; defaults to `console.error`. */
33
+ readonly onError?: (error: unknown) => void;
34
+ }
35
+ /**
36
+ * Validates the device manifest and DDL and writes `.mica/device.d.ts` and `.mica/tsconfig.json`.
37
+ *
38
+ * Preparation never executes an author module: it reads JSON, compiles DDL and renders types. A
39
+ * file whose content is unchanged keeps its previous bytes and timestamp, so a watching compiler
40
+ * is not disturbed by repeated runs. A failing run reports the original manifest or DDL error and
41
+ * leaves the previous type environment in place; the build is still prevented from running.
42
+ */
43
+ export declare function prepareDevice(options: PrepareDeviceOptions): Promise<PreparedDevice>;
44
+ /**
45
+ * Regenerates the type environment whenever the manifest, the DDL model or the project config
46
+ * changes. Inputs are re-resolved on every run, so editing the config or renaming a declared file
47
+ * retargets the watchers. Generated writes never feed back into the loop.
48
+ */
49
+ export declare function watchDevice(options: WatchDeviceOptions): PrepareWatcher;
50
+ export interface WatchPreparationOptions<T> {
51
+ readonly load: () => Promise<T>;
52
+ readonly inputs: (loaded: T) => readonly string[];
53
+ readonly prepare: (loaded: T) => Promise<readonly string[]>;
54
+ readonly debounceMs?: number;
55
+ readonly onPrepare?: (files: readonly string[]) => void;
56
+ readonly onError?: (error: unknown) => void;
57
+ }
58
+ export declare function watchPreparation<T>(options: WatchPreparationOptions<T>): PrepareWatcher;