@spellkave/world-author 0.0.0-bootstrap
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +89 -0
- package/README.md +62 -0
- package/package.json +57 -0
- package/src/applyset-diff-types.ts +158 -0
- package/src/applyset.ts +82 -0
- package/src/authoring-harness.ts +487 -0
- package/src/browser.ts +114 -0
- package/src/compose.ts +699 -0
- package/src/corpus.generated.ts +279 -0
- package/src/corpus.ts +1180 -0
- package/src/damage.ts +75 -0
- package/src/diagnostics.ts +59 -0
- package/src/diff-manifest-core.ts +393 -0
- package/src/diff-manifest.ts +5 -0
- package/src/docs-index.ts +105 -0
- package/src/dsl.ts +10 -0
- package/src/evaluate.ts +100 -0
- package/src/explain-core.ts +219 -0
- package/src/explain.ts +43 -0
- package/src/filter-manifest-core.ts +122 -0
- package/src/filter-manifest.ts +41 -0
- package/src/grants-core.ts +38 -0
- package/src/grants.ts +10 -0
- package/src/included-manifest-metadata-core.ts +63 -0
- package/src/included-manifest-metadata.ts +21 -0
- package/src/index.ts +30 -0
- package/src/inspect.ts +35 -0
- package/src/inspection.ts +239 -0
- package/src/lint.ts +540 -0
- package/src/manifest-text.ts +21 -0
- package/src/manifest.ts +403 -0
- package/src/metadata.ts +137 -0
- package/src/npc-dm-authority-projection.ts +95 -0
- package/src/npc-dm-documents.ts +339 -0
- package/src/npc-dm-presentation.ts +17 -0
- package/src/npc-dm-srd.ts +51 -0
- package/src/npc-dm-types.ts +723 -0
- package/src/npc-kinds.ts +404 -0
- package/src/npc-quests.ts +319 -0
- package/src/observation-tokens.browser.ts +31 -0
- package/src/observation-tokens.ts +27 -0
- package/src/owner-instance-read.ts +765 -0
- package/src/patch.ts +47 -0
- package/src/ref-tags.ts +149 -0
- package/src/reference.ts +48 -0
- package/src/row-identity.ts +105 -0
- package/src/row-kinds-data.ts +35 -0
- package/src/row-kinds.ts +93 -0
- package/src/scenario-guidance.ts +180 -0
- package/src/scoped-instance-read.ts +187 -0
- package/src/service-only-audience.ts +14 -0
- package/src/session-predicates.ts +6 -0
- package/src/spell.ts +119 -0
- package/src/tag-prefix-families.ts +143 -0
- package/src/tooling.browser.ts +397 -0
- package/src/tooling.ts +38 -0
- package/src/validate.ts +255 -0
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
// embedded-manifest: {"category": "production_schema_constructor", "rationale": "production harness constructs schema envelopes from caller-supplied rows", "signatures": ["schema_object", "schema_shape"]}
|
|
2
|
+
// Generic verb-call-script harness (#1968 "fixtures become verb-call
|
|
3
|
+
// scripts"). Extracted from `packages/spellkave-mechanics/src/core/generate-core-fixtures.ts` so any
|
|
4
|
+
// bundle-generation script (core today; srd/phandelver planned) can reuse the
|
|
5
|
+
// same file-based workspace, manifest merge/render/compare helpers, and
|
|
6
|
+
// drift-check plumbing without re-deriving them.
|
|
7
|
+
//
|
|
8
|
+
// Deliberately has NO dependency on `@spellkave/tool-authoring` — the
|
|
9
|
+
// AUTHOR-facing verb tools (and their `AuthorWorkspace`/`AuthorToolContext`
|
|
10
|
+
// types) live there; this module only needs the STRUCTURAL shape of a
|
|
11
|
+
// workspace (`readToml`/`writeToml`), so it declares its own minimal
|
|
12
|
+
// `HarnessWorkspace` interface instead of importing the nominal type. A
|
|
13
|
+
// generator script imports verbs from shared tool runtime AND this harness from
|
|
14
|
+
// world-author side by side — no cycle between the two packages.
|
|
15
|
+
|
|
16
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
17
|
+
import { tmpdir } from "node:os";
|
|
18
|
+
import { dirname, join, resolve } from "node:path";
|
|
19
|
+
import { splitIncludedManifestMetadata } from "./included-manifest-metadata";
|
|
20
|
+
import { inspectManifest } from "./inspect";
|
|
21
|
+
import { renderSchemaManifest } from "./manifest";
|
|
22
|
+
|
|
23
|
+
/** Structural match for `@spellkave/tool-authoring`'s `AuthorWorkspace` —
|
|
24
|
+
* kept in sync by convention, not by import (see file header). */
|
|
25
|
+
export interface HarnessWorkspace {
|
|
26
|
+
readToml(): string | null;
|
|
27
|
+
writeToml(next: string): string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** An in-memory `HarnessWorkspace` — same shape every verb tool call writes
|
|
31
|
+
* through, but nothing ever touches disk until the script explicitly renders
|
|
32
|
+
* output files. */
|
|
33
|
+
export function memoryWorkspace(): HarnessWorkspace & { current(): string | null } {
|
|
34
|
+
let toml: string | null = null;
|
|
35
|
+
return {
|
|
36
|
+
readToml: () => toml,
|
|
37
|
+
writeToml: (next: string) => {
|
|
38
|
+
toml = next;
|
|
39
|
+
return "(in-memory)";
|
|
40
|
+
},
|
|
41
|
+
current: () => toml,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface KindGroup {
|
|
46
|
+
kind: string;
|
|
47
|
+
rows: Record<string, unknown>[];
|
|
48
|
+
}
|
|
49
|
+
export interface FileEntry {
|
|
50
|
+
relPath: string;
|
|
51
|
+
groups: KindGroup[];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Strip `renderSchemaManifest`'s 2-line schema header + blank line — an
|
|
55
|
+
* included fragment file never carries one (the loader's include
|
|
56
|
+
* concatenation supplies it exactly once, from the root manifest). */
|
|
57
|
+
export function stripHeader(rendered: string): string {
|
|
58
|
+
const lines = rendered.split("\n");
|
|
59
|
+
if (!lines[0]?.startsWith("#:schema")) {
|
|
60
|
+
throw new Error(`renderSchemaManifest header shape changed (line 0): ${lines[0]}`);
|
|
61
|
+
}
|
|
62
|
+
if (!lines[1]?.startsWith("schema_version")) {
|
|
63
|
+
throw new Error(`renderSchemaManifest header shape changed (line 1): ${lines[1]}`);
|
|
64
|
+
}
|
|
65
|
+
if (lines[2] !== "") {
|
|
66
|
+
throw new Error(`renderSchemaManifest header shape changed (line 2 not blank): ${lines[2]}`);
|
|
67
|
+
}
|
|
68
|
+
return lines.slice(3).join("\n");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Render one included fragment file (a flat kind->rows map, no bundle/metadata). */
|
|
72
|
+
export function renderFile(file: FileEntry): string {
|
|
73
|
+
const mini: Record<string, unknown> = { schema_version: "1.0.0" };
|
|
74
|
+
for (const group of file.groups) mini[group.kind] = group.rows;
|
|
75
|
+
return stripHeader(renderSchemaManifest(mini));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Render the root `manifest.toml` (bundle header + metadata + `[[include]]` block). */
|
|
79
|
+
export function renderManifestToml(
|
|
80
|
+
bundle: Record<string, unknown>,
|
|
81
|
+
metadata: Record<string, unknown>,
|
|
82
|
+
includeOrder: readonly string[],
|
|
83
|
+
applyset?: string,
|
|
84
|
+
): string {
|
|
85
|
+
// ADR-0145: a root names its applyset; `undefined` renders no field.
|
|
86
|
+
const mini = {
|
|
87
|
+
schema_version: "1.0.0",
|
|
88
|
+
...(applyset === undefined ? {} : { applyset }),
|
|
89
|
+
metadata,
|
|
90
|
+
bundles: [bundle],
|
|
91
|
+
};
|
|
92
|
+
const rendered = renderSchemaManifest(mini).replace(/\n+$/, "\n");
|
|
93
|
+
const includeBlock = includeOrder.map((path) => `[[include]]\npath = "${path}"\n`).join("\n");
|
|
94
|
+
return `${rendered}\n${includeBlock}`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Write a root manifest + its included fragment files under `outDir`, mirroring
|
|
98
|
+
* a `{outDir}/manifest.toml` + `{outDir}/<relPath>` layout. */
|
|
99
|
+
export function writeOutputs(
|
|
100
|
+
outDir: string,
|
|
101
|
+
bundle: Record<string, unknown>,
|
|
102
|
+
metadata: Record<string, unknown>,
|
|
103
|
+
includeOrder: readonly string[],
|
|
104
|
+
files: readonly FileEntry[],
|
|
105
|
+
applyset?: string,
|
|
106
|
+
): void {
|
|
107
|
+
mkdirSync(outDir, { recursive: true });
|
|
108
|
+
writeFileSync(
|
|
109
|
+
join(outDir, "manifest.toml"),
|
|
110
|
+
renderManifestToml(bundle, metadata, includeOrder, applyset),
|
|
111
|
+
"utf8",
|
|
112
|
+
);
|
|
113
|
+
for (const file of files) {
|
|
114
|
+
const outPath = join(outDir, file.relPath);
|
|
115
|
+
mkdirSync(dirname(outPath), { recursive: true });
|
|
116
|
+
writeFileSync(outPath, renderFile(file), "utf8");
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Concatenate a root source and its direct parsed `[[include]]` files, each
|
|
121
|
+
* followed by "\n". `manifestFile` supports standalone roots such as an
|
|
122
|
+
* adventure descriptor without duplicating loader logic. */
|
|
123
|
+
export function loadFlattened(dir: string, manifestFile = "manifest.toml"): string {
|
|
124
|
+
const manifestText = readFileSync(join(dir, manifestFile), "utf8");
|
|
125
|
+
const includePaths = includePathsFromRoot(manifestText);
|
|
126
|
+
let resolved = `${manifestText}\n`;
|
|
127
|
+
for (const rel of includePaths) {
|
|
128
|
+
const fragment = readFileSync(join(dir, rel), "utf8");
|
|
129
|
+
resolved += `${splitIncludedManifestMetadata(fragment).rowsToml}\n`;
|
|
130
|
+
}
|
|
131
|
+
return resolved;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Merge every top-level ARRAY field of `manifest` into the matching bucket of
|
|
136
|
+
* `into` (creating the bucket on first sight), leaving non-array fields
|
|
137
|
+
* (`schema_version`, `metadata`, `include`) untouched on `into` — a bundle's
|
|
138
|
+
* own `[[include]]`/metadata are per-bundle bookkeeping, never merged content.
|
|
139
|
+
*/
|
|
140
|
+
function mergeManifestRowsInto(
|
|
141
|
+
into: Record<string, unknown>,
|
|
142
|
+
manifest: Record<string, unknown>,
|
|
143
|
+
): void {
|
|
144
|
+
for (const [key, value] of Object.entries(manifest)) {
|
|
145
|
+
if (!Array.isArray(value)) continue;
|
|
146
|
+
const bucket = into[key];
|
|
147
|
+
if (Array.isArray(bucket)) bucket.push(...value);
|
|
148
|
+
else into[key] = [...value];
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export interface BundleManifestSource {
|
|
153
|
+
/** Every authored `[[bundles]].bundle_id` in the flattened source, never inferred from a directory name. */
|
|
154
|
+
bundleIds: string[];
|
|
155
|
+
/** Absolute root TOML path supplied by the caller or its dependency resolver. */
|
|
156
|
+
manifestPath: string;
|
|
157
|
+
/** Root `schema_version`, retained outside the row-only merged projection. */
|
|
158
|
+
schemaVersion: unknown;
|
|
159
|
+
/** Root `[metadata]`; deliberately outside the merged Manifest row projection. */
|
|
160
|
+
metadata: Record<string, unknown>;
|
|
161
|
+
/** Direct `[[include]]` paths in declaration order, with their resolved files. */
|
|
162
|
+
includes: Array<{ path: string; resolvedPath: string }>;
|
|
163
|
+
/**
|
|
164
|
+
* Direct include metadata in declaration order. This is intentionally
|
|
165
|
+
* outside the merged row projection: an include's `[metadata]` describes
|
|
166
|
+
* the source file, not a second bundle root.
|
|
167
|
+
*/
|
|
168
|
+
fragments: Array<{ path: string; resolvedPath: string; metadata: Record<string, unknown> }>;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export interface LoadBundleChainDetailedOptions {
|
|
172
|
+
/** Any root name is valid, including an adventure descriptor such as adventure.manifest.toml. */
|
|
173
|
+
rootManifestPath: string;
|
|
174
|
+
/**
|
|
175
|
+
* The root's TOML when it is not (yet) the file on disk, such as a pending
|
|
176
|
+
* write. `rootManifestPath` still anchors its includes and identity.
|
|
177
|
+
*/
|
|
178
|
+
rootManifestText?: string;
|
|
179
|
+
/** Maps the authored dependency id to its root TOML. Return undefined when it is unavailable. */
|
|
180
|
+
resolveDependency: (bundleId: string, from: BundleManifestSource) => string | undefined;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export interface LoadedBundleChain {
|
|
184
|
+
/** Canonical row projection: only top-level array row kinds are merged. */
|
|
185
|
+
manifest: Record<string, unknown>;
|
|
186
|
+
/** Dependency-before-dependent sources, with root headers retained per source. */
|
|
187
|
+
sources: BundleManifestSource[];
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function recordOf(value: unknown): Record<string, unknown> {
|
|
191
|
+
return value !== null && typeof value === "object" && !Array.isArray(value)
|
|
192
|
+
? (value as Record<string, unknown>)
|
|
193
|
+
: {};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Uses the manifest parser rather than syntax-sensitive text matching so the
|
|
197
|
+
* flattened body and provenance observe exactly the same includes. */
|
|
198
|
+
function includePathsFromRoot(manifestText: string): string[] {
|
|
199
|
+
const root = inspectManifest(manifestText).manifest as Record<string, unknown>;
|
|
200
|
+
return Array.isArray(root.include)
|
|
201
|
+
? root.include
|
|
202
|
+
.map((row) => recordOf(row).path)
|
|
203
|
+
.filter((path): path is string => typeof path === "string")
|
|
204
|
+
: [];
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* A manifest root the loader was pointed at does not exist: the requested root,
|
|
209
|
+
* or the file a `depends_on` resolver returned. Typed so a host can tell a
|
|
210
|
+
* missing bundle from a malformed one without reading the message.
|
|
211
|
+
*/
|
|
212
|
+
export class ManifestRootMissingError extends Error {
|
|
213
|
+
readonly path: string;
|
|
214
|
+
constructor(path: string) {
|
|
215
|
+
super(`loadBundleChainDetailed: manifest root missing '${path}'.`);
|
|
216
|
+
this.name = "ManifestRootMissingError";
|
|
217
|
+
this.path = path;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function sourceForManifest(
|
|
222
|
+
manifestPath: string,
|
|
223
|
+
manifestText?: string,
|
|
224
|
+
): {
|
|
225
|
+
source: BundleManifestSource;
|
|
226
|
+
manifest: Record<string, unknown>;
|
|
227
|
+
} {
|
|
228
|
+
const absolutePath = resolve(manifestPath);
|
|
229
|
+
if (manifestText === undefined && !existsSync(absolutePath)) {
|
|
230
|
+
throw new ManifestRootMissingError(absolutePath);
|
|
231
|
+
}
|
|
232
|
+
const rootText = manifestText ?? readFileSync(absolutePath, "utf8");
|
|
233
|
+
const root = inspectManifest(rootText).manifest as Record<string, unknown>;
|
|
234
|
+
const relativeIncludes = includePathsFromRoot(rootText);
|
|
235
|
+
const fragments = relativeIncludes.map((path) => {
|
|
236
|
+
const resolvedPath = resolve(dirname(absolutePath), path);
|
|
237
|
+
const fragment = splitIncludedManifestMetadata(readFileSync(resolvedPath, "utf8"));
|
|
238
|
+
return { path, resolvedPath, metadata: fragment.metadata, rowsToml: fragment.rowsToml };
|
|
239
|
+
});
|
|
240
|
+
const flattened = `${rootText}\n${fragments.map((fragment) => `${fragment.rowsToml}\n`).join("")}`;
|
|
241
|
+
const parsed = inspectManifest(flattened).manifest as Record<string, unknown>;
|
|
242
|
+
const bundleRows = Array.isArray(parsed.bundles)
|
|
243
|
+
? (parsed.bundles as Record<string, unknown>[])
|
|
244
|
+
: [];
|
|
245
|
+
const bundleIds = [
|
|
246
|
+
...new Set(
|
|
247
|
+
bundleRows.map((row) => row.bundle_id).filter((id): id is string => typeof id === "string"),
|
|
248
|
+
),
|
|
249
|
+
];
|
|
250
|
+
if (bundleIds.length === 0) {
|
|
251
|
+
throw new Error(`loadBundleChainDetailed: '${absolutePath}' declares no bundle_id.`);
|
|
252
|
+
}
|
|
253
|
+
return {
|
|
254
|
+
source: {
|
|
255
|
+
bundleIds,
|
|
256
|
+
manifestPath: absolutePath,
|
|
257
|
+
schemaVersion: root.schema_version,
|
|
258
|
+
metadata: recordOf(root.metadata),
|
|
259
|
+
includes: relativeIncludes.map((path) => ({
|
|
260
|
+
path,
|
|
261
|
+
resolvedPath: resolve(dirname(absolutePath), path),
|
|
262
|
+
})),
|
|
263
|
+
fragments: fragments.map(({ path, resolvedPath, metadata }) => ({
|
|
264
|
+
path,
|
|
265
|
+
resolvedPath,
|
|
266
|
+
metadata,
|
|
267
|
+
})),
|
|
268
|
+
},
|
|
269
|
+
manifest: parsed,
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Load an explicitly rooted bundle dependency closure into the same row-only
|
|
275
|
+
* projection as {@link loadBundleChain}, while retaining each root's authored
|
|
276
|
+
* metadata and direct include provenance in a separate envelope. Dependency
|
|
277
|
+
* traversal is dependency-before-dependent, deduplicates diamonds by authored
|
|
278
|
+
* bundle ID, and does not itself de-duplicate row natural keys.
|
|
279
|
+
*/
|
|
280
|
+
export function loadBundleChainDetailed(
|
|
281
|
+
options: LoadBundleChainDetailedOptions,
|
|
282
|
+
): LoadedBundleChain {
|
|
283
|
+
const manifest: Record<string, unknown> = { schema_version: "1.0.0" };
|
|
284
|
+
const sources: BundleManifestSource[] = [];
|
|
285
|
+
const completed = new Set<string>();
|
|
286
|
+
const visiting: string[] = [];
|
|
287
|
+
const resolvedPaths = new Map<string, string>();
|
|
288
|
+
|
|
289
|
+
function visit(manifestPath: string, expectedBundleId?: string, manifestText?: string): void {
|
|
290
|
+
if (expectedBundleId !== undefined) {
|
|
291
|
+
const cycleAt = visiting.indexOf(expectedBundleId);
|
|
292
|
+
if (cycleAt !== -1) {
|
|
293
|
+
throw new Error(
|
|
294
|
+
`loadBundleChainDetailed: dependency cycle ${[...visiting.slice(cycleAt), expectedBundleId].join(" -> ")}.`,
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
const absolutePath = resolve(manifestPath);
|
|
298
|
+
const knownPath = resolvedPaths.get(expectedBundleId);
|
|
299
|
+
if (knownPath !== undefined) {
|
|
300
|
+
if (knownPath !== absolutePath) {
|
|
301
|
+
throw new Error(
|
|
302
|
+
`loadBundleChainDetailed: dependency '${expectedBundleId}' resolved inconsistently to ` +
|
|
303
|
+
`'${knownPath}' and '${absolutePath}'.`,
|
|
304
|
+
);
|
|
305
|
+
}
|
|
306
|
+
if (completed.has(expectedBundleId)) return;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
const loaded = sourceForManifest(manifestPath, manifestText);
|
|
310
|
+
const { source } = loaded;
|
|
311
|
+
if (expectedBundleId !== undefined && !source.bundleIds.includes(expectedBundleId)) {
|
|
312
|
+
throw new Error(
|
|
313
|
+
`loadBundleChainDetailed: dependency '${expectedBundleId}' resolved to '${source.manifestPath}', ` +
|
|
314
|
+
`which declares bundle_id(s) '${source.bundleIds.join(", ")}'.`,
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
for (const bundleId of source.bundleIds) {
|
|
318
|
+
const knownPath = resolvedPaths.get(bundleId);
|
|
319
|
+
if (knownPath !== undefined && knownPath !== source.manifestPath) {
|
|
320
|
+
throw new Error(
|
|
321
|
+
`loadBundleChainDetailed: bundle_id '${bundleId}' appears in both '${knownPath}' and '${source.manifestPath}'.`,
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
resolvedPaths.set(bundleId, source.manifestPath);
|
|
325
|
+
}
|
|
326
|
+
if (source.bundleIds.every((bundleId) => completed.has(bundleId))) return;
|
|
327
|
+
const activeBundleId = source.bundleIds.find((bundleId) => visiting.includes(bundleId));
|
|
328
|
+
if (activeBundleId !== undefined) {
|
|
329
|
+
const cycleAt = visiting.indexOf(activeBundleId);
|
|
330
|
+
throw new Error(
|
|
331
|
+
`loadBundleChainDetailed: dependency cycle ${[...visiting.slice(cycleAt), activeBundleId].join(" -> ")}.`,
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
visiting.push(...source.bundleIds);
|
|
335
|
+
const bundleRows = Array.isArray(loaded.manifest.bundles)
|
|
336
|
+
? (loaded.manifest.bundles as Record<string, unknown>[])
|
|
337
|
+
: [];
|
|
338
|
+
const dependencies = bundleRows.flatMap((bundle) =>
|
|
339
|
+
Array.isArray(bundle.depends_on)
|
|
340
|
+
? bundle.depends_on.filter((id): id is string => typeof id === "string")
|
|
341
|
+
: [],
|
|
342
|
+
);
|
|
343
|
+
for (const dependency of dependencies) {
|
|
344
|
+
if (source.bundleIds.includes(dependency)) continue;
|
|
345
|
+
const dependencyPath = options.resolveDependency(dependency, source);
|
|
346
|
+
if (dependencyPath === undefined) {
|
|
347
|
+
throw new Error(
|
|
348
|
+
`loadBundleChainDetailed: dependency '${dependency}' required by '${source.bundleIds.join(", ")}' has no manifest path.`,
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
visit(dependencyPath, dependency);
|
|
352
|
+
}
|
|
353
|
+
visiting.length -= source.bundleIds.length;
|
|
354
|
+
for (const bundleId of source.bundleIds) completed.add(bundleId);
|
|
355
|
+
mergeManifestRowsInto(manifest, loaded.manifest);
|
|
356
|
+
sources.push(source);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
visit(options.rootManifestPath, undefined, options.rootManifestText);
|
|
360
|
+
return { manifest, sources };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export function loadBundleChain(
|
|
364
|
+
dir: string,
|
|
365
|
+
fixturesRoot: string = dirname(dir),
|
|
366
|
+
): Record<string, unknown> {
|
|
367
|
+
return loadBundleChainDetailed({
|
|
368
|
+
rootManifestPath: join(dir, "manifest.toml"),
|
|
369
|
+
resolveDependency: (bundleId) => join(fixturesRoot, bundleId, "manifest.toml"),
|
|
370
|
+
}).manifest;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function stableStringify(value: unknown): string {
|
|
374
|
+
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
|
375
|
+
if (value !== null && typeof value === "object") {
|
|
376
|
+
const entries = Object.entries(value as Record<string, unknown>).sort(([a], [b]) =>
|
|
377
|
+
a.localeCompare(b),
|
|
378
|
+
);
|
|
379
|
+
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
|
|
380
|
+
}
|
|
381
|
+
return JSON.stringify(value);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** Order-insensitive per-kind row comparison. `include` is excluded by
|
|
385
|
+
* default (loader-only/ignored by apply logic, not authored content — never
|
|
386
|
+
* a drift signal); pass `ignoreKeys` to exclude any other top-level keys a
|
|
387
|
+
* caller's manifest shape doesn't want compared. */
|
|
388
|
+
/** Whole-row stringify compare for harness drift (not the product `diffManifests`). */
|
|
389
|
+
export function diffManifestKindRows(
|
|
390
|
+
oldManifest: Record<string, unknown>,
|
|
391
|
+
newManifest: Record<string, unknown>,
|
|
392
|
+
ignoreKeys: readonly string[] = ["include"],
|
|
393
|
+
): string[] {
|
|
394
|
+
const diffs: string[] = [];
|
|
395
|
+
const keys = new Set([...Object.keys(oldManifest), ...Object.keys(newManifest)]);
|
|
396
|
+
for (const ignored of ignoreKeys) keys.delete(ignored);
|
|
397
|
+
for (const key of keys) {
|
|
398
|
+
const a = oldManifest[key];
|
|
399
|
+
const b = newManifest[key];
|
|
400
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
401
|
+
const aSorted = (Array.isArray(a) ? a : []).map(stableStringify).sort();
|
|
402
|
+
const bSorted = (Array.isArray(b) ? b : []).map(stableStringify).sort();
|
|
403
|
+
if (JSON.stringify(aSorted) !== JSON.stringify(bSorted)) {
|
|
404
|
+
const aSet = new Set(aSorted);
|
|
405
|
+
const bSet = new Set(bSorted);
|
|
406
|
+
const onlyOld = aSorted.filter((v) => !bSet.has(v));
|
|
407
|
+
const onlyNew = bSorted.filter((v) => !aSet.has(v));
|
|
408
|
+
diffs.push(
|
|
409
|
+
`kind '${key}': ${onlyOld.length} row(s) only in OLD, ${onlyNew.length} row(s) only in NEW`,
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
} else if (stableStringify(a) !== stableStringify(b)) {
|
|
413
|
+
diffs.push(`field '${key}': OLD=${stableStringify(a)} NEW=${stableStringify(b)}`);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
return diffs;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Supplementary RAW-TEXT check for u64-precision-risk fields (see
|
|
421
|
+
* `restoreBigIntPrecision`'s comment): `semanticEqual`'s `inspectManifest`
|
|
422
|
+
* pass parses BOTH sides through the SAME lossy wasm->JSON hop, so a future
|
|
423
|
+
* precision regression would be invisible to it (both sides would
|
|
424
|
+
* independently round to the SAME wrong value and compare equal). This check
|
|
425
|
+
* never goes through JSON — it greps the exact digit strings from the raw
|
|
426
|
+
* flattened text on both sides.
|
|
427
|
+
*/
|
|
428
|
+
export function diffBigIntFieldsRaw(
|
|
429
|
+
oldText: string,
|
|
430
|
+
newText: string,
|
|
431
|
+
fields: readonly string[] = ["cell_res10", "cell_res7", "cell_res4"],
|
|
432
|
+
): string[] {
|
|
433
|
+
const diffs: string[] = [];
|
|
434
|
+
for (const field of fields) {
|
|
435
|
+
const pattern = new RegExp(`^${field} = (-?\\d+)$`, "gm");
|
|
436
|
+
const oldValues = [...oldText.matchAll(pattern)].map((m) => m[1]).sort();
|
|
437
|
+
const newValues = [...newText.matchAll(pattern)].map((m) => m[1]).sort();
|
|
438
|
+
if (JSON.stringify(oldValues) !== JSON.stringify(newValues)) {
|
|
439
|
+
diffs.push(
|
|
440
|
+
`RAW field '${field}' (u64 precision check): OLD=${JSON.stringify(oldValues)} NEW=${JSON.stringify(newValues)}`,
|
|
441
|
+
);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
return diffs;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Full drift check between two on-disk manifest directories: semantic
|
|
448
|
+
* per-kind diff (order-insensitive) plus the raw u64-precision sweep. */
|
|
449
|
+
export function semanticEqual(
|
|
450
|
+
oldDir: string,
|
|
451
|
+
newDir: string,
|
|
452
|
+
opts: { ignoreKeys?: readonly string[]; bigIntFields?: readonly string[] } = {},
|
|
453
|
+
): string[] {
|
|
454
|
+
const oldText = loadFlattened(oldDir);
|
|
455
|
+
const newText = loadFlattened(newDir);
|
|
456
|
+
const oldManifest = inspectManifest(oldText).manifest as Record<string, unknown>;
|
|
457
|
+
const newManifest = inspectManifest(newText).manifest as Record<string, unknown>;
|
|
458
|
+
return [
|
|
459
|
+
...diffManifestKindRows(oldManifest, newManifest, opts.ignoreKeys),
|
|
460
|
+
...diffBigIntFieldsRaw(oldText, newText, opts.bigIntFields),
|
|
461
|
+
];
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** Run `check` (write outputs to a scratch temp dir, semantic-diff against
|
|
465
|
+
* `committedDir`, clean up) OR write outputs directly to `committedDir` — the
|
|
466
|
+
* shared `--check`/write fork every generator script needs. Returns the
|
|
467
|
+
* drift diagnostics in check mode (empty = clean); returns `null` in write mode. */
|
|
468
|
+
export function checkOrWrite(
|
|
469
|
+
committedDir: string,
|
|
470
|
+
bundle: Record<string, unknown>,
|
|
471
|
+
metadata: Record<string, unknown>,
|
|
472
|
+
includeOrder: readonly string[],
|
|
473
|
+
files: readonly FileEntry[],
|
|
474
|
+
options: { check: boolean } = { check: false },
|
|
475
|
+
): string[] | null {
|
|
476
|
+
if (!options.check) {
|
|
477
|
+
writeOutputs(committedDir, bundle, metadata, includeOrder, files);
|
|
478
|
+
return null;
|
|
479
|
+
}
|
|
480
|
+
const tmpDir = mkdtempSync(join(tmpdir(), "authoring-harness-check-"));
|
|
481
|
+
try {
|
|
482
|
+
writeOutputs(tmpDir, bundle, metadata, includeOrder, files);
|
|
483
|
+
return semanticEqual(committedDir, tmpDir);
|
|
484
|
+
} finally {
|
|
485
|
+
rmSync(tmpDir, { recursive: true, force: true });
|
|
486
|
+
}
|
|
487
|
+
}
|
package/src/browser.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import initWasm, {
|
|
2
|
+
dsl_reference_json,
|
|
3
|
+
manifest_schema_json,
|
|
4
|
+
parse_manifest_toml_to_json,
|
|
5
|
+
render_manifest_json_to_toml,
|
|
6
|
+
validate_manifest_toml,
|
|
7
|
+
} from "@spellkave/validate-wasm/browser";
|
|
8
|
+
import { type Diagnostic, diagnosticsFromJson } from "./diagnostics";
|
|
9
|
+
import { inspectSchemaManifest, type ManifestInspection } from "./inspection";
|
|
10
|
+
import { type LintFinding, lintManifest as lintManifestRules } from "./lint";
|
|
11
|
+
import {
|
|
12
|
+
type SchemaMetadataAttachmentRow,
|
|
13
|
+
type SchemaMetadataNamespaceRow,
|
|
14
|
+
validateMetadataRows,
|
|
15
|
+
} from "./metadata";
|
|
16
|
+
import { patchManifest } from "./patch";
|
|
17
|
+
import type { DslReference, ManifestSchema } from "./reference";
|
|
18
|
+
import { manifestTagPrefixFamilies } from "./tag-prefix-families";
|
|
19
|
+
|
|
20
|
+
export type {
|
|
21
|
+
Diagnostic,
|
|
22
|
+
DiagnosticSeverity,
|
|
23
|
+
DiagnosticSpan,
|
|
24
|
+
} from "./diagnostics";
|
|
25
|
+
export type { ManifestInspection, ManifestSummary } from "./inspection";
|
|
26
|
+
export type { LintFinding, LintRule } from "./lint";
|
|
27
|
+
export type {
|
|
28
|
+
DslArgReference,
|
|
29
|
+
DslOperatorReference,
|
|
30
|
+
DslReference,
|
|
31
|
+
ManifestSchema,
|
|
32
|
+
} from "./reference";
|
|
33
|
+
|
|
34
|
+
export interface BrowserAuthorSdk {
|
|
35
|
+
describeDsl(): DslReference;
|
|
36
|
+
describeManifestSchema(): ManifestSchema;
|
|
37
|
+
inspectManifest(toml: string): ManifestInspection;
|
|
38
|
+
lintManifest(manifest: Record<string, unknown>): LintFinding[];
|
|
39
|
+
patchManifest(
|
|
40
|
+
manifest: Record<string, unknown>,
|
|
41
|
+
op: string,
|
|
42
|
+
payload: Record<string, unknown>,
|
|
43
|
+
): void;
|
|
44
|
+
renderSchemaManifest(manifest: Record<string, unknown>): string;
|
|
45
|
+
renderSchemaManifestJson(manifestJson: string): string;
|
|
46
|
+
validateManifestToml(toml: string): Diagnostic[];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
let wasmReady: Promise<void> | null = null;
|
|
50
|
+
|
|
51
|
+
function ensureWasm(): Promise<void> {
|
|
52
|
+
if (wasmReady === null) {
|
|
53
|
+
wasmReady = initWasm().then(() => undefined);
|
|
54
|
+
}
|
|
55
|
+
return wasmReady;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function describeManifestSchema(): ManifestSchema {
|
|
59
|
+
return JSON.parse(manifest_schema_json()) as ManifestSchema;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function describeDsl(): DslReference {
|
|
63
|
+
return JSON.parse(dsl_reference_json()) as DslReference;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function inspectManifest(toml: string): ManifestInspection {
|
|
67
|
+
return inspectSchemaManifest(
|
|
68
|
+
JSON.parse(parse_manifest_toml_to_json(toml)) as Record<string, unknown>,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function lintManifest(manifest: Record<string, unknown>): LintFinding[] {
|
|
73
|
+
return lintManifestRules(manifest, { refTagFamilies: manifestTagPrefixFamilies(manifest) });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function renderSchemaManifest(manifest: Record<string, unknown>): string {
|
|
77
|
+
return render_manifest_json_to_toml(JSON.stringify(manifest));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function renderSchemaManifestJson(manifestJson: string): string {
|
|
81
|
+
return render_manifest_json_to_toml(manifestJson);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function validateManifestToml(toml: string): Diagnostic[] {
|
|
85
|
+
const diagnostics = diagnosticsFromJson(validate_manifest_toml(toml));
|
|
86
|
+
try {
|
|
87
|
+
const manifest = inspectManifest(toml).manifest as Record<string, unknown>;
|
|
88
|
+
diagnostics.push(
|
|
89
|
+
...validateMetadataRows(
|
|
90
|
+
manifest.metadata_attachments as SchemaMetadataAttachmentRow[] | undefined,
|
|
91
|
+
manifest.metadata_namespaces as SchemaMetadataNamespaceRow[] | undefined,
|
|
92
|
+
),
|
|
93
|
+
);
|
|
94
|
+
} catch {
|
|
95
|
+
// Parse errors are already represented by validate_manifest_toml.
|
|
96
|
+
}
|
|
97
|
+
return diagnostics;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function loadBrowserAuthorSdk(): Promise<BrowserAuthorSdk> {
|
|
101
|
+
await ensureWasm();
|
|
102
|
+
return {
|
|
103
|
+
describeDsl,
|
|
104
|
+
describeManifestSchema,
|
|
105
|
+
inspectManifest,
|
|
106
|
+
lintManifest,
|
|
107
|
+
patchManifest,
|
|
108
|
+
renderSchemaManifest,
|
|
109
|
+
renderSchemaManifestJson,
|
|
110
|
+
validateManifestToml,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export { composeGrant, type GrantInput, type GrantRow, grantDelta } from "./tooling.browser";
|