@onereach/json-schema-aot 0.0.0-stage → 0.2.0-framework.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.
Files changed (54) hide show
  1. package/README.md +271 -2
  2. package/dist/index.d.mts +17 -0
  3. package/dist/index.d.mts.map +1 -0
  4. package/dist/index.mjs +189 -0
  5. package/dist/index.mjs.map +1 -0
  6. package/dist/replace-directory.d.mts +20 -0
  7. package/dist/replace-directory.d.mts.map +1 -0
  8. package/dist/replace-directory.mjs +41 -0
  9. package/dist/replace-directory.mjs.map +1 -0
  10. package/dist/rolldown/authoring-inputs.d.mts +13 -0
  11. package/dist/rolldown/authoring-inputs.d.mts.map +1 -0
  12. package/dist/rolldown/authoring-inputs.mjs +86 -0
  13. package/dist/rolldown/authoring-inputs.mjs.map +1 -0
  14. package/dist/rolldown/directories.d.mts +7 -0
  15. package/dist/rolldown/directories.d.mts.map +1 -0
  16. package/dist/rolldown/directories.mjs +65 -0
  17. package/dist/rolldown/directories.mjs.map +1 -0
  18. package/dist/rolldown/generate.d.mts +7 -0
  19. package/dist/rolldown/generate.d.mts.map +1 -0
  20. package/dist/rolldown/generate.mjs +49 -0
  21. package/dist/rolldown/generate.mjs.map +1 -0
  22. package/dist/rolldown/index.d.mts +18 -0
  23. package/dist/rolldown/index.d.mts.map +1 -0
  24. package/dist/rolldown/index.mjs +185 -0
  25. package/dist/rolldown/index.mjs.map +1 -0
  26. package/dist/rolldown/inputs.d.mts +7 -0
  27. package/dist/rolldown/inputs.d.mts.map +1 -0
  28. package/dist/rolldown/inputs.mjs +65 -0
  29. package/dist/rolldown/inputs.mjs.map +1 -0
  30. package/dist/rolldown/node-options.d.mts +10 -0
  31. package/dist/rolldown/node-options.d.mts.map +1 -0
  32. package/dist/rolldown/node-options.mjs +95 -0
  33. package/dist/rolldown/node-options.mjs.map +1 -0
  34. package/dist/rolldown/publish.d.mts +10 -0
  35. package/dist/rolldown/publish.d.mts.map +1 -0
  36. package/dist/rolldown/publish.mjs +25 -0
  37. package/dist/rolldown/publish.mjs.map +1 -0
  38. package/dist/rolldown/resolution.d.mts +10 -0
  39. package/dist/rolldown/resolution.d.mts.map +1 -0
  40. package/dist/rolldown/resolution.mjs +105 -0
  41. package/dist/rolldown/resolution.mjs.map +1 -0
  42. package/dist/rolldown/schema-worker.d.mts +2 -0
  43. package/dist/rolldown/schema-worker.d.mts.map +1 -0
  44. package/dist/rolldown/schema-worker.mjs +24 -0
  45. package/dist/rolldown/schema-worker.mjs.map +1 -0
  46. package/dist/rolldown/worker-protocol.d.mts +10 -0
  47. package/dist/rolldown/worker-protocol.d.mts.map +1 -0
  48. package/dist/rolldown/worker-protocol.mjs +9 -0
  49. package/dist/rolldown/worker-protocol.mjs.map +1 -0
  50. package/dist/validator-source.d.mts +10 -0
  51. package/dist/validator-source.d.mts.map +1 -0
  52. package/dist/validator-source.mjs +62 -0
  53. package/dist/validator-source.mjs.map +1 -0
  54. package/package.json +49 -3
