animader-cli 0.1.0 → 0.2.1

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.
@@ -15,7 +15,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
15
15
 
16
16
  import { packScore as realPackScore, reflectionOfPayload } from './export-node.mjs';
17
17
  import { listSnapshotInputFiles, snapshotProject } from './snapshot.mjs';
18
- import { createNodeIo, hashBytes } from './node-fs.mjs';
18
+ import { createNodeIo, hashBytes, removeTree } from './node-fs.mjs';
19
19
  import { buildError } from '../lib/errors.mjs';
20
20
  import { buildProject, assertProjectSnapshotsMatch } from '../lib/pipeline.mjs';
21
21
  import { BAKED_PAYLOAD, BUILD_RECEIPT, GENERATED_DIR, PACKED_SCORE, inspectProject } from '../lib/contract.mjs';
@@ -185,7 +185,9 @@ export async function runFullBuild({
185
185
  await fsp.writeFile(paths.receipt, `${JSON.stringify(built.receipt, null, 2)}\n`);
186
186
  return built;
187
187
  } finally {
188
- await fsp.rm(work, { recursive: true, force: true });
188
+ // The disposal guard (lib/rmtree.mjs): a completed build must not fail
189
+ // on a transient ENOTEMPTY while the work tree settles.
190
+ await removeTree(work);
189
191
  }
190
192
  }
191
193
 
@@ -255,7 +257,9 @@ export async function runSnapshotBuild({
255
257
  });
256
258
  return { built, work, workProject };
257
259
  } catch (cause) {
258
- await fsp.rm(work, { recursive: true, force: true });
260
+ // The disposal guard (lib/rmtree.mjs) on the failure path too: a failed
261
+ // build's work tree must go, transient removal codes included.
262
+ await removeTree(work);
259
263
  throw cause;
260
264
  }
261
265
  }
@@ -15,7 +15,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
15
15
  import { promisify } from 'node:util';
16
16
  import { brotliCompressSync, constants as zlibConstants, gzipSync } from 'node:zlib';
17
17
 
18
- import { createNodeIo, hashBytes, hashFile } from './node-fs.mjs';
18
+ import { createNodeIo, hashBytes, hashFile, removeTree } from './node-fs.mjs';
19
19
  import { createPngineNative } from './pngine.mjs';
20
20
  import { listSnapshotInputFiles, snapshotProject } from './snapshot.mjs';
21
21
  import { assertProjectSnapshotsMatch, buildProject } from '../lib/pipeline.mjs';
@@ -596,6 +596,8 @@ export async function prepareRelease({
596
596
  },
597
597
  };
598
598
  } finally {
599
- await fsp.rm(work, { recursive: true, force: true });
599
+ // The disposal guard (lib/rmtree.mjs): a completed export must not fail
600
+ // on a transient ENOTEMPTY while the work tree settles.
601
+ await removeTree(work);
600
602
  }
601
603
  }
@@ -22,39 +22,11 @@ import { join } from 'node:path';
22
22
 
23
23
  import { isSoundtrackName, PLAYER_CONFIG_FORMATS, soundtrackNamesText } from '../lib/soundtrack.mjs';
24
24
  import { serverError } from '../lib/errors.mjs';
25
+ import { removeTree } from './node-fs.mjs';
25
26
 
26
27
  /** How long a retired generation with no in-flight responses is kept. */
27
28
  export const DEFAULT_GENERATION_GRACE_MS = 30_000;
28
29
 
