@vttforge/cli 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.mjs CHANGED
@@ -1,9 +1,117 @@
1
1
  #!/usr/bin/env node
2
- import { f as REMOVED_UTILS, i as runDev, l as runAuditCommand, m as _internal, n as ScaffoldError, o as runBuild, r as runInit, t as VTTFORGE_CLI_VERSION } from "./src-CZnBIzlF.mjs";
2
+ import { f as REMOVED_UTILS, g as definesName, h as bareUsePattern, i as runDev, l as runAuditCommand, m as LEGACY_GLOBALS, n as ScaffoldError, o as runBuild, p as maskComments, r as runInit, t as VTTFORGE_CLI_VERSION, v as _internal } from "./src-CgS7GUiL.mjs";
3
3
  import { existsSync } from "node:fs";
4
- import { join, relative, resolve } from "node:path";
5
- import { readFile, stat, writeFile } from "node:fs/promises";
4
+ import { dirname, join, relative, resolve } from "node:path";
5
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
6
6
  import { defineCommand, runMain } from "citty";
7
+ //#region src/migrate/data-models.ts
8
+ const RICH_TEXT_KEYS = /^(description|biography|bio|notes|details)$/i;
9
+ function fieldFor(key, value, path, notes, indent) {
10
+ const next = `${indent} `;
11
+ if (typeof value === "number") return `new f.NumberField({ required: true, nullable: false${Number.isInteger(value) ? ", integer: true" : ""}, initial: ${value} })`;
12
+ if (typeof value === "boolean") return `new f.BooleanField({ required: true, nullable: false, initial: ${value} })`;
13
+ if (typeof value === "string") {
14
+ const literal = JSON.stringify(value);
15
+ if (RICH_TEXT_KEYS.test(key)) return `new f.HTMLField({ required: true, blank: true, initial: ${literal} })`;
16
+ return `new f.StringField({ required: true, blank: true, initial: ${literal} })`;
17
+ }
18
+ if (Array.isArray(value)) {
19
+ const first = value[0];
20
+ if (first === void 0 || typeof first === "object" && first !== null) {
21
+ if (first === void 0) notes.push(`${path}: an empty array in the template; it is an ArrayField of ObjectField. Name the element's shape if it has one.`);
22
+ return "new f.ArrayField(new f.ObjectField())";
23
+ }
24
+ return `new f.ArrayField(${fieldFor(key, first, `${path}[]`, notes, indent)})`;
25
+ }
26
+ if (value !== null && typeof value === "object") {
27
+ const entries = Object.entries(value);
28
+ if (entries.length === 0) {
29
+ notes.push(`${path}: an empty object in the template; it is an ObjectField. Give it a SchemaField if it has a shape.`);
30
+ return "new f.ObjectField()";
31
+ }
32
+ return `new f.SchemaField({\n${entries.map(([k, v]) => `${next}${safeKey(k)}: ${fieldFor(k, v, `${path}.${k}`, notes, next)},`).join("\n")}\n${indent}})`;
33
+ }
34
+ notes.push(`${path}: null in the template; it is an ObjectField. Pick the real field.`);
35
+ return "new f.ObjectField()";
36
+ }
37
+ function safeKey(key) {
38
+ return /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key);
39
+ }
40
+ function pascal(name) {
41
+ return name.replace(/(^|[^A-Za-z0-9])([a-z0-9])/g, (_m, _s, c) => c.toUpperCase()).replace(/[^A-Za-z0-9]/g, "");
42
+ }
43
+ function camel(name) {
44
+ const p = pascal(name);
45
+ return p.charAt(0).toLowerCase() + p.slice(1);
46
+ }
47
+ function schemaBody(data, path, notes) {
48
+ return Object.entries(data).filter(([k]) => k !== "templates").map(([k, v]) => ` ${safeKey(k)}: ${fieldFor(k, v, `${path}.${k}`, notes, " ")},`).join("\n");
49
+ }
50
+ function header(style) {
51
+ if (style === "sdk") return "import { BaseTypeDataModel, fields } from '@vttforge/core';\n";
52
+ return "";
53
+ }
54
+ function fieldsLine(style) {
55
+ return style === "sdk" ? " const f = fields();" : " const f = foundry.data.fields;";
56
+ }
57
+ function planDataModels(template, { style = "plain", lang = "js", dir = "scripts/data" } = {}) {
58
+ const ext = lang === "ts" ? "ts" : "mjs";
59
+ const files = [];
60
+ const notes = [];
61
+ const documentTypes = {};
62
+ const registrations = [];
63
+ for (const [document, raw] of Object.entries(template)) {
64
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
65
+ const doc = raw;
66
+ const types = doc.types ?? [];
67
+ const templates = doc.templates ?? {};
68
+ const docDir = `${dir}/${document.toLowerCase()}`;
69
+ const fragmentNames = Object.keys(templates);
70
+ if (fragmentNames.length > 0) {
71
+ const fns = fragmentNames.map((name) => {
72
+ const body = schemaBody(templates[name] ?? {}, `${document}.templates.${name}`, notes);
73
+ return `/** The \`${name}\` template, as the types that listed it spread it. */\nexport function ${camel(name)}Fields(f) {\n return {\n${body}\n };\n}`;
74
+ }).join("\n\n");
75
+ const tsHint = lang === "ts" ? "// @ts-nocheck: the field constructors are typed by the runtime, not by this file\n" : "";
76
+ files.push({
77
+ path: `${docDir}/templates.${ext}`,
78
+ source: `${tsHint}/**\n * The \`templates\` of the old template.json for ${document}, each as a\n * function of the fields bag. A type spreads the ones it listed.\n */\n\n${fns}\n`
79
+ });
80
+ }
81
+ documentTypes[document] = {};
82
+ const modelNames = [];
83
+ for (const type of types) {
84
+ const own = doc[type] ?? {};
85
+ const listed = (own.templates ?? []).filter((t) => t !== "base");
86
+ for (const t of listed) if (!(t in templates)) notes.push(`${document}.${type}: lists template "${t}", which template.json does not define; it was skipped.`);
87
+ const spreads = listed.filter((t) => t in templates).map((t) => ` ...${camel(t)}Fields(f),`).join("\n");
88
+ const body = schemaBody(own, `${document}.${type}`, notes);
89
+ const className = `${pascal(type)}Data`;
90
+ const importLine = listed.length ? `import { ${listed.filter((t) => t in templates).map((t) => `${camel(t)}Fields`).join(", ")} } from './templates.${ext === "ts" ? "js" : "mjs"}';\n` : "";
91
+ const schemaFn = `${fieldsLine(style)}\n return {\n${[spreads, body].filter(Boolean).join("\n")}\n };`;
92
+ const classSource = style === "sdk" ? `${header(style)}${importLine}\n/** The \`${type}\` ${document}, as template.json declared it. */\nfunction define${className}Schema() {\n${schemaFn}\n}\n\nexport class ${className} extends BaseTypeDataModel(define${className}Schema) {\n prepareDerivedData() {\n // Derived values go here. Nothing here writes to the database.\n }\n}\n` : `${importLine}\n/** The \`${type}\` ${document}, as template.json declared it. */\nexport class ${className} extends foundry.abstract.TypeDataModel {\n static defineSchema() {\n${schemaFn.replace(/^/gm, " ")}\n }\n\n prepareDerivedData() {\n // Derived values go here. Nothing here writes to the database.\n }\n}\n`;
93
+ files.push({
94
+ path: `${docDir}/${type}-data.${ext}`,
95
+ source: classSource
96
+ });
97
+ const meta = {};
98
+ const html = (doc.htmlFields ?? []).filter((k) => k in own || listed.some((t) => k in (templates[t] ?? {})));
99
+ if (html.length) meta.htmlFields = html;
100
+ documentTypes[document][type] = meta;
101
+ modelNames.push(`${type}: ${className}`);
102
+ registrations.push(`import { ${className} } from './${docDir.replace(/^scripts\//, "")}/${type}-data.${ext === "ts" ? "js" : "mjs"}';`);
103
+ }
104
+ if (types.length) registrations.push(style === "sdk" ? `// registerSystem({ ${document === "Actor" ? "actorDataModels" : document === "Item" ? "itemDataModels" : `${camel(document)}DataModels`}: { ${modelNames.join(", ")} } })` : `// Hooks.once('init', () => Object.assign(CONFIG.${document}.dataModels, { ${modelNames.join(", ")} }));`);
105
+ }
106
+ notes.push("When every type has a model, delete template.json: while it exists, Foundry resets each listed type's documentTypes entry on every start.");
107
+ return {
108
+ files,
109
+ documentTypes,
110
+ registration: registrations.join("\n"),
111
+ notes
112
+ };
113
+ }
114
+ //#endregion
7
115
  //#region src/migrate/transforms.ts