package/README.md CHANGED
@@ -1,3 +1,272 @@
1
- # Temporary Holding Version
1
+ # @onereach/json-schema-aot
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Build-time JSON Schema tooling, independent of the state-machine framework,
4
+ OneReach, and TypeBox. TypeBox definitions are supported inputs, not a dependency.
5
+
6
+ ```js
7
+ import { generateArtifacts } from '@onereach/json-schema-aot';
8
+
9
+ await generateArtifacts(
10
+ {
11
+ Configuration: {
12
+ type: 'object',
13
+ properties: { name: { type: 'string', description: 'Display name.' } },
14
+ required: ['name'],
15
+ additionalProperties: false,
16
+ },
17
+ },
18
+ {
19
+ outputDirectory: new URL('./generated/', import.meta.url),
20
+ temporaryDirectory: new URL('./.build/', import.meta.url),
21
+ },
22
+ );
23
+ ```
24
+
25
+ Install this package as a **development dependency**. AJV, format support,
26
+ declaration generation, TypeScript, and bundling belong to this tool. Generated
27
+ runtime files do not import this package, TypeBox, AJV, or Standard Schema.
28
+ AJV's standalone runtime helpers are bundled into each validator.
29
+
30
+ The package's public ESM entry points have no import-time generation or plugin
31
+ registration. Its `sideEffects` list preserves the private
32
+ `dist/rolldown/schema-worker.mjs` entry, which intentionally generates artifacts
33
+ and posts its result when the worker loads. Do not mark the entire package
34
+ side-effect-free or remove that worker from published output.
35
+
36
+ ## Generated artifacts
37
+
38
+ For each named schema:
39
+
40
+ Schema keys are PascalCase ASCII type names (for example, `Configuration`).
41
+ Use `fileNames` for filesystem naming independent of those exported type names.
42
+ An authored display `title` does not replace the exported type name.
43
+
44
+ - `<Name>.mjs`: `validator` implementing synchronous Standard Schema v1;
45
+ `isValid` for structural type guards; low-level `validate` returning
46
+ `{ valid, errors }` for existing structural consumers; and `fields` containing
47
+ declared root property names.
48
+ - `<Name>.d.mts`: documented, independent data types and validator declarations.
49
+ - `json-schemas/<Name>.json`: portable Draft 2020-12 schema.
50
+ - Shared `schema-values.mjs` / `.d.mts`: deeply frozen schema literals and their
51
+ literal declarations.
52
+
53
+ ```js
54
+ import { validator } from './generated/Configuration.mjs';
55
+
56
+ const result = validator['~standard'].validate(input);
57
+ if (result.issues) console.error(result.issues);
58
+ else console.log(result.value);
59
+ ```
60
+
61
+ Standard validation returns the original successful input and fresh message/path
62
+ issues on failure. Paths are decoded string segments; missing-property issues
63
+ include the missing field. No coercion, defaults, stripping, or transformations
64
+ occur. The low-level API is internal structural interop, not a second framework
65
+ runtime-validator protocol.
66
+
67
+ ## Options and limits
68
+
69
+ - `outputDirectory` and `temporaryDirectory`: filesystem paths or file URLs.
70
+ Use sibling locations on the same filesystem and one writer per output.
71
+ - `fileNames`: override filenames independently of exported data type names.
72
+ - `jsonDirectory`: a single relative directory name, or `.` for flat JSON output.
73
+ - `validateDefaults`: check authored defaults without applying them; disabled by
74
+ default. Checks traverse properties/items, not examples or default data.
75
+ - `promote`: optional directory-installation function for integration testing.
76
+
77
+ Draft 2020-12, strict keywords, standard AJV formats, and synchronous schemas are
78
+ supported. Unresolved references fail without fetching external schemas.
79
+ TypeBox symbol metadata is excluded; nonportable string-keyed values (functions,
80
+ undefined, nonfinite numbers, cycles, and host objects) fail rather than silently
81
+ changing the schema. Boolean schemas are supported.
82
+
83
+ Declarations describe structural data only; they cannot prove semantic checks,
84
+ formats, or arbitrary refinements. Keep creation transformations, domain checks,
85
+ normalization, SDK values, and runtime caches in consumers.
86
+
87
+ Generation stages all artifacts before promotion, restores prior outputs on
88
+ installation failure, and preserves recovery backups if rollback also fails.
89
+ Consumers must include schema and generator changes in their build/watch inputs.
90
+
91
+ ## Rolldown and tsdown integration
92
+
93
+ The optional `@onereach/json-schema-aot/rolldown` entry point owns bundler watch
94
+ integration without coupling the root generation API to a bundler lifecycle:
95
+
96
+ ```ts
97
+ import { defineConfig } from 'tsdown';
98
+ import { jsonSchemaAot } from '@onereach/json-schema-aot/rolldown';
99
+
100
+ const schemaPlugin = jsonSchemaAot({
101
+ entry: new URL('./src/schemas/index.ts', import.meta.url),
102
+ outputDirectory: new URL('./generated/', import.meta.url),
103
+ temporaryDirectory: new URL('./.build/', import.meta.url),
104
+ validateDefaults: true,
105
+ });
106
+
107
+ export default defineConfig({
108
+ entry: ['src/index.ts'],
109
+ format: ['esm'],
110
+ dts: true,
111
+ inputOptions(options) {
112
+ options.plugins = [options.plugins, schemaPlugin];
113
+ },
114
+ copy: [{ from: 'generated/json-schemas/*.json', to: 'dist/json-schemas' }],
115
+ });
116
+ ```
117
+
118
+ The same plugin works in Rolldown's `plugins` array, including native watch mode.
119
+ With tsdown, use `inputOptions` as above: its separate CJS declaration pipeline
120
+ does not include ordinary user `plugins`. This registers the same serialized
121
+ generator in every pipeline. Tests cover ESM, CJS, and dual-format watch builds,
122
+ including executable output, `.d.mts`, `.d.cts`, and copied JSON.
123
+ The schema entry exports named schemas, such as `export const Configuration = …`.
124
+ For an entry exporting a record instead, set `exportName` to that export's name
125
+ (including `'default'`). Non-schema exports must not be included in that record.
126
+ All ordinary generation options except the testing-only `promote` are supported.
127
+ String paths resolve relative to the process working directory; file URLs avoid
128
+ ambiguity when configuring another package.
129
+
130
+ The adapter bundles the authoring graph separately, registers imported files as
131
+ watch inputs, and evaluates generation in a fresh worker. Transitive schema
132
+ imports therefore reload without accumulating Node module-cache entries.
133
+ Generation runs in an early, sequential `buildStart` hook, before module loading
134
+ and later build-start hooks. Input content snapshots are checked again after
135
+ generation; edits made while generation is running cause a retry before consumers
136
+ load artifacts, including during the initial build before native watch inputs are
137
+ active. The source loader hashes and compiles the same captured bytes, preserving
138
+ TypeScript, JavaScript/CommonJS, and JSON loading rather than rereading between
139
+ snapshotting and compilation. Use one plugin instance per generated directory; unrelated builds must
140
+ not write that directory concurrently.
141
+
142
+ Unchanged authoring bundles do not rewrite intact artifacts, avoiding
143
+ generated-output watch loops. An in-memory manifest checks generated filenames
144
+ and content; missing or modified artifacts are repaired on the next build.
145
+ `tsconfig` selects the authoring bundler's TypeScript configuration;
146
+ `watchFiles` adds explicit file inputs, including configuration or data read by
147
+ authoring code. Changes to these files also invalidate the generation fingerprint.
148
+ The explicitly selected or automatically discovered schema tsconfig, its extended
149
+ configuration chain, and existing package manifests observed during schema-import
150
+ resolution are also watched and snapshotted. Changes to path mappings and package
151
+ `exports`/`imports` maps therefore regenerate without touching schema source.
152
+ Configuration tracking does not add syntax or resolution features beyond those
153
+ supported by Rolldown.
154
+ Custom Node conditions from `--conditions`, `-C`, and `NODE_OPTIONS` are applied
155
+ to both static authoring resolution and worker evaluation. Rolldown's standard
156
+ `node`, `default`, and import/require-specific conditions remain in effect.
157
+ Repeated condition flags and Node's double-quoted `NODE_OPTIONS` values are
158
+ supported; conditions also participate in the generation fingerprint.
159
+ Keep authoring statically bundleable: computed imports and filesystem reads are
160
+ not automatically tracked, and paths relative to the bundled module's
161
+ `import.meta.url` refer to the temporary bundle, not the authored file.
162
+ Bundler configuration and plugin implementation changes remain the host build
163
+ tool's reload responsibility. After adding a previously unresolved import or
164
+ previously absent resolution-metadata file, edit an already watched input or
165
+ restart watch: creating an untracked file alone does not necessarily rebuild.
166
+
167
+ ### Directory ownership
168
+
169
+ `outputDirectory` and `temporaryDirectory` must be dedicated, disjoint trees:
170
+ neither may equal or contain the other. The schema entry, imported authoring
171
+ modules, consumer entry points, tracked configuration, and explicit watch inputs
172
+ must remain outside both trees. Bundle generated artifacts through an authored
173
+ entry point outside these directories.
174
+
175
+ The adapter rejects overlaps with known inputs before generation and rechecks
176
+ before promotion. It checks both normalized directory-entry paths and resolved
177
+ symlink targets, including existing ancestors of missing paths, so outward-pointing
178
+ symlinks cannot hide an authored entry or a nested staging/output tree.
179
+ Transitive imports retain their lexical resolution paths as well as canonical
180
+ module identities, including file aliases, directory aliases, and symlinked
181
+ packages. Both are checked for ownership; alias paths and their targets are
182
+ watched. Retargeting an alias invalidates the input snapshot even when its new
183
+ target has identical source bytes. Compilation still uses canonical module IDs,
184
+ preserving module deduplication and target-relative dependency resolution.
185
+ Shared ancestor discovery is deduplicated within a resolution pass; those results
186
+ are not reused across input-freshness checks or generation attempts.
187
+ Rejection leaves authored files intact. These guards protect known build
188
+ inputs, not unrelated files placed in a designated output directory: successful
189
+ generation still replaces that directory in full.
190
+ Missing output parent directories are created during publication, so nested output
191
+ paths work on a clean checkout. Directory ownership is revalidated after creating
192
+ the parent. Publication then rechecks input snapshots; stale candidates are
193
+ discarded and retried without replacing live artifacts or updating the generation
194
+ cache. This also covers edits made during publication preparation, after worker
195
+ generation has completed.
196
+
197
+ Failed generation fails the build, preserves the prior **generated directory**,
198
+ and permits recovery on subsequent edits. The plugin does not provide a
199
+ transaction around the host's `dist/` cleanup or writes. In particular, tsdown
200
+ cleans outputs before `buildStart`; retaining a working published build after
201
+ failure requires separate orchestration.
202
+
203
+ ### Cancellation and shutdown
204
+
205
+ For programmatic builds/watchers, pass an `AbortSignal` and abort it **before**
206
+ awaiting the host watcher's shutdown:
207
+
208
+ ```ts
209
+ const cancellation = new AbortController();
210
+ const schemaPlugin = jsonSchemaAot({
211
+ entry: new URL('./src/schemas/index.ts', import.meta.url),
212
+ outputDirectory: new URL('./generated/', import.meta.url),
213
+ temporaryDirectory: new URL('./.build/', import.meta.url),
214
+ signal: cancellation.signal,
215
+ });
216
+
217
+ // Register schemaPlugin with the host as shown above.
218
+ // When stopping:
219
+ cancellation.abort();
220
+ await watcher.close();
221
+ ```
222
+
223
+ Rolldown waits for active builds before invoking `closeWatcher`, so that hook
224
+ alone cannot interrupt stuck authoring code. Aborting terminates the active
225
+ worker and prevents queued generation from starting; normal watch closure also
226
+ disposes the plugin through `closeWatcher`. A disposed plugin instance is not
227
+ reusable.
228
+
229
+ Workers only generate into isolated staging directories. The parent promotes
230
+ complete, current artifacts using the existing rollback-safe installation.
231
+ Workers explicitly report job success or failure; the parent terminates them and
232
+ waits for thread exit before promotion or cleanup. Authoring-module timers and
233
+ other background handles therefore cannot keep a completed job alive. Exiting
234
+ without a completion result fails the build, even with exit code zero.
235
+ Cancellation during staging or publication preparation leaves live artifacts intact
236
+ and removes temporary outputs. The parent checks cancellation again after directory
237
+ validation and the final input-freshness check, immediately before installation starts.
238
+ Newly created, empty output
239
+ ancestors may remain after cancellation or failure. A promotion already in progress
240
+ completes or rolls back before shutdown;
241
+ it is not forcibly interrupted. Failed rollback retains recovery backups.
242
+ Worker Node arguments use an allowlist for module resolution, preload/loader,
243
+ source-map, warning, and symlink settings. Invocation-only, V8/heap, debugging,
244
+ and profiling flags are not forwarded; parent CLI heap settings are not converted
245
+ into worker resource limits.
246
+ `NODE_OPTIONS` remains inherited by workers; only its custom conditions are
247
+ explicitly added to worker arguments, without replaying its preloads or loaders.
248
+
249
+ Contracts and both step packages use this plugin in their tsdown configurations,
250
+ including native watch mode through `pnpm dev` / `pnpm watch`. No custom contracts
251
+ watcher remains. Generation failures preserve generated artifacts, not tsdown's
252
+ cleaned `dist/`. Rebuild the tool and restart watch after changing tooling;
253
+ configuration changes also require a restart.
254
+
255
+ Run `pnpm --filter @onereach/json-schema-aot unit` for generation, isolated-runtime,
256
+ declaration, non-mutation, diagnostics, and failure-preservation tests.
257
+ Build the tool first when running plugin tests directly; their workers execute
258
+ the published JavaScript modules.
259
+
260
+ ## Implementation and builds
261
+
262
+ Author the generator and its tests in TypeScript (`src/**/*.mts`, `test/**/*.mts`).
263
+ Bundler-specific implementation and tests are grouped under `src/rolldown/` and
264
+ `test/rolldown/`; the public import remains `/rolldown`.
265
+ The tool owns tsdown integration tests; tsdown is a development dependency only.
266
+ `pnpm --filter @onereach/json-schema-aot build` compiles JavaScript, declaration
267
+ files, and source maps to `dist/`; npm exports point only to those built outputs.
268
+ Public API declarations are inferred from the implementation, not maintained
269
+ separately. `typecheck` checks both the generator and its tests.
270
+
271
+ Turbo builds the tool before dependent contracts and steps. For direct consumer
272
+ builds or native watch outside Turbo, build workspace dependencies first.
@@ -0,0 +1,17 @@
1
+ import type { DirectoryPaths } from './replace-directory.mjs';
2
+ /**
3
+ * Build-time output locations and policies. Only one writer may own an output directory.
4
+ */
5
+ export interface GenerateOptions {
6
+ outputDirectory: string | URL;
7
+ temporaryDirectory: string | URL;
8
+ fileNames?: Record<string, string>;
9
+ jsonDirectory?: string;
10
+ validateDefaults?: boolean;
11
+ promote?: (paths: DirectoryPaths) => Promise<void>;
12
+ }
13
+ /**
14
+ * Prepare artifacts completely before replacing the working generated directory.
15
+ */
16
+ export declare function generateArtifacts(contracts: Record<string, object | boolean>, { outputDirectory, temporaryDirectory, fileNames, jsonDirectory, validateDefaults, promote, }: GenerateOptions): Promise<void>;
17
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.mts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAW9D;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,eAAe,EAAE,MAAM,GAAG,GAAG,CAAC;IAC9B,kBAAkB,EAAE,MAAM,GAAG,GAAG,CAAC;IACjC,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACnC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACpD;AAsED;;GAEG;AACH,wBAAsB,iBAAiB,CACrC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,EAC3C,EACE,eAAe,EACf,kBAAkB,EAClB,SAAc,EACd,aAA8B,EAC9B,gBAAwB,EACxB,OAA0B,GAC3B,EAAE,eAAe,GACjB,OAAO,CAAC,IAAI,CAAC,CA+Ff"}
package/dist/index.mjs ADDED
@@ -0,0 +1,189 @@
1
+ import { Ajv2020 } from 'ajv/dist/2020.js';
2
+ import standaloneCode from 'ajv/dist/standalone/index.js';
3
+ import formats from 'ajv-formats';
4
+ import { compile } from 'json-schema-to-typescript';
5
+ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
6
+ import { createRequire } from 'node:module';
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { build } from 'rolldown';
10
+ import { transpileDeclaration } from 'typescript';
11
+ import { DirectoryRecoveryError, replaceDirectory } from './replace-directory.mjs';
12
+ import { validatorDeclarationSource, validatorModuleSource } from './validator-source.mjs';
13
+ const require = createRequire(import.meta.url);
14
+ function isObject(value) {
15
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
16
+ }
17
+ /**
18
+ * Check authored defaults without applying them. Walk properties/items only,
19
+ * never interpreting examples or default data as additional schemas.
20
+ */
21
+ function validateCreationDefaults(schema, location, ajv) {
22
+ if (!isObject(schema))
23
+ return;
24
+ if (Object.hasOwn(schema, 'default')) {
25
+ const validator = ajv.compile(schema);
26
+ if (!validator(structuredClone(schema.default)))
27
+ throw new Error(`Invalid creation default at ${location}`);
28
+ }
29
+ const properties = isObject(schema.properties) ? schema.properties : {};
30
+ for (const [name, property] of Object.entries(properties))
31
+ validateCreationDefaults(property, `${location}/properties/${name}`, ajv);
32
+ if (schema.items)
33
+ validateCreationDefaults(schema.items, `${location}/items`, ajv);
34
+ }
35
+ /**
36
+ * The declaration generator treats annotation-only schemas as objects. Preserve
37
+ * opaque values as unknown without adding generator keywords to portable schemas.
38
+ */
39
+ function declarationSchema(schema) {
40
+ if (typeof schema === 'boolean')
41
+ return { tsType: schema ? 'unknown' : 'never' };
42
+ if (!isObject(schema))
43
+ throw new Error('Expected an object or boolean schema');
44
+ const result = structuredClone(schema);
45
+ if (Object.keys(result).every((key) => ['description', 'examples', 'default'].includes(key)))
46
+ result.tsType = 'unknown';
47
+ if (isObject(result.properties))
48
+ result.properties = Object.fromEntries(Object.entries(result.properties).map(([name, property]) => [name, declarationSchema(property)]));
49
+ if (result.items)
50
+ result.items = declarationSchema(result.items);
51
+ return result;
52
+ }
53
+ /**
54
+ * Copy JSON values without silently converting unsupported values. TypeBox's
55
+ * symbol-keyed authoring metadata is excluded; string-keyed values must be portable.
56
+ */
57
+ function portable(value, ancestors = new Set()) {
58
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
59
+ return value;
60
+ if (typeof value === 'number' && Number.isFinite(value))
61
+ return value;
62
+ if (typeof value !== 'object' || ancestors.has(value))
63
+ throw new Error('Schema contains a nonportable value or cycle');
64
+ const prototype = Object.getPrototypeOf(value);
65
+ if (prototype !== null && prototype !== Object.prototype && !Array.isArray(value))
66
+ throw new Error('Schema contains a nonportable object');
67
+ ancestors.add(value);
68
+ try {
69
+ if (Array.isArray(value)) {
70
+ if (Object.keys(value).length !== value.length)
71
+ throw new Error('Schema contains a nonportable array');
72
+ return Array.from(value, (item) => portable(item, ancestors));
73
+ }
74
+ return Object.fromEntries(Object.entries(Object.getOwnPropertyDescriptors(value)).map(([key, descriptor]) => {
75
+ if (!descriptor.enumerable || !Object.hasOwn(descriptor, 'value'))
76
+ throw new Error('Schema contains a nonportable property');
77
+ return [key, portable(descriptor.value, ancestors)];
78
+ }));
79
+ }
80
+ finally {
81
+ ancestors.delete(value);
82
+ }
83
+ }
84
+ /**
85
+ * Prepare artifacts completely before replacing the working generated directory.
86
+ */
87
+ export async function generateArtifacts(contracts, { outputDirectory, temporaryDirectory, fileNames = {}, jsonDirectory = 'json-schemas', validateDefaults = false, promote = replaceDirectory, }) {
88
+ if (jsonDirectory !== '.' && !/^[\w-]+$/.test(jsonDirectory))
89
+ throw new Error('JSON directory must be a single relative directory name');
90
+ const output = outputDirectory instanceof URL ? fileURLToPath(outputDirectory) : path.resolve(outputDirectory);
91
+ const temporary = temporaryDirectory instanceof URL ? fileURLToPath(temporaryDirectory) : path.resolve(temporaryDirectory);
92
+ await mkdir(temporary, { recursive: true });
93
+ const work = await mkdtemp(path.join(temporary, 'json-schema-aot-'));
94
+ const prepared = path.join(work, 'prepared');
95
+ let isPreserveWork = false;
96
+ try {
97
+ await mkdir(path.join(prepared, jsonDirectory), { recursive: true });
98
+ const ajv = new Ajv2020({
99
+ strict: true,
100
+ allErrors: true,
101
+ coerceTypes: false,
102
+ useDefaults: false,
103
+ removeAdditional: false,
104
+ code: { source: true, esm: true },
105
+ });
106
+ formats.default(ajv);
107
+ let schemaDeclarations = '';
108
+ let schemaValues = `function freeze(value) {
109
+ if (value !== null && typeof value === 'object') {
110
+ for (const child of Object.values(value)) freeze(child);
111
+ Object.freeze(value);
112
+ }
113
+ return value;
114
+ }\n`;
115
+ const entries = Object.entries(contracts).map(([name, authored]) => {
116
+ const schema = portable(authored);
117
+ if (typeof schema !== 'boolean' && !isObject(schema))
118
+ throw new Error(`Expected a JSON Schema: ${name}`);
119
+ if (typeof schema !== 'boolean' && schema.$async)
120
+ throw new Error('Async schemas are unsupported');
121
+ ajv.addSchema(schema, name);
122
+ return [name, schema];
123
+ });
124
+ const usedFiles = new Set();
125
+ for (const [name, schema] of entries) {
126
+ // Strip TypeBox's symbol metadata and emit only portable JSON literals.
127
+ const fileName = fileNames[name] ?? name;
128
+ if (!/^[A-Z][A-Za-z0-9]*$/.test(name) || /\d[a-z]/.test(name))
129
+ throw new Error(`Schema export names must be PascalCase type names: ${name}`);
130
+ if (!/^[\w-]+$/.test(fileName))
131
+ throw new Error(`Invalid artifact file name: ${fileName}`);
132
+ if (fileName === 'schema-values' || usedFiles.has(fileName))
133
+ throw new Error(`Duplicate artifact file name: ${fileName}`);
134
+ usedFiles.add(fileName);
135
+ if (validateDefaults)
136
+ validateCreationDefaults(schema, name, ajv);
137
+ const entry = path.join(work, `${fileName}.mjs`);
138
+ const fields = Object.keys(typeof schema !== 'boolean' && isObject(schema.properties) ? schema.properties : {});
139
+ await writeFile(entry, validatorModuleSource(standaloneCode.default(ajv, { isValid: name }), fields));
140
+ await build({
141
+ input: entry,
142
+ plugins: [
143
+ {
144
+ name: 'resolve-generator-helpers',
145
+ resolveId(id) {
146
+ if (/^ajv(?:-formats)?\//.test(id))
147
+ return require.resolve(id);
148
+ return;
149
+ },
150
+ },
151
+ ],
152
+ onwarn(warning, defaultHandler) {
153
+ if (warning.code === 'UNRESOLVED_IMPORT')
154
+ throw new Error(warning.message);
155
+ defaultHandler(warning);
156
+ },
157
+ output: { file: path.join(prepared, `${fileName}.mjs`), format: 'esm' },
158
+ });
159
+ const declarations = await compile({ ...declarationSchema(schema), title: name }, name, {
160
+ bannerComment: '// Generated from authored schemas. Do not edit.',
161
+ unknownAny: true,
162
+ // Open records must not acquire declaration-only arbitrary property limits.
163
+ additionalProperties: true,
164
+ enableConstEnums: false,
165
+ });
166
+ await writeFile(path.join(prepared, `${fileName}.d.mts`), validatorDeclarationSource(declarations, name));
167
+ schemaValues += `export const ${name} = freeze(JSON.parse(${JSON.stringify(JSON.stringify(schema))}));\n`;
168
+ schemaDeclarations += `export const ${name} = ${JSON.stringify(schema)} as const;\n`;
169
+ await writeFile(path.join(prepared, jsonDirectory, `${fileName}.json`), `${JSON.stringify(typeof schema === 'boolean' ? schema : { $schema: 'https://json-schema.org/draft/2020-12/schema', ...schema }, undefined, 2)}\n`);
170
+ }
171
+ const declaration = transpileDeclaration(schemaDeclarations, { fileName: 'schema-values.mts' });
172
+ if (declaration.diagnostics?.length)
173
+ throw new Error('Failed to generate schema literal declarations');
174
+ await writeFile(path.join(prepared, 'schema-values.mjs'), schemaValues);
175
+ await writeFile(path.join(prepared, 'schema-values.d.mts'), declaration.outputText);
176
+ try {
177
+ await promote({ prepared, output, backup: path.join(work, 'previous') });
178
+ }
179
+ catch (error) {
180
+ isPreserveWork = error instanceof DirectoryRecoveryError;
181
+ throw error;
182
+ }
183
+ }
184
+ finally {
185
+ if (!isPreserveWork)
186
+ await rm(work, { recursive: true, force: true });
187
+ }
188
+ }
189
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,cAAc,MAAM,8BAA8B,CAAC;AAC1D,OAAO,OAAO,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,MAAM,2BAA2B,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAEnF,OAAO,EAAE,0BAA0B,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAE3F,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAoB/C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,YAAY,CAAC,CAAC;QACxE,MAAM,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,qBAAqB,CAAC,EAAE,WAAW,CAAC,UAAU,CAAC,CAAC;QACpF,IAAI,CAAC;YACH,MAAM,OAAO,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,CAAC,CAAC;QAC3E,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,cAAc,GAAG,KAAK,YAAY,sBAAsB,CAAC;YACzD,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;YAAS,CAAC;QACT,IAAI,CAAC,cAAc;YAAE,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IACxE,CAAC;AACH,CAAC","sourcesContent":["import { Ajv2020 } from 'ajv/dist/2020.js';\nimport standaloneCode from 'ajv/dist/standalone/index.js';\nimport formats from 'ajv-formats';\nimport { compile } from 'json-schema-to-typescript';\nimport { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { build } from 'rolldown';\nimport { transpileDeclaration } from 'typescript';\n\nimport { DirectoryRecoveryError, replaceDirectory } from './replace-directory.mjs';\nimport type { DirectoryPaths } from './replace-directory.mjs';\nimport { validatorDeclarationSource, validatorModuleSource } from './validator-source.mjs';\n\nconst require = createRequire(import.meta.url);\n\ntype JsonValue = null | string | number | boolean | JsonValue[] | JsonObject;\n\ninterface JsonObject {\n [key: string]: JsonValue;\n}\n\n/**\n * Build-time output locations and policies. Only one writer may own an output directory.\n */\nexport interface GenerateOptions {\n outputDirectory: string | URL;\n temporaryDirectory: string | URL;\n fileNames?: Record<string, string>;\n jsonDirectory?: string;\n validateDefaults?: boolean;\n promote?: (paths: DirectoryPaths) => Promise<void>;\n}\n\nfunction isObject(value: unknown): value is JsonObject {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Check authored defaults without applying them. Walk properties/items only,\n * never interpreting examples or default data as additional schemas.\n */\nfunction validateCreationDefaults(schema: JsonValue | undefined, location: string, ajv: Ajv2020): void {\n if (!isObject(schema)) return;\n if (Object.hasOwn(schema, 'default')) {\n const validator = ajv.compile(schema);\n if (!validator(structuredClone(schema.default))) throw new Error(`Invalid creation default at ${location}`);\n }\n const properties = isObject(schema.properties) ? schema.properties : {};\n for (const [name, property] of Object.entries(properties))\n validateCreationDefaults(property, `${location}/properties/${name}`, ajv);\n if (schema.items) validateCreationDefaults(schema.items, `${location}/items`, ajv);\n}\n\n/**\n * The declaration generator treats annotation-only schemas as objects. Preserve\n * opaque values as unknown without adding generator keywords to portable schemas.\n */\nfunction declarationSchema(schema: JsonValue): JsonObject {\n if (typeof schema === 'boolean') return { tsType: schema ? 'unknown' : 'never' };\n if (!isObject(schema)) throw new Error('Expected an object or boolean schema');\n const result = structuredClone(schema);\n if (Object.keys(result).every((key) => ['description', 'examples', 'default'].includes(key)))\n result.tsType = 'unknown';\n if (isObject(result.properties))\n result.properties = Object.fromEntries(\n Object.entries(result.properties).map(([name, property]) => [name, declarationSchema(property)]),\n );\n if (result.items) result.items = declarationSchema(result.items);\n return result;\n}\n\n/**\n * Copy JSON values without silently converting unsupported values. TypeBox's\n * symbol-keyed authoring metadata is excluded; string-keyed values must be portable.\n */\nfunction portable(value: unknown, ancestors = new Set<object>()): JsonValue {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value !== 'object' || ancestors.has(value))\n throw new Error('Schema contains a nonportable value or cycle');\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== Object.prototype && !Array.isArray(value))\n throw new Error('Schema contains a nonportable object');\n ancestors.add(value);\n try {\n if (Array.isArray(value)) {\n if (Object.keys(value).length !== value.length) throw new Error('Schema contains a nonportable array');\n return Array.from(value, (item) => portable(item, ancestors));\n }\n return Object.fromEntries(\n Object.entries(Object.getOwnPropertyDescriptors(value)).map(([key, descriptor]) => {\n if (!descriptor.enumerable || !Object.hasOwn(descriptor, 'value'))\n throw new Error('Schema contains a nonportable property');\n return [key, portable(descriptor.value, ancestors)];\n }),\n );\n } finally {\n ancestors.delete(value);\n }\n}\n\n/**\n * Prepare artifacts completely before replacing the working generated directory.\n */\nexport async function generateArtifacts(\n contracts: Record<string, object | boolean>,\n {\n outputDirectory,\n temporaryDirectory,\n fileNames = {},\n jsonDirectory = 'json-schemas',\n validateDefaults = false,\n promote = replaceDirectory,\n }: GenerateOptions,\n): Promise<void> {\n if (jsonDirectory !== '.' && !/^[\\w-]+$/.test(jsonDirectory))\n throw new Error('JSON directory must be a single relative directory name');\n const output = outputDirectory instanceof URL ? fileURLToPath(outputDirectory) : path.resolve(outputDirectory);\n const temporary =\n temporaryDirectory instanceof URL ? fileURLToPath(temporaryDirectory) : path.resolve(temporaryDirectory);\n await mkdir(temporary, { recursive: true });\n const work = await mkdtemp(path.join(temporary, 'json-schema-aot-'));\n const prepared = path.join(work, 'prepared');\n let isPreserveWork = false;\n try {\n await mkdir(path.join(prepared, jsonDirectory), { recursive: true });\n const ajv = new Ajv2020({\n strict: true,\n allErrors: true,\n coerceTypes: false,\n useDefaults: false,\n removeAdditional: false,\n code: { source: true, esm: true },\n });\n formats.default(ajv);\n let schemaDeclarations = '';\n let schemaValues = `function freeze(value) {\n if (value !== null && typeof value === 'object') {\n for (const child of Object.values(value)) freeze(child);\n Object.freeze(value);\n }\n return value;\n }\\n`;\n const entries = Object.entries(contracts).map(([name, authored]) => {\n const schema = portable(authored);\n if (typeof schema !== 'boolean' && !isObject(schema)) throw new Error(`Expected a JSON Schema: ${name}`);\n if (typeof schema !== 'boolean' && schema.$async) throw new Error('Async schemas are unsupported');\n ajv.addSchema(schema, name);\n return [name, schema] as const;\n });\n const usedFiles = new Set();\n for (const [name, schema] of entries) {\n // Strip TypeBox's symbol metadata and emit only portable JSON literals.\n const fileName = fileNames[name] ?? name;\n if (!/^[A-Z][A-Za-z0-9]*$/.test(name) || /\\d[a-z]/.test(name))\n throw new Error(`Schema export names must be PascalCase type names: ${name}`);\n if (!/^[\\w-]+$/.test(fileName)) throw new Error(`Invalid artifact file name: ${fileName}`);\n if (fileName === 'schema-values' || usedFiles.has(fileName))\n throw new Error(`Duplicate artifact file name: ${fileName}`);\n usedFiles.add(fileName);\n if (validateDefaults) validateCreationDefaults(schema, name, ajv);\n const entry = path.join(work, `${fileName}.mjs`);\n const fields = Object.keys(typeof schema !== 'boolean' && isObject(schema.properties) ? schema.properties : {});\n await writeFile(entry, validatorModuleSource(standaloneCode.default(ajv, { isValid: name }), fields));\n await build({\n input: entry,\n plugins: [\n {\n name: 'resolve-generator-helpers',\n resolveId(id) {\n if (/^ajv(?:-formats)?\\//.test(id)) return require.resolve(id);\n return;\n },\n },\n ],\n onwarn(warning, defaultHandler) {\n if (warning.code === 'UNRESOLVED_IMPORT') throw new Error(warning.message);\n defaultHandler(warning);\n },\n output: { file: path.join(prepared, `${fileName}.mjs`), format: 'esm' },\n });\n const declarations = await compile({ ...declarationSchema(schema), title: name }, name, {\n bannerComment: '// Generated from authored schemas. Do not edit.',\n unknownAny: true,\n // Open records must not acquire declaration-only arbitrary property limits.\n additionalProperties: true,\n enableConstEnums: false,\n });\n await writeFile(path.join(prepared, `${fileName}.d.mts`), validatorDeclarationSource(declarations, name));\n schemaValues += `export const ${name} = freeze(JSON.parse(${JSON.stringify(JSON.stringify(schema))}));\\n`;\n schemaDeclarations += `export const ${name} = ${JSON.stringify(schema)} as const;\\n`;\n await writeFile(\n path.join(prepared, jsonDirectory, `${fileName}.json`),\n `${JSON.stringify(typeof schema === 'boolean' ? schema : { $schema: 'https://json-schema.org/draft/2020-12/schema', ...schema }, undefined, 2)}\\n`,\n );\n }\n const declaration = transpileDeclaration(schemaDeclarations, { fileName: 'schema-values.mts' });\n if (declaration.diagnostics?.length) throw new Error('Failed to generate schema literal declarations');\n await writeFile(path.join(prepared, 'schema-values.mjs'), schemaValues);\n await writeFile(path.join(prepared, 'schema-values.d.mts'), declaration.outputText);\n try {\n await promote({ prepared, output, backup: path.join(work, 'previous') });\n } catch (error) {\n isPreserveWork = error instanceof DirectoryRecoveryError;\n throw error;\n }\n } finally {\n if (!isPreserveWork) await rm(work, { recursive: true, force: true });\n }\n}\n"]}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Staged, published, and recovery paths on the same filesystem.
3
+ */
4
+ export interface DirectoryPaths {
5
+ prepared: string;
6
+ output: string;
7
+ backup: string;
8
+ }
9
+ /**
10
+ * A failed rollback must leave the backup intact for manual recovery.
11
+ */
12
+ export declare class DirectoryRecoveryError extends AggregateError {
13
+ readonly backup: string;
14
+ constructor(installationError: unknown, restorationError: unknown, backup: string);
15
+ }
16
+ /**
17
+ * Install a prepared directory, restoring the previous directory if installation fails.
18
+ */
19
+ export declare function replaceDirectory({ prepared, output, backup }: DirectoryPaths, move?: (source: string, destination: string) => Promise<void>): Promise<void>;
20
+ //# sourceMappingURL=replace-directory.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replace-directory.d.mts","sourceRoot":"","sources":["../src/replace-directory.mts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,qBAAa,sBAAuB,SAAQ,cAAc;IACxD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;gBAEZ,iBAAiB,EAAE,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM;CAKlF;AAED;;GAEG;AACH,wBAAsB,gBAAgB,CACpC,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,cAAc,EAC5C,IAAI,GAAE,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAU,GACpE,OAAO,CAAC,IAAI,CAAC,CAoBf"}
@@ -0,0 +1,41 @@
1
+ import { rename } from 'node:fs/promises';
2
+ /**
3
+ * A failed rollback must leave the backup intact for manual recovery.
4
+ */
5
+ export class DirectoryRecoveryError extends AggregateError {
6
+ backup;
7
+ constructor(installationError, restorationError, backup) {
8
+ super([installationError, restorationError], `Could not restore generated artifacts; backup: ${backup}`);
9
+ this.name = 'DirectoryRecoveryError';
10
+ this.backup = backup;
11
+ }
12
+ }
13
+ /**
14
+ * Install a prepared directory, restoring the previous directory if installation fails.
15
+ */
16
+ export async function replaceDirectory({ prepared, output, backup }, move = rename) {
17
+ let isHadPrevious = false;
18
+ try {
19
+ await move(output, backup);
20
+ isHadPrevious = true;
21
+ }
22
+ catch (error) {
23
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
24
+ throw error;
25
+ }
26
+ try {
27
+ await move(prepared, output);
28
+ }
29
+ catch (error) {
30
+ if (isHadPrevious) {
31
+ try {
32
+ await move(backup, output);
33
+ }
34
+ catch (restorationError) {
35
+ throw new DirectoryRecoveryError(error, restorationError, backup);
36
+ }
37
+ }
38
+ throw error;
39
+ }
40
+ }
41
+ //# sourceMappingURL=replace-directory.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replace-directory.mjs","sourceRoot":"","sources":["../src/replace-directory.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAW1C;;GAEG;AACH,MAAM,OAAO,sBAAuB,SAAQ,cAAc;IAC/C,MAAM,CAAS;IAExB,YAAY,iBAA0B,EAAE,gBAAyB,EAAE,MAAc;QAC/E,KAAK,CAAC,CAAC,iBAAiB,EAAE,gBAAgB,CAAC,EAAE,kDAAkD,MAAM,EAAE,CAAC,CAAC;QACzG,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;QACrC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAkB,EAC5C,OAA+D,MAAM;IAErE,IAAI,aAAa,GAAG,KAAK,CAAC;IAC1B,IAAI,CAAC;QACH,MAAM,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC3B,aAAa,GAAG,IAAI,CAAC;IACvB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC;YAAE,MAAM,KAAK,CAAC;IAC3F,CAAC;IACD,IAAI,CAAC;QACH,MAAM,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAC/B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,aAAa,EAAE,CAAC;YAClB,IAAI,CAAC;gBACH,MAAM,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;YAC7B,CAAC;YAAC,OAAO,gBAAgB,EAAE,CAAC;gBAC1B,MAAM,IAAI,sBAAsB,CAAC,KAAK,EAAE,gBAAgB,EAAE,MAAM,CAAC,CAAC;YACpE,CAAC;QACH,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { rename } from 'node:fs/promises';\n\n/**\n * Staged, published, and recovery paths on the same filesystem.\n */\nexport interface DirectoryPaths {\n prepared: string;\n output: string;\n backup: string;\n}\n\n/**\n * A failed rollback must leave the backup intact for manual recovery.\n */\nexport class DirectoryRecoveryError extends AggregateError {\n readonly backup: string;\n\n constructor(installationError: unknown, restorationError: unknown, backup: string) {\n super([installationError, restorationError], `Could not restore generated artifacts; backup: ${backup}`);\n this.name = 'DirectoryRecoveryError';\n this.backup = backup;\n }\n}\n\n/**\n * Install a prepared directory, restoring the previous directory if installation fails.\n */\nexport async function replaceDirectory(\n { prepared, output, backup }: DirectoryPaths,\n move: (source: string, destination: string) => Promise<void> = rename,\n): Promise<void> {\n let isHadPrevious = false;\n try {\n await move(output, backup);\n isHadPrevious = true;\n } catch (error) {\n if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) throw error;\n }\n try {\n await move(prepared, output);\n } catch (error) {\n if (isHadPrevious) {\n try {\n await move(backup, output);\n } catch (restorationError) {\n throw new DirectoryRecoveryError(error, restorationError, backup);\n }\n }\n throw error;\n }\n}\n"]}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Keep lexical resolver paths alongside canonical module IDs. Content alone cannot
3
+ * detect a symlink retargeted to identical source with different relative imports.
4
+ */
5
+ export declare function authoringInputs(watchFile: (file: string) => void): {
6
+ contents: Map<string, string>;
7
+ identities: Map<string, string>;
8
+ snapshot: (file: string, bytes: Uint8Array) => void;
9
+ resolveFile: (file: string) => Promise<string>;
10
+ areCurrent: () => Promise<boolean>;
11
+ paths: () => string[];
12
+ };
13
+ //# sourceMappingURL=authoring-inputs.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authoring-inputs.d.mts","sourceRoot":"","sources":["../../src/rolldown/authoring-inputs.mts"],"names":[],"mappings":"AAKA;;;GAGG;AACH,wBAAgB,eAAe,CAAC,SAAS,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI;;;qBAMvC,MAAM,SAAS,UAAU,KAAG,IAAI;wBAgCvB,MAAM,KAAG,OAAO,CAAC,MAAM,CAAC;sBAU5B,OAAO,CAAC,OAAO,CAAC;;EAuB9C"}