29
- /**
30
- * The transient codes a recursive removal can answer when the directory is
31
- * observed while it changes underneath (an entry landing between the walk
32
- * and the rmdir, a tree swapped mid-walk). The fix for those is upstream —
33
- * the session quiesces its writers before disposing, and every tree has one
34
- * owner — so this retry is only the last guard, never the mechanism.
35
- */
36
- const REMOVAL_RETRY_CODES = new Set(['ENOTEMPTY', 'EBUSY', 'ENOTDIR']);
37
- /** A few short attempts: enough to clear a transient observer, never a leak. */
38
- const REMOVAL_ATTEMPTS = 4;
39
- const REMOVAL_BACKOFF_MS = 25;
40
-
41
- async function removeTree(path) {
42
- let lastError = null;
43
- for (let attempt = 1; attempt <= REMOVAL_ATTEMPTS; attempt += 1) {
44
- try {
45
- await fsp.rm(path, { recursive: true, force: true });
46
- return;
47
- } catch (cause) {
48
- if (!REMOVAL_RETRY_CODES.has(cause?.code)) throw cause;
49
- lastError = cause;
50
- if (attempt < REMOVAL_ATTEMPTS) {
51
- await new Promise((resolve) => setTimeout(resolve, REMOVAL_BACKOFF_MS * attempt));
52
- }
53
- }
54
- }
55
- throw lastError;
56
- }
57
-
58
30
  /**
59
31
  * @param {Object} options
60
32
  * @param {string} options.root the session-owned root directory (outside
@@ -6,6 +6,8 @@ import { createHash } from 'node:crypto';
6
6
  import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
7
7
  import { dirname } from 'node:path';
8
8
 
9
+ import { removeTree as retryingRemoveTree } from '../lib/rmtree.mjs';
10
+
9
11
  export function hashBytes(bytes) {
10
12
  return createHash('sha256').update(bytes).digest('hex');
11
13
  }
@@ -40,6 +42,16 @@ export async function removeFile(path) {
40
42
  await rm(path, { force: true });
41
43
  }
42
44
 
45
+ /**
46
+ * The one recursive tree removal for work-tree disposal: `fsp.rm` under the
47
+ * shared transient-code retry (lib/rmtree.mjs). Every owner of a throwaway
48
+ * tree — the dev generation store, the full build's snapshot work tree, the
49
+ * export's work tree — disposes through this, never a bare rm.
50
+ */
51
+ export async function removeTree(path) {
52
+ await retryingRemoveTree(path, { remove: (target) => rm(target, { recursive: true, force: true }) });
53
+ }
54
+
43
55
  export async function writeFileAtomic(path, data) {
44
56
  await mkdir(dirname(path), { recursive: true });
45
57
  const temporary = `${path}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
@@ -4,11 +4,12 @@
4
4
  // the one policy: generated `out/`, the caller's own output/staging trees
5
5
  // and detached reports when they sit inside the project, `.git`,
6
6
  // `node_modules` and legacy `.animader-export-work-*` debris never enter a
7
- // snapshot; `.gitignore` is data for humans and git, never an asset
8
- // allowlist. `listSnapshotInputFiles` hashes the filtered snapshot into the
9
- // receipt's consumed-input rows — the conservative coverage the build
10
- // receipt records when the compiler answers no dependency metadata of its
11
- // own.
7
+ // snapshot, and every excluded root is excluded as a whole subtree — no
8
+ // file under it enters the copy or the receipt's rows either; `.gitignore`
9
+ // is data for humans and git, never an asset allowlist.
10
+ // `listSnapshotInputFiles` hashes the filtered snapshot into the receipt's
11
+ // consumed-input rows — the conservative coverage the build receipt records
12
+ // when the compiler answers no dependency metadata of its own.
12
13
 
13
14
  import { promises as fsp } from 'node:fs';
14
15
  import { tmpdir } from 'node:os';
@@ -28,10 +29,13 @@ export const LEGACY_WORK_PREFIX = '.animader-export-work-';
28
29
 
29
30
  /**
30
31
  * Root-relative paths of the caller's own output, staging and size-report
31
- * locations, but only those that sit inside the project folder. These are
32
- * owned generated trees and reports, not authored resources, so they never
33
- * enter the input snapshot. The exclusion is this fixed list — the
34
- * `.gitignore` file is data for humans and git, never an asset allowlist.
32
+ * locations, but only those that sit inside the project folder. The
33
+ * project's own generated directory is always among them — the project
34
+ * root is known at copy time and `GENERATED_DIR` is a contract constant —
35
+ * whether or not the caller named any paths at all. These are owned
36
+ * generated trees and reports, not authored resources, so they never enter
37
+ * an input snapshot. The exclusion is this fixed list — the `.gitignore`
38
+ * file is data for humans and git, never an asset allowlist.
35
39
  */
36
40
  function snapshotExclusions({ projectRoot, paths }) {
37
41
  const insideProject = (path) => {
@@ -56,7 +60,15 @@ export function snapshotFilter({ projectRoot, paths }) {
56
60
  const segments = rel.split(sep);
57
61
  if (segments.some((name) => SNAPSHOT_PRUNED_NAMES.includes(name))) return false;
58
62
  if (segments.some((name) => name.startsWith(LEGACY_WORK_PREFIX))) return false;
59
- return !excluded.has(segments.join('/'));
63
+ // Any excluded root-relative path is a subtree: a file or a deeper
64
+ // directory under it is excluded with it, in the copy filter and in the
65
+ // receipt's hashing walk alike — the same shape the watcher's filter
66
+ // keeps. An exact-path match alone would let a row under `out/` through
67
+ // whenever the walk meets a tree that still carries one.
68
+ for (let depth = 1; depth <= segments.length; depth += 1) {
69
+ if (excluded.has(segments.slice(0, depth).join('/'))) return false;
70
+ }
71
+ return true;
60
72
  };
61
73
  }
62
74
 
@@ -65,11 +77,13 @@ export function snapshotFilter({ projectRoot, paths }) {
65
77
  * the source tree, so an in-project output (`animader export --out dist`
66
78
  * from the project root) never asks Node to copy a directory into its own
67
79
  * subtree (ERR_FS_CP_EINVAL). The copy keeps every authored file at its
68
- * relative path and excludes only the caller's own trees and reports plus
69
- * VCS/dependency directories: generated `out/`, the output, its
70
- * `<out>.next` staging directory and detached `<out>.size.json` when they
71
- * sit inside the project, `.git`, `node_modules`, and legacy
72
- * `.animader-export-work-*` debris. `.gitignore` is not consulted.
80
+ * relative path and excludes only the generated and caller-owned trees and
81
+ * reports plus VCS/dependency directories — each as a whole subtree: the
82
+ * project's own generated `out/` (a contract constant, named by the caller
83
+ * or not), the output, its `<out>.next` staging directory and detached
84
+ * `<out>.size.json` when they sit inside the project, `.git`,
85
+ * `node_modules`, and legacy `.animader-export-work-*` debris. `.gitignore`
86
+ * is not consulted.
73
87
  *
74
88
  * @param {Object} options
75
89
  * @param {{folder: string}} options.project the inspected source project
@@ -0,0 +1,422 @@
1
+ // Editor schema associations and packaged resource staging.
2
+ //
3
+ // The exported snapshot's own `metadata.json` is the only manifest inventory:
4
+ // this module renders `sjon-lsp.sjon` from that metadata and stages the
5
+ // snapshot's exact bytes. It is portable — reads arrive through the injected
6
+ // `io` functions, no process is started and no network is touched. The
7
+ // explicit `prepare-editor-resources.mjs` script owns the one Zig build
8
+ // invocation.
9
+
10
+ import { PROJECT_FILES } from './contract.mjs';
11
+ import { projectError } from './errors.mjs';
12
+
13
+ export const EDITOR_RESOURCE_ROOT = new URL('../resources/editor/', import.meta.url);
14
+ export const EDITOR_CONFIG_PATH = 'sjon-lsp.sjon';
15
+ export const EDITOR_SCHEMA_DIR = '.animader/schemas';
16
+ export const EDITOR_CONFIG_VERSION = 1;
17
+
18
+ const SNAPSHOT_FORMAT = 'animader-schema-snapshot/1';
19
+ const SNAPSHOT_FILE = 'metadata.json';
20
+ const SOURCE_OWNERS = new Set(['animader', 'tempura', 'pngine']);
21
+ const DIRECTORY_PATTERNS = Object.freeze([
22
+ 'examples/cli',
23
+ 'npm/cli/starters',
24
+ 'demo/starters',
25
+ 'demo/pieces',
26
+ ]);
27
+ const VERIFIED_PROGRAM_FILES = Object.freeze([
28
+ 'examples/hello',
29
+ 'demo/fixture',
30
+ ]);
31
+
32
+ const PREPARE_REMEDY = 'Regenerate the packaged editor resources on a host with Zig: '
33
+ + 'node npm/cli/scripts/prepare-editor-resources.mjs --profile starter --output npm/cli/resources/editor '
34
+ + '(the repository gate runs that command through obs). A plain npm test in npm/cli or demo requires this preparation first.';
35
+
36
+ function metadataError(message) {
37
+ return projectError(
38
+ 'editor_metadata_invalid',
39
+ `editor snapshot metadata is invalid: ${message}`,
40
+ PREPARE_REMEDY,
41
+ );
42
+ }
43
+
44
+ function configError(message) {
45
+ return projectError(
46
+ 'editor_config_mismatch',
47
+ `editor configuration does not match the exported snapshot: ${message}`,
48
+ PREPARE_REMEDY,
49
+ );
50
+ }
51
+
52
+ function resourceError(code, message) {
53
+ return projectError(code, message, PREPARE_REMEDY);
54
+ }
55
+
56
+ /**
57
+ * Normalize one relative resource path lexically. Absolute paths, drive
58
+ * paths, backslashes, NULs, traversal and glob syntax are refused before
59
+ * any URL is joined or any file is read.
60
+ */
61
+ function normalizeResourcePath(value, label) {
62
+ if (typeof value !== 'string' || value === '') {
63
+ throw metadataError(`${label} is not a nonempty string`);
64
+ }
65
+ if (value.includes('\0')) throw metadataError(`${label} contains a NUL byte`);
66
+ if (value.includes('\\')) throw metadataError(`${label} contains a backslash: ${JSON.stringify(value)}`);
67
+ if (value.startsWith('/') || /^[A-Za-z]:/.test(value) || value.startsWith('//')) {
68
+ throw metadataError(`${label} is absolute: ${JSON.stringify(value)}`);
69
+ }
70
+ if (/[*?{}[\]:]/.test(value)) {
71
+ throw metadataError(`${label} contains glob or URL syntax: ${JSON.stringify(value)}`);
72
+ }
73
+ const segments = [];
74
+ for (const segment of value.split('/')) {
75
+ if (segment === '' || segment === '.') continue;
76
+ if (segment === '..') throw metadataError(`${label} traverses a parent: ${JSON.stringify(value)}`);
77
+ segments.push(segment);
78
+ }
79
+ if (segments.length === 0) throw metadataError(`${label} is empty after normalization`);
80
+ return segments.join('/');
81
+ }
82
+
83
+ function documentName(value, label) {
84
+ if (typeof value !== 'string' || value === '') {
85
+ throw projectError('editor_project_files_invalid', `editor ${label} document name is empty`);
86
+ }
87
+ if (value.includes('/') || value.includes('\\') || value.includes('\0') || value === '.' || value === '..') {
88
+ throw projectError(
89
+ 'editor_project_files_invalid',
90
+ `editor ${label} document name must be a plain root file name: ${JSON.stringify(value)}`,
91
+ );
92
+ }
93
+ return value;
94
+ }
95
+
96
+ /**
97
+ * Validate and normalize the exported `metadata.json`. The contract is fixed:
98
+ * ten sources, a nine-member timeline and a one-member program bundle, with
99
+ * every source belonging to exactly one bundle. The source *order* and
100
+ * manifest *order* are preserved as exported; nothing here re-sorts them.
101
+ */
102
+ function validateMetadata(metadata) {
103
+ if (metadata === null || typeof metadata !== 'object' || Array.isArray(metadata)) {
104
+ throw metadataError('the document is not an object');
105
+ }
106
+ if (metadata.format !== SNAPSHOT_FORMAT) {
107
+ throw metadataError(`format must be ${JSON.stringify(SNAPSHOT_FORMAT)}`);
108
+ }
109
+ if (!Array.isArray(metadata.sources) || metadata.sources.length === 0) {
110
+ throw metadataError('sources must be a nonempty array');
111
+ }
112
+
113
+ const sources = [];
114
+ const byFile = new Map();
115
+ for (const [index, source] of metadata.sources.entries()) {
116
+ if (source === null || typeof source !== 'object' || Array.isArray(source)) {
117
+ throw metadataError(`sources[${index}] is not an object`);
118
+ }
119
+ if (typeof source.name !== 'string' || !/^[a-z][a-z0-9_-]*$/.test(source.name)) {
120
+ throw metadataError(`sources[${index}].name is not a schema name`);
121
+ }
122
+ const file = normalizeResourcePath(source.file, `sources[${index}].file`);
123
+ if (!file.endsWith('.sjon')) {
124
+ throw metadataError(`sources[${index}].file must be a .sjon file: ${JSON.stringify(source.file)}`);
125
+ }
126
+ if (file !== `${source.name}.sjon`) {
127
+ throw metadataError(
128
+ `sources[${index}].file must be named after its source: ${JSON.stringify(source.file)}`,
129
+ );
130
+ }
131
+ if (file === SNAPSHOT_FILE) {
132
+ throw metadataError(`sources[${index}].file shadows the snapshot metadata file`);
133
+ }
134
+ if (byFile.has(file)) {
135
+ throw metadataError(`duplicate normalized source path ${JSON.stringify(file)}`);
136
+ }
137
+ if (!SOURCE_OWNERS.has(source.owner)) {
138
+ throw metadataError(`sources[${index}].owner is not animader, tempura or pngine`);
139
+ }
140
+ if (typeof source.optional !== 'boolean') {
141
+ throw metadataError(`sources[${index}].optional is not a boolean`);
142
+ }
143
+ if (!Number.isInteger(source.bytes) || source.bytes < 0) {
144
+ throw metadataError(`sources[${index}].bytes is not a nonnegative integer`);
145
+ }
146
+ if (typeof source.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(source.sha256)) {
147
+ throw metadataError(`sources[${index}].sha256 is not 64 lowercase hex characters`);
148
+ }
149
+ const normalized = {
150
+ name: source.name,
151
+ file,
152
+ owner: source.owner,
153
+ optional: source.optional,
154
+ bytes: source.bytes,
155
+ sha256: source.sha256,
156
+ };
157
+ sources.push(normalized);
158
+ byFile.set(file, normalized);
159
+ }
160
+
161
+ if (sources.length !== 10) {
162
+ throw metadataError(`exactly ten sources are required; found ${sources.length}`);
163
+ }
164
+ if (!Array.isArray(metadata.bundles) || metadata.bundles.length !== 2) {
165
+ throw metadataError('exactly the timeline and program bundles are required');
166
+ }
167
+
168
+ const bundles = new Map();
169
+ for (const [index, bundle] of metadata.bundles.entries()) {
170
+ if (bundle === null || typeof bundle !== 'object' || Array.isArray(bundle)) {
171
+ throw metadataError(`bundles[${index}] is not an object`);
172
+ }
173
+ if (bundle.name !== 'timeline' && bundle.name !== 'program') {
174
+ throw metadataError(`bundles[${index}] has an unexpected name`);
175
+ }
176
+ if (bundles.has(bundle.name)) throw metadataError(`duplicate bundle ${JSON.stringify(bundle.name)}`);
177
+ if (!Array.isArray(bundle.manifests) || bundle.manifests.length === 0) {
178
+ throw metadataError(`bundle ${bundle.name} has no manifests`);
179
+ }
180
+ const expectedLength = bundle.name === 'timeline' ? 9 : 1;
181
+ if (bundle.manifests.length !== expectedLength) {
182
+ throw metadataError(
183
+ `bundle ${bundle.name} must contain ${expectedLength} manifests; found ${bundle.manifests.length}`,
184
+ );
185
+ }
186
+ const manifests = [];
187
+ const seen = new Set();
188
+ for (const [manifestIndex, manifest] of bundle.manifests.entries()) {
189
+ const file = normalizeResourcePath(manifest, `bundle ${bundle.name} manifest ${manifestIndex}`);
190
+ if (seen.has(file)) {
191
+ throw metadataError(`bundle ${bundle.name} repeats normalized path ${JSON.stringify(file)}`);
192
+ }
193
+ if (!byFile.has(file)) {
194
+ throw metadataError(`bundle ${bundle.name} names an unknown source ${JSON.stringify(file)}`);
195
+ }
196
+ seen.add(file);
197
+ manifests.push(file);
198
+ }
199
+ bundles.set(bundle.name, { name: bundle.name, manifests });
200
+ }
201
+ if (!bundles.has('timeline') || !bundles.has('program')) {
202
+ throw metadataError('both the timeline and program bundles are required');
203
+ }
204
+
205
+ const timeline = bundles.get('timeline');
206
+ const program = bundles.get('program');
207
+ const members = new Set(timeline.manifests);
208
+ for (const manifest of program.manifests) {
209
+ if (members.has(manifest)) {
210
+ throw metadataError(`source ${JSON.stringify(manifest)} belongs to both bundles`);
211
+ }
212
+ }
213
+ for (const source of sources) {
214
+ if (!members.has(source.file) && !program.manifests.includes(source.file)) {
215
+ throw metadataError(`source ${JSON.stringify(source.file)} has no bundle membership`);
216
+ }
217
+ }
218
+
219
+ return { sources, timeline, program };
220
+ }
221
+
222
+ /** Render one string vector in the fixed generated layout. */
223
+ function vectorLines(keyword, values) {
224
+ const indent = ' '.repeat(9 + keyword.length);
225
+ const lines = [` :${keyword} [${JSON.stringify(values[0])}`];
226
+ for (const value of values.slice(1)) lines.push(`${indent}${JSON.stringify(value)}`);
227
+ lines[lines.length - 1] += ']';
228
+ return lines;
229
+ }
230
+
231
+ /**
232
+ * Render the exact `sjon-lsp.sjon` configuration. The starter profile uses
233
+ * only the two root document names; the contributor profile uses the eight
234
+ * pinned per-directory patterns plus the two individually verified program
235
+ * files. Neither profile ever emits a bare directory `**` pattern.
236
+ *
237
+ * @param {Object} options
238
+ * @param {Object} options.metadata parsed exported `metadata.json`
239
+ * @param {'starter'|'contributor'} [options.profile]
240
+ * @param {Object} [options.projectFiles]
241
+ * @returns {string}
242
+ */
243
+ export function renderEditorConfig({
244
+ metadata,
245
+ profile = 'starter',
246
+ projectFiles = PROJECT_FILES,
247
+ } = {}) {
248
+ if (profile !== 'starter' && profile !== 'contributor') {
249
+ throw projectError(
250
+ 'editor_profile_invalid',
251
+ `unknown editor profile ${JSON.stringify(profile)}; expected starter or contributor`,
252
+ );
253
+ }
254
+ if (projectFiles === null || typeof projectFiles !== 'object') {
255
+ throw projectError('editor_project_files_invalid', 'editor project files must be an object');
256
+ }
257
+ const programName = documentName(projectFiles.program, 'program');
258
+ const timelineName = documentName(projectFiles.timeline, 'timeline');
259
+ const snapshot = validateMetadata(metadata);
260
+
261
+ let programFiles;
262
+ let timelineFiles;
263
+ if (profile === 'starter') {
264
+ programFiles = [programName];
265
+ timelineFiles = [timelineName];
266
+ } else {
267
+ programFiles = [
268
+ ...DIRECTORY_PATTERNS.map((directory) => `${directory}/**/${programName}`),
269
+ ...VERIFIED_PROGRAM_FILES.map((directory) => `${directory}/${programName}`),
270
+ ];
271
+ timelineFiles = DIRECTORY_PATTERNS.map(
272
+ (directory) => `${directory}/**/${timelineName}`,
273
+ );
274
+ }
275
+
276
+ const bundles = [
277
+ {
278
+ name: 'program',
279
+ files: programFiles,
280
+ manifests: snapshot.program.manifests.map((file) => `${EDITOR_SCHEMA_DIR}/${file}`),
281
+ },
282
+ {
283
+ name: 'timeline',
284
+ files: timelineFiles,
285
+ manifests: snapshot.timeline.manifests.map((file) => `${EDITOR_SCHEMA_DIR}/${file}`),
286
+ },
287
+ ];
288
+
289
+ const lines = [`(sjon-lsp :version ${EDITOR_CONFIG_VERSION}`, ' :bundles ['];
290
+ for (const bundle of bundles) {
291
+ lines.push(` (bundle :name ${bundle.name}`);
292
+ lines.push(...vectorLines('files', bundle.files));
293
+ lines.push(...vectorLines('manifests', bundle.manifests));
294
+ lines[lines.length - 1] = `${lines[lines.length - 1]})`;
295
+ }
296
+ lines[lines.length - 1] = `${lines[lines.length - 1]}])`;
297
+ return `${lines.join('\n')}\n`;
298
+ }
299
+
300
+ /**
301
+ * Every file a packaged/generated editor resource set contains, relative to
302
+ * the resource root: the configuration, the ten exported schemas in source
303
+ * order, then the snapshot metadata.
304
+ *
305
+ * @param {Object} metadata parsed exported `metadata.json`
306
+ * @returns {string[]}
307
+ */
308
+ export function editorResourcePaths(metadata) {
309
+ const snapshot = validateMetadata(metadata);
310
+ return [
311
+ EDITOR_CONFIG_PATH,
312
+ ...snapshot.sources.map((source) => `${EDITOR_SCHEMA_DIR}/${source.file}`),
313
+ `${EDITOR_SCHEMA_DIR}/${SNAPSHOT_FILE}`,
314
+ ];
315
+ }
316
+
317
+ function asResourceRoot(resourceRoot) {
318
+ const url = resourceRoot instanceof URL
319
+ ? new URL(resourceRoot.href)
320
+ : new URL(String(resourceRoot), EDITOR_RESOURCE_ROOT);
321
+ if (!url.pathname.endsWith('/')) url.pathname += '/';
322
+ return url;
323
+ }
324
+
325
+ async function readResource(io, root, path) {
326
+ try {
327
+ const bytes = await io.readFile(new URL(path, root));
328
+ if (!bytes || typeof bytes.byteLength !== 'number') {
329
+ throw new TypeError('readFile returned no byte array');
330
+ }
331
+ return bytes;
332
+ } catch (error) {
333
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') {
334
+ throw resourceError('editor_resource_missing', `editor resource ${path} is missing`);
335
+ }
336
+ if (error?.code?.startsWith?.('editor_')) throw error;
337
+ throw resourceError(
338
+ 'editor_resource_unreadable',
339
+ `editor resource ${path} could not be read: ${error?.message ?? String(error)}`,
340
+ );
341
+ }
342
+ }
343
+
344
+ function decodeConfig(bytes, path) {
345
+ try {
346
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
347
+ } catch {
348
+ throw resourceError('editor_resource_corrupt', `editor resource ${path} is not valid UTF-8`);
349
+ }
350
+ }
351
+
352
+ /**
353
+ * Read and validate the config, snapshot metadata, every listed schema, its
354
+ * byte count and its SHA-256 before returning any staged resource. The
355
+ * returned order is `editorResourcePaths`' order. No process execution and
356
+ * no network access happen here.
357
+ *
358
+ * @param {Object} options
359
+ * @param {Object} options.io
360
+ * @param {URL|string} [options.resourceRoot]
361
+ * @param {Object} [options.projectFiles]
362
+ * @returns {Promise<Array<{path: string, bytes: Uint8Array, sha256: string}>>}
363
+ */
364
+ export async function stageEditorResources({
365
+ io,
366
+ resourceRoot = EDITOR_RESOURCE_ROOT,
367
+ projectFiles = PROJECT_FILES,
368
+ } = {}) {
369
+ if (!io || typeof io.readFile !== 'function' || typeof io.hashBytes !== 'function') {
370
+ throw new TypeError('stageEditorResources needs io.readFile and io.hashBytes');
371
+ }
372
+ const root = asResourceRoot(resourceRoot);
373
+
374
+ const metadataPath = `${EDITOR_SCHEMA_DIR}/${SNAPSHOT_FILE}`;
375
+ const metadataBytes = await readResource(io, root, metadataPath);
376
+ let metadata;
377
+ try {
378
+ metadata = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(metadataBytes));
379
+ } catch (error) {
380
+ throw metadataError(`metadata.json is not valid UTF-8 JSON: ${error?.message ?? String(error)}`);
381
+ }
382
+ const snapshot = validateMetadata(metadata);
383
+
384
+ const configPath = EDITOR_CONFIG_PATH;
385
+ const configBytes = await readResource(io, root, configPath);
386
+ const configText = decodeConfig(configBytes, configPath);
387
+ const starter = renderEditorConfig({ metadata, profile: 'starter', projectFiles });
388
+ const contributor = renderEditorConfig({ metadata, profile: 'contributor', projectFiles });
389
+ if (configText !== starter && configText !== contributor) {
390
+ throw configError(`${configPath} is neither the starter nor the contributor form for this snapshot`);
391
+ }
392
+
393
+ const staged = [{
394
+ path: configPath,
395
+ bytes: configBytes,
396
+ sha256: io.hashBytes(configBytes),
397
+ }];
398
+ for (const source of snapshot.sources) {
399
+ const path = `${EDITOR_SCHEMA_DIR}/${source.file}`;
400
+ const bytes = await readResource(io, root, path);
401
+ if (bytes.byteLength !== source.bytes) {
402
+ throw resourceError(
403
+ 'editor_resource_corrupt',
404
+ `editor resource ${path} is ${bytes.byteLength} bytes; metadata records ${source.bytes}`,
405
+ );
406
+ }
407
+ const digest = io.hashBytes(bytes);
408
+ if (digest !== source.sha256) {
409
+ throw resourceError(
410
+ 'editor_resource_corrupt',
411
+ `editor resource ${path} digest ${digest} does not match metadata ${source.sha256}`,
412
+ );
413
+ }
414
+ staged.push({ path, bytes, sha256: digest });
415
+ }
416
+ staged.push({
417
+ path: metadataPath,
418
+ bytes: metadataBytes,
419
+ sha256: io.hashBytes(metadataBytes),
420
+ });
421
+ return staged;
422
+ }
package/lib/new.mjs CHANGED
@@ -10,6 +10,7 @@
10
10
  // There is no rollback and no transaction claim.
11
11
 
12
12
  import { PROJECT_FILES } from './contract.mjs';
13
+ import { stageEditorResources } from './editor-resources.mjs';
13
14
  import { DemoError, EXIT_CODES, projectError, usageError } from './errors.mjs';
14
15
  import { createTestTone } from './wav.mjs';
15
16
 
@@ -19,6 +20,7 @@ const CIRCLE_STARTER = new URL('../starters/circle/', import.meta.url).href;
19
20
  const STARTER_FILES = [
20
21
  { path: PROJECT_FILES.program, source: 'program.sjon' },
21
22
  { path: PROJECT_FILES.timeline, source: 'timeline.piece.sjon' },
23
+ { path: 'README.md', source: 'README.md' },
22
24
  { path: 'kernels/curl.wgsl', source: 'kernels/curl.wgsl' },
23
25
  { path: 'kernels/ember.wgsl', source: 'kernels/ember.wgsl' },
24
26
  { path: 'kernels/hash.wgsl', source: 'kernels/hash.wgsl' },
@@ -162,6 +164,10 @@ export function newUsageText() {
162
164
  ' soundtrack.opus — exactly one may exist at a time)',
163
165
  ' kernels/{curl,ember,hash,simplex}.wgsl',
164
166
  ' bake/spans.bin',
167
+ ' sjon-lsp.sjon editor associations for the snapshotted schemas',
168
+ ' .animader/schemas/metadata.json',
169
+ ' .animader/schemas/{piece,world,session,machine,bridge,tempura,midi,it,pacer,pngine}.sjon',
170
+ ' committed offline editor schema snapshot',
165
171
  '',
166
172
  'Options:',
167
173
  ` --starter NAME starter to copy (default: ember; available: ${starterList()})`,
@@ -276,6 +282,11 @@ export async function createProject({ folder, starter, io }) {
276
282
  staged.push({ path: entry.path, bytes, sha256: io.hashBytes(bytes) });
277
283
  }
278
284
 
285
+ // The shared packaged snapshot is staged after the starter's own files
286
+ // (the soundtrack stays the last starter entry) and before any write:
287
+ // a missing or stale resource refuses here, leaving the target empty.
288
+ staged.push(...await stageEditorResources({ io }));
289
+
279
290
  const created = [];
280
291
  for (const file of staged) {
281
292
  try {