8
116
  /**
9
117
  * The rewrites `vttforge migrate` applies to a v13 source file.
@@ -15,9 +123,9 @@ import { defineCommand, runMain } from "citty";
15
123
  *
16
124
  * Text-based, like the audit rules they mirror (`VTTF-AUDIT-011` to `016`).
17
125
  * The patterns are short and mechanical, and a syntax tree would not make
18
- * `'-=key'` easier to find. The cost is that a match inside a string or a
19
- * comment is rewritten too; the preview exists so that is seen before it is
20
- * written.
126
+ * `'-=key'` easier to find. Comments are left alone: every match has to
127
+ * start in code. A match inside a string literal is still rewritten, which
128
+ * is what the preview is for.
21
129
  */
22
130
  function lineAt(source, index) {
23
131
  let line = 1;
@@ -36,9 +144,11 @@ function lineText(source, index) {
36
144
  */
37
145
  function rewrite(source, pattern, replacement, rule) {
38
146
  const changes = [];
147
+ const code = maskComments(source);
39
148
  return {
40
149
  output: source.replace(pattern, (match, ...rest) => {
41
150
  const offset = rest.find((r) => typeof r === "number") ?? 0;
151
+ if (code[offset] === "\0") return match;
42
152
  const groups = rest.filter((r) => typeof r === "string");
43
153
  const after = typeof replacement === "string" ? replacement : replacement(match, ...groups);
44
154
  if (after !== match) changes.push({
@@ -89,39 +199,85 @@ const removedGlobals = (source) => {
89
199
  };
90
200
  const clamped = rewrite(utils.output, /\bMath\.clamped\s*\(/g, "Math.clamp(", "removed-globals");
91
201
  const notes = [];
92
- for (const match of clamped.output.matchAll(/\bgame\.template\b/g)) notes.push({
93
- line: lineAt(clamped.output, match.index ?? 0),
94
- rule: "removed-globals",
95
- message: "`game.template` is gone. Read type defaults from `game.model`, or the type list from the package's `documentTypes`."
96
- });
202
+ const code = maskComments(clamped.output);
203
+ for (const match of clamped.output.matchAll(/\bgame\.template\b/g)) {
204
+ if (code[match.index ?? 0] === "\0") continue;
205
+ notes.push({
206
+ line: lineAt(clamped.output, match.index ?? 0),
207
+ rule: "removed-globals",
208
+ message: "`game.template` is gone. Read type defaults from `game.model`, or the type list from the package's `documentTypes`."
209
+ });
210
+ }
97
211
  return {
98
212
  ...merge(utils, clamped),
99
213
  notes
100
214
  };
101
215
  };
102
216
  /**
217
+ * Bare v13 global aliases → their `foundry.*` path: `renderTemplate(` →
218
+ * `foundry.applications.handlebars.renderTemplate(`, `extends ActorSheet` →
219
+ * `extends foundry.appv1.sheets.ActorSheet`. Same object, no removal date.
220
+ * A name the file declares or imports, an object key, a property, and a
221
+ * word inside a string or comment are left alone.
222
+ */
223
+ const namespacedGlobals = (source) => {
224
+ const changes = [];
225
+ const code = maskComments(source, { strings: true });
226
+ const edits = [];
227
+ for (const [name, path] of Object.entries(LEGACY_GLOBALS)) {
228
+ if (definesName(code, name)) continue;
229
+ for (const match of code.matchAll(bareUsePattern(name))) {
230
+ const start = match.index ?? 0;
231
+ edits.push({
232
+ start,
233
+ end: start + name.length,
234
+ text: path,
235
+ name
236
+ });
237
+ }
238
+ }
239
+ let output = source;
240
+ for (const edit of edits.sort((a, b) => b.start - a.start)) output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
241
+ for (const edit of edits.sort((a, b) => a.start - b.start)) changes.push({
242
+ line: lineAt(source, edit.start),
243
+ before: edit.name,
244
+ after: edit.text,
245
+ rule: "namespaced-globals"
246
+ });
247
+ return {
248
+ output,
249
+ changes,
250
+ notes: []
251
+ };
252
+ };
253
+ /**
103
254
  * `'-=key': null` → `key: _del`; `'==key': value` → `key: _replace(value)`;
104
255
  * `performDeletions` → `applyOperators`; `objectsEqual` → `equals`.
256
+ *
257
+ * The key may be a template literal with `${...}` segments in the prefix,
258
+ * which is how a flag deletion is usually written: `` [`flags.${id}.-=old`] ``.
105
259
  */
106
260
  const dataOperators = (source) => {
107
- const deletions = rewrite(source, /(['"])((?:[\w$]+\.)*)-=([\w$.]+)\1\s*:\s*null\b/g, (_m, quote, prefix, key) => `${quote}${prefix}${key}${quote}: _del`, "data-operators");
261
+ const deletions = rewrite(source, /(['"`])((?:[\w$]+\.|\$\{[^}]*\}\.)*)-=([\w$.]+)\1(\]?)\s*:\s*null\b/g, (_m, quote, prefix, key, bracket) => `${quote}${prefix}${key}${quote}${bracket}: _del`, "data-operators");
108
262
  const replacements = wrapReplacementValues(deletions.output);
109
263
  const flags = rewrite(replacements.output, /\bperformDeletions\s*:/g, "applyOperators:", "data-operators");
110
264
  return merge(deletions, replacements, flags, rewrite(flags.output, /\bfoundry\.utils\.objectsEqual\s*\(/g, "foundry.utils.equals(", "data-operators"));
111
265
  };
112
266
  function wrapReplacementValues(source) {
113
267
  const changes = [];
114
- const pattern = /(['"])((?:[\w$]+\.)*)==([\w$.]+)\1\s*:\s*/g;
268
+ const pattern = /(['"`])((?:[\w$]+\.|\$\{[^}]*\}\.)*)==([\w$.]+)\1(\]?)\s*:\s*/g;
269
+ const code = maskComments(source);
115
270
  let out = "";
116
271
  let cursor = 0;
117
272
  for (const match of source.matchAll(pattern)) {
118
273
  const start = match.index ?? 0;
274
+ if (code[start] === "\0") continue;
119
275
  const valueStart = start + match[0].length;
120
276
  const valueEnd = scanValueEnd(source, valueStart);
121
277
  if (valueEnd === -1) continue;
122
278
  const value = source.slice(valueStart, valueEnd).trimEnd();
123
- const [, quote = "\"", prefix = "", key = ""] = match;
124
- const after = `${quote}${prefix}${key}${quote}: _replace(${value})`;
279
+ const [, quote = "\"", prefix = "", key = "", bracket = ""] = match;
280
+ const after = `${quote}${prefix}${key}${quote}${bracket}: _replace(${value})`;
125
281
  out += source.slice(cursor, start) + after;
126
282
  cursor = valueStart + value.length;
127
283
  changes.push({
@@ -175,41 +331,103 @@ const ROLL_MODE_CONSTANTS = {
175
331
  *
176
332
  * `"roll"` meant "whatever the user's chat dropdown says", which is what an
177
333
  * absent `messageMode` means now, so it becomes `undefined`. A value that is
178
- * an expression is left for the reader, with a note.
334
+ * an expression is wrapped in `Roll._mapLegacyRollMode(...)`, which maps a
335
+ * v13 name and passes a v14 key or `undefined` through unchanged, so the
336
+ * wrap is safe whatever the expression yields.
179
337
  */
180
338
  const rollMode = (source) => {
181
- const notes = [];
182
339
  const option = rewrite(source, /\brollMode\s*:\s*(['"])(publicroll|gmroll|blindroll|selfroll|roll)\1/g, (_m, quote, value) => value === "roll" ? "messageMode: undefined" : `messageMode: ${quote}${ROLL_MODE_VALUES[value]}${quote}`, "roll-mode");
183
- const key = rewrite(option.output, /\brollMode\s*:/g, (m) => m.replace("rollMode", "messageMode"), "roll-mode");
184
- for (const change of key.changes) notes.push({
185
- line: change.line,
186
- rule: "roll-mode",
187
- message: "The value is an expression. If it can be a v13 mode name, wrap it: `Roll._mapLegacyRollMode(value)`."
188
- });
189
- const setting = rewrite(key.output, /(['"])core\1\s*,\s*(['"])rollMode\2/g, (_m, q1, q2) => `${q1}core${q1}, ${q2}messageMode${q2}`, "roll-mode");
340
+ const expressions = wrapRollModeExpressions(option.output);
341
+ const setting = rewrite(expressions.output, /(['"])core\1\s*,\s*(['"])rollMode\2/g, (_m, q1, q2) => `${q1}core${q1}, ${q2}messageMode${q2}`, "roll-mode");
190
342
  const modes = rewrite(setting.output, /\bCONFIG\.Dice\.rollModes\b/g, "CONFIG.ChatMessage.modes", "roll-mode");
343
+ return merge(option, expressions, setting, modes, rewrite(modes.output, /\bCONST\.DICE_ROLL_MODES\.(PUBLIC|PRIVATE|BLIND|SELF)\b/g, (_m, name) => `"${ROLL_MODE_CONSTANTS[name]}"`, "roll-mode"));
344
+ };
345
+ /** `rollMode: <expr>` → `messageMode: Roll._mapLegacyRollMode(<expr>)`. */
346
+ function wrapRollModeExpressions(source) {
347
+ const changes = [];
348
+ const pattern = /\brollMode\s*:\s*/g;
349
+ const code = maskComments(source);
350
+ let out = "";
351
+ let cursor = 0;
352
+ for (const match of source.matchAll(pattern)) {
353
+ const start = match.index ?? 0;
354
+ if (code[start] === "\0") continue;
355
+ const valueStart = start + match[0].length;
356
+ const valueEnd = scanValueEnd(source, valueStart);
357
+ if (valueEnd === -1) continue;
358
+ const value = source.slice(valueStart, valueEnd).trimEnd();
359
+ const after = `messageMode: Roll._mapLegacyRollMode(${value})`;
360
+ out += source.slice(cursor, start) + after;
361
+ cursor = valueStart + value.length;
362
+ changes.push({
363
+ line: lineAt(source, start),
364
+ before: source.slice(start, cursor),
365
+ after,
366
+ rule: "roll-mode"
367
+ });
368
+ }
369
+ out += source.slice(cursor);
370
+ return {
371
+ output: out,
372
+ changes,
373
+ notes: []
374
+ };
375
+ }
376
+ /**
377
+ * Hooks that changed shape: noted, not rewritten. `renderChatMessage` is
378
+ * removed in v15 and its replacement hands an element where it handed a
379
+ * jQuery object, so the handler body is the reader's to change.
380
+ */
381
+ const hookNotes = (source) => {
382
+ const notes = [];
383
+ const code = maskComments(source);
384
+ for (const match of source.matchAll(/Hooks\.(?:on|once)\(\s*['"]renderChatMessage['"]/g)) {
385
+ if (code[match.index ?? 0] === "\0") continue;
386
+ notes.push({
387
+ line: lineAt(source, match.index ?? 0),
388
+ rule: "hooks",
389
+ message: "`renderChatMessage` is removed in v15. Listen to `renderChatMessageHTML(message, html, context)`; `html` is the element, so `html.find(x)` becomes `html.querySelector(x)`."
390
+ });
391
+ }
191
392
  return {
192
- ...merge(option, key, setting, modes, rewrite(modes.output, /\bCONST\.DICE_ROLL_MODES\.(PUBLIC|PRIVATE|BLIND|SELF)\b/g, (_m, name) => `"${ROLL_MODE_CONSTANTS[name]}"`, "roll-mode")),
393
+ output: source,
394
+ changes: [],
193
395
  notes
194
396
  };
195
397
  };
196
398
  /**
197
399
  * Context-menu entries and header controls: `name` → `label`, `condition` →
198
- * `visible`, `callback` → `onClick`. Only inside an object literal that has a
199
- * `callback` and an `icon` or `condition`, so an unrelated `name:` elsewhere
200
- * is not renamed. The callback's parameters change too, from `(li)` to
201
- * `(event, target)`, and that is noted rather than rewritten.
400
+ * `visible`, `callback` → `onClick`.
401
+ *
402
+ * Only an object literal whose own keys include `callback` and `name` or
403
+ * `condition` is an entry. A Dialog button has `icon`, `label` and
404
+ * `callback`, and keeps `callback` on v14, so `icon` is not a signal; and
405
+ * only the literal's own keys count, so a class body or a `buttons` bag that
406
+ * happens to contain an entry is not itself treated as one. The callback's
407
+ * parameters change too, from `(li)` to `(event, target)`, and that is noted
408
+ * rather than rewritten.
202
409
  */
203
410
  const contextMenuKeys = (source) => {
204
411
  const changes = [];
205
412
  const notes = [];
206
- let output = source;
207
- const literals = objectLiterals(source);
208
- for (const { start, end } of literals.reverse()) {
209
- const body = output.slice(start, end);
210
- if (!/\bcallback\s*:/.test(body) || !/\b(?:icon|condition)\s*:/.test(body)) continue;
211
- const renamed = body.replace(/(^|[{,\s])name\s*:/g, "$1label:").replace(/(^|[{,\s])condition\s*:/g, "$1visible:").replace(/(^|[{,\s])callback\s*:/g, "$1onClick:");
212
- if (renamed === body) continue;
413
+ const RENAME = {
414
+ name: "label",
415
+ condition: "visible",
416
+ callback: "onClick"
417
+ };
418
+ const edits = [];
419
+ for (const { start, end } of objectLiterals(source).sort((a, b) => b.start - a.start)) {
420
+ const keys = ownKeys(source, start, end);
421
+ const names = new Set(keys.map((k) => k.name));
422
+ if (!names.has("callback") || !(names.has("name") || names.has("condition"))) continue;
423
+ for (const key of keys) {
424
+ const to = RENAME[key.name];
425
+ if (to !== void 0) edits.push({
426
+ start: key.offset,
427
+ end: key.offset + key.name.length,
428
+ text: to
429
+ });
430
+ }
213
431
  changes.push({
214
432
  line: lineAt(source, start),
215
433
  before: lineText(source, start),
@@ -221,14 +439,82 @@ const contextMenuKeys = (source) => {
221
439
  rule: "context-menu-keys",
222
440
  message: "`onClick` receives `(event, target)` where `callback` received the element. Check the parameter list."
223
441
  });
224
- output = output.slice(0, start) + renamed + output.slice(end);
225
442
  }
443
+ let output = source;
444
+ for (const edit of edits.sort((a, b) => b.start - a.start)) output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
226
445
  return {
227
446
  output,
228
447
  changes,
229
448
  notes
230
449
  };
231
450
  };
451
+ /**
452
+ * The keys an object literal declares itself, with the offset of each name.
453
+ *
454
+ * Walks the span between the braces at depth one: a key is an identifier
455
+ * followed by `:` where a property may start, which is right after the
456
+ * opening brace or after a comma at that depth. Nested literals, arrays,
457
+ * calls, strings and comments are stepped over.
458
+ */
459
+ function ownKeys(source, start, end) {
460
+ const keys = [];
461
+ let depth = 0;
462
+ let quote = null;
463
+ let expectKey = true;
464
+ for (let i = start; i < end; i += 1) {
465
+ const ch = source[i] ?? "";
466
+ const next = source[i + 1] ?? "";
467
+ if (quote) {
468
+ if (ch === "\\") i += 1;
469
+ else if (ch === quote) quote = null;
470
+ continue;
471
+ }
472
+ if (ch === "/" && next === "/") {
473
+ const nl = source.indexOf("\n", i);
474
+ i = nl === -1 ? end : nl;
475
+ continue;
476
+ }
477
+ if (ch === "/" && next === "*") {
478
+ const close = source.indexOf("*/", i + 2);
479
+ i = close === -1 ? end : close + 1;
480
+ continue;
481
+ }
482
+ if (ch === "\"" || ch === "'" || ch === "`") {
483
+ quote = ch;
484
+ expectKey = false;
485
+ continue;
486
+ }
487
+ if (ch === "{" || ch === "[" || ch === "(") {
488
+ depth += 1;
489
+ expectKey = depth === 1 && ch === "{";
490
+ continue;
491
+ }
492
+ if (ch === "}" || ch === "]" || ch === ")") {
493
+ depth -= 1;
494
+ expectKey = false;
495
+ continue;
496
+ }
497
+ if (depth !== 1) continue;
498
+ if (ch === ",") {
499
+ expectKey = true;
500
+ continue;
501
+ }
502
+ if (/\s/.test(ch)) continue;
503
+ if (expectKey && /[A-Za-z_$]/.test(ch)) {
504
+ let j = i;
505
+ while (j < end && /[\w$]/.test(source[j] ?? "")) j += 1;
506
+ let k = j;
507
+ while (k < end && /\s/.test(source[k] ?? "")) k += 1;
508
+ if (source[k] === ":") keys.push({
509
+ name: source.slice(i, j),
510
+ offset: i
511
+ });
512
+ i = j - 1;
513
+ }
514
+ expectKey = false;
515
+ }
516
+ return keys;
517
+ }
232
518
  /** Every `{ ... }` span in the text, outermost first, strings and comments skipped. */
233
519
  function objectLiterals(source) {
234
520
  const spans = [];
@@ -283,8 +569,11 @@ const statusEffectsAssignment = (source) => {
283
569
  const changes = [];
284
570
  let output = "";
285
571
  let cursor = 0;
286
- for (const match of source.matchAll(/\bCONFIG\.statusEffects\s*=(?!=)\s*/g)) {
572
+ const pattern = /\bCONFIG\.statusEffects\s*=(?!=)\s*/g;
573
+ const code = maskComments(source);
574
+ for (const match of source.matchAll(pattern)) {
287
575
  const start = match.index ?? 0;
576
+ if (code[start] === "\0") continue;
288
577
  const valueStart = start + match[0].length;
289
578
  const end = scanStatementEnd(source, valueStart);
290
579
  if (end === -1) continue;
@@ -352,13 +641,15 @@ const activeEffectModes = (source) => {
352
641
  /** The transforms, in the order they run. */
353
642
  const SOURCE_TRANSFORMS = [
354
643
  ["removed-globals", removedGlobals],
644
+ ["namespaced-globals", namespacedGlobals],
355
645
  ["data-operators", dataOperators],
356
646
  ["roll-mode", rollMode],
357
647
  ["context-menu-keys", contextMenuKeys],
358
648
  ["legacy-transferral", legacyTransferral],
359
649
  ["unregister-core-sheets", unregisterCoreSheets],
360
650
  ["status-effects", statusEffectsAssignment],
361
- ["active-effect-modes", activeEffectModes]
651
+ ["active-effect-modes", activeEffectModes],
652
+ ["hooks", hookNotes]
362
653
  ];
363
654
  function transformSource(source) {
364
655
  return pipe(source, SOURCE_TRANSFORMS.map(([, t]) => t));
@@ -366,33 +657,73 @@ function transformSource(source) {
366
657
  /**
367
658
  * The manifest: `type` declared, `compatibility` raised to 14 where it is
368
659
  * lower. Returns `null` when nothing needed to change.
660
+ *
661
+ * Edited as text, not re-serialised: a manifest carries its author's
662
+ * indentation, key order and one-line arrays, and a diff that reformats the
663
+ * whole file to add one key is a diff nobody merges. `type` goes on the line
664
+ * after `id`, with that line's indentation; the compatibility values are
665
+ * replaced in place.
369
666
  */
370
667
  function transformManifest(raw, kind) {
371
668
  const parsed = JSON.parse(raw);
372
669
  const changes = [];
373
670
  const notes = [];
671
+ let output = raw;
374
672
  if (parsed.type !== kind) {
375
- parsed.type = kind;
376
- changes.push({
377
- line: 1,
378
- before: "(no \"type\")",
379
- after: `"type": "${kind}"`,
380
- rule: "manifest"
381
- });
673
+ const typeKey = topLevelKey(output, "type");
674
+ if (typeKey) {
675
+ output = `${output.slice(0, typeKey.valueStart)}"${kind}"${output.slice(typeKey.valueEnd)}`;
676
+ changes.push({
677
+ line: lineAt(raw, typeKey.keyStart),
678
+ before: raw.slice(typeKey.keyStart, typeKey.valueEnd).trim(),
679
+ after: `"type": "${kind}"`,
680
+ rule: "manifest"
681
+ });
682
+ } else {
683
+ const idKey = topLevelKey(output, "id");
684
+ if (idKey) {
685
+ const lineStart = output.lastIndexOf("\n", idKey.keyStart) + 1;
686
+ const indent = output.slice(lineStart, idKey.keyStart);
687
+ const after = output.indexOf("\n", idKey.valueEnd);
688
+ const insertAt = after === -1 ? output.length : after;
689
+ output = `${!/,\s*$/.test(output.slice(idKey.valueEnd, insertAt)) ? `${output.slice(0, idKey.valueEnd)},${output.slice(idKey.valueEnd, insertAt)}` : output.slice(0, insertAt)}\n${indent}"type": "${kind}",${output.slice(insertAt)}`;
690
+ changes.push({
691
+ line: lineAt(raw, idKey.keyStart) + 1,
692
+ before: "(no \"type\")",
693
+ after: `"type": "${kind}"`,
694
+ rule: "manifest"
695
+ });
696
+ } else notes.push({
697
+ line: 1,
698
+ rule: "manifest",
699
+ message: `Add \`"type": "${kind}"\` next to "id"; the key could not be placed by hand.`
700
+ });
701
+ }
382
702
  }
383
703
  const compatibility = parsed.compatibility ?? {};
384
704
  for (const field of ["minimum", "verified"]) {
385
705
  const current = compatibility[field];
386
706
  const major = Number.parseInt(String(current ?? "0"), 10);
387
- if (!Number.isFinite(major) || major < 14) {
388
- compatibility[field] = "14";
707
+ if (Number.isFinite(major) && major >= 14) continue;
708
+ const block = topLevelKey(output, "compatibility");
709
+ const inner = block ? topLevelKey(output.slice(block.valueStart, block.valueEnd), field) : null;
710
+ if (block && inner && current !== void 0) {
711
+ const valueStart = block.valueStart + inner.valueStart;
712
+ const valueEnd = block.valueStart + inner.valueEnd;
713
+ output = `${output.slice(0, valueStart)}"14"${output.slice(valueEnd)}`;
389
714
  changes.push({
390
- line: 1,
391
- before: `compatibility.${field}: ${JSON.stringify(current ?? null)}`,
715
+ line: lineAt(output, block.valueStart + inner.keyStart),
716
+ before: `compatibility.${field}: ${JSON.stringify(current)}`,
392
717
  after: `compatibility.${field}: "14"`,
393
718
  rule: "manifest"
394
719
  });
720
+ continue;
395
721
  }
722
+ notes.push({
723
+ line: 1,
724
+ rule: "manifest",
725
+ message: `Set compatibility.${field} to "14"; it is ${JSON.stringify(current ?? null)} and could not be edited in place.`
726
+ });
396
727
  }
397
728
  const maximum = compatibility.maximum;
398
729
  if (maximum !== void 0 && Number.parseInt(String(maximum), 10) < 14) notes.push({
@@ -405,25 +736,86 @@ function transformManifest(raw, kind) {
405
736
  rule: "manifest",
406
737
  message: "gridDistance / gridUnits are ignored on v14. Move them into `\"grid\": { \"type\", \"distance\", \"units\", \"diagonals\" }`."
407
738
  });
408
- parsed.compatibility = compatibility;
409
739
  if (changes.length === 0) return notes.length ? {
410
740
  output: raw,
411
741
  changes,
412
742
  notes
413
743
  } : null;
414
- const ordered = {};
415
- for (const [key, value] of Object.entries(parsed)) {
416
- if (key === "type") continue;
417
- ordered[key] = value;
418
- if (key === "id") ordered.type = parsed.type;
419
- }
420
- if (!("type" in ordered)) ordered.type = parsed.type;
744
+ JSON.parse(output);
421
745
  return {
422
- output: `${JSON.stringify(ordered, null, 2)}\n`,
746
+ output,
423
747
  changes,
424
748
  notes
425
749
  };
426
750
  }
751
+ /**
752
+ * Where a key of the root object sits in the JSON text: the start of the
753
+ * quoted key, and the span of its value. Only depth one counts, so a
754
+ * `"type"` inside `relationships.systems[]` is not the manifest's `type`.
755
+ */
756
+ function topLevelKey(json, key) {
757
+ let depth = 0;
758
+ let i = 0;
759
+ const skipString = (from) => {
760
+ let j = from + 1;
761
+ for (; j < json.length; j += 1) if (json[j] === "\\") j += 1;
762
+ else if (json[j] === "\"") return j + 1;
763
+ return j;
764
+ };
765
+ const skipValue = (from) => {
766
+ let j = from;
767
+ while (j < json.length && /\s/.test(json[j] ?? "")) j += 1;
768
+ const ch = json[j] ?? "";
769
+ if (ch === "\"") return skipString(j);
770
+ if (ch === "{" || ch === "[") {
771
+ let d = 0;
772
+ for (let k = j; k < json.length; k += 1) {
773
+ const c = json[k] ?? "";
774
+ if (c === "\"") k = skipString(k) - 1;
775
+ else if (c === "{" || c === "[") d += 1;
776
+ else if (c === "}" || c === "]") {
777
+ d -= 1;
778
+ if (d === 0) return k + 1;
779
+ }
780
+ }
781
+ return json.length;
782
+ }
783
+ while (j < json.length && !/[,}\]\s]/.test(json[j] ?? "")) j += 1;
784
+ return j;
785
+ };
786
+ while (i < json.length) {
787
+ const ch = json[i] ?? "";
788
+ if (ch === "\"") {
789
+ const end = skipString(i);
790
+ if (depth === 1) {
791
+ const name = json.slice(i + 1, end - 1);
792
+ let k = end;
793
+ while (k < json.length && /\s/.test(json[k] ?? "")) k += 1;
794
+ if (json[k] === ":") {
795
+ const valueStart = (() => {
796
+ let v = k + 1;
797
+ while (v < json.length && /\s/.test(json[v] ?? "")) v += 1;
798
+ return v;
799
+ })();
800
+ const valueEnd = skipValue(k + 1);
801
+ if (name === key) return {
802
+ keyStart: i,
803
+ valueStart,
804
+ valueEnd
805
+ };
806
+ i = valueEnd;
807
+ continue;
808
+ }
809
+ }
810
+ i = end;
811
+ continue;
812
+ }
813
+ if (ch === "{" || ch === "[") depth += 1;
814
+ else if (ch === "}" || ch === "]") depth -= 1;
815
+ i += 1;
816
+ }
817
+ return null;
818
+ }
427
819
  //#endregion
428
820
  //#region src/migrate/index.ts
429
821
  /**
@@ -475,7 +867,7 @@ async function runMigrate(options) {
475
867
  if (write && result.output !== source) await writeFile(path, result.output, "utf8");
476
868
  }
477
869
  files.sort((a, b) => a.file.localeCompare(b.file));
478
- return {
870
+ const report = {
479
871
  cwd,
480
872
  files,
481
873
  written: write,
@@ -485,21 +877,65 @@ async function runMigrate(options) {
485
877
  notes: files.reduce((n, f) => n + f.notes.length, 0)
486
878
  }
487
879
  };
880
+ if (options.dataModels) {
881
+ const templatePath = join(cwd, "template.json");
882
+ if (!existsSync(templatePath)) report.dataModels = {
883
+ files: [],
884
+ documentTypes: {},
885
+ registration: "",
886
+ notes: ["No template.json here; nothing to generate."]
887
+ };
888
+ else {
889
+ const plan = planDataModels(JSON.parse(await readFile(templatePath, "utf8")), {
890
+ style: options.style ?? "plain",
891
+ lang: options.lang ?? "js"
892
+ });
893
+ const written = [];
894
+ for (const file of plan.files) {
895
+ const target = join(cwd, file.path);
896
+ if (existsSync(target)) {
897
+ plan.notes.unshift(`${file.path} exists and was left alone.`);
898
+ continue;
899
+ }
900
+ if (write) {
901
+ await mkdir(dirname(target), { recursive: true });
902
+ await writeFile(target, file.source, "utf8");
903
+ }
904
+ written.push(file.path);
905
+ }
906
+ report.dataModels = {
907
+ files: written,
908
+ documentTypes: plan.documentTypes,
909
+ registration: plan.registration,
910
+ notes: plan.notes
911
+ };
912
+ }
913
+ }
914
+ return report;
488
915
  }
489
916
  /** The report as text: one block per file, edits then notes. */
490
917
  function formatMigrateReport(report) {
491
918
  const lines = [];
492
- if (report.files.length === 0) {
919
+ if (report.files.length === 0 && !report.dataModels) {
493
920
  lines.push("Nothing to migrate. The project already reads as v14.");
494
921
  return `${lines.join("\n")}\n`;
495
922
  }
496
- lines.push(report.written ? `Rewrote ${report.counts.changes} place(s) in ${report.counts.files} file(s).` : `Would rewrite ${report.counts.changes} place(s) in ${report.counts.files} file(s). Run again with --write to apply.`);
923
+ if (report.files.length === 0) lines.push("Nothing to rewrite in the source or the manifest.");
924
+ else lines.push(report.written ? `Rewrote ${report.counts.changes} place(s) in ${report.counts.files} file(s).` : `Would rewrite ${report.counts.changes} place(s) in ${report.counts.files} file(s). Run again with --write to apply.`);
497
925
  for (const file of report.files) {
498
926
  lines.push("", `${file.file}`);
499
927
  for (const change of file.changes) lines.push(` ${change.line}: ${oneLine(change.before)}`, ` ${" ".repeat(String(change.line).length)} → ${oneLine(change.after)}`);
500
928
  for (const note of file.notes) lines.push(` ${note.line}: needs a decision: ${note.message}`);
501
929
  }
502
930
  if (report.counts.notes > 0) lines.push("", `${report.counts.notes} place(s) need a decision. Run \`vttforge audit\` after editing them.`);
931
+ if (report.dataModels) {
932
+ const dm = report.dataModels;
933
+ lines.push("", report.written ? `Wrote ${dm.files.length} data model file(s) from template.json:` : `Would write ${dm.files.length} data model file(s) from template.json:`);
934
+ for (const f of dm.files) lines.push(` ${f}`);
935
+ if (Object.keys(dm.documentTypes).length > 0) lines.push("", "Declare the types in the manifest:", ` "documentTypes": ${JSON.stringify(dm.documentTypes)}`);
936
+ if (dm.registration) lines.push("", "Register the models at init:", ...dm.registration.split("\n").map((l) => ` ${l}`));
937
+ for (const n of dm.notes) lines.push(` needs a decision: ${n}`);
938
+ }
503
939
  return `${lines.join("\n")}\n`;
504
940
  }
505
941
  function oneLine(text) {
@@ -522,7 +958,10 @@ async function runMigrateCommand(options = {}) {
522
958
  });
523
959
  const report = await runMigrate({
524
960
  cwd,
525
- write: options.write === true
961
+ write: options.write === true,
962
+ dataModels: options.dataModels === true,
963
+ style: options.style,
964
+ lang: options.lang
526
965
  });
527
966
  out(options.json ? `${JSON.stringify(report, null, 2)}\n` : formatMigrateReport(report));
528
967
  return {
@@ -723,6 +1162,21 @@ const migrate = defineCommand({
723
1162
  type: "boolean",
724
1163
  default: false,
725
1164
  description: "Emit the report as JSON"
1165
+ },
1166
+ "data-models": {
1167
+ type: "boolean",
1168
+ default: false,
1169
+ description: "Also generate a data model per template.json type (template.json is deprecated since v14)"
1170
+ },
1171
+ style: {
1172
+ type: "string",
1173
+ default: "plain",
1174
+ description: "For --data-models: \"plain\" Foundry classes, or \"sdk\" classes on @vttforge/core"
1175
+ },
1176
+ lang: {
1177
+ type: "string",
1178
+ default: "js",
1179
+ description: "For --data-models: \"js\" writes .mjs, \"ts\" writes .ts"
726
1180
  }
727
1181
  },
728
1182
  async run({ args }) {
@@ -730,7 +1184,10 @@ const migrate = defineCommand({
730
1184
  const { exitCode } = await runMigrateCommand({
731
1185
  cwd: args.path ? String(args.path) : void 0,
732
1186
  write: Boolean(args.write),
733
- json: Boolean(args.json)
1187
+ json: Boolean(args.json),
1188
+ dataModels: Boolean(args["data-models"]),
1189
+ style: String(args.style) === "sdk" ? "sdk" : "plain",
1190
+ lang: String(args.lang) === "ts" ? "ts" : "js"
734
1191
  });
735
1192
  process.exitCode = exitCode;
736
1193
  } catch (error) {