@vttforge/cli 0.9.0 → 0.10.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @vttforge/cli
2
2
 
3
+ ## 0.10.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 60d3222: `vttforge audit` rules 011 to 016 and `vttforge migrate` no longer match inside comments. A call quoted in a JSDoc block or a `// TODO` line was a finding, and `migrate` rewrote it.
8
+
9
+ ## 0.10.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 11afe13: `vttforge migrate` rewrites a v13 system or module for v14: bare `mergeObject`-style globals, `-=` and `==` update keys, `rollMode`, context-menu and header-control keys, numeric Active Effect modes, whole-array `CONFIG.statusEffects` assignment, `legacyTransferral`, the core-sheet unregister lines, and the manifest's `type` and `compatibility`. It reports by default and writes with `--write`; what it cannot decide it reports as needing a decision.
14
+
15
+ ### Patch Changes
16
+
17
+ - c7a9920: The templates pin `@vttforge/core` at `^0.15.0`, the release that carries `@SystemSetting`.
18
+
3
19
  ## 0.9.0
4
20
 
5
21
  ### Minor Changes
package/README.md CHANGED
@@ -14,6 +14,7 @@ vttforge init <name> [--type system|module] [--lang ts|js] [--id] [--title] [--d
14
14
  vttforge dev [--foundry-data <path>] [--port <n>]
15
15
  vttforge build
16
16
  vttforge audit [dir] [--json] [--strict]
17
+ vttforge migrate [dir] [--write] [--json]
17
18
  ```
18
19
 
19
20
  **`init`** writes a runnable system or module into `<name>/` from one of four templates (`system-ts`, `system-js`, `module-ts`, `module-js`). It asks for what you did not pass, or takes defaults with `--yes`, so it works in CI. It detects the package manager that invoked it (`pnpm`, `npm`, `bun`, `yarn`), installs, and runs `git init`.
@@ -24,6 +25,8 @@ vttforge audit [dir] [--json] [--strict]
24
25
 
25
26
  **`audit`** checks the manifest, the source and the templates against the v14 breakages that fail quietly: the `flags.hotReload` shape, the removed grid fields, the v12 `styles` shape, `HTMLField`/`FilePathField` paths missing from `documentTypes`, `TypeDataModel` without `prepareBaseData`, a bad `_addDataFieldMigrations` override, token attributes that do not point at a `{ value, max }` field, a sheet template that opens a `<form>` the sheet already is, a declared subtype with no name in any language file, a `template.json` that erases the metadata `system.json` declares for the same type, and the v13 code v14 broke or deprecated: bare `mergeObject`-style globals, `-=` update keys, `rollMode`, whole-array `CONFIG.statusEffects` assignment, `legacyTransferral`, numeric Active Effect modes. `--json` for machines; `--strict` exits non-zero on any finding rather than only on HIGH.
26
27
 
28
+ **`migrate`** rewrites a v13 project for v14: the removed globals, `-=` keys, `rollMode`, context-menu keys, numeric effect modes, whole-array `CONFIG.statusEffects`, `legacyTransferral`, the core-sheet unregister lines, and the manifest's `type` and `compatibility`. It reports by default and writes with `--write`; what it will not decide it lists as needing one.
29
+
27
30
  ## As a library
28
31
 
29
32
  Every command is exported for tooling built on top: `runInit`, `runDev`, `runBuild`, `runAudit`, `emitReleaseZip`, `resolveFoundryDataDir`, `readManifest`, and the scaffold helpers.
package/dist/bin.mjs CHANGED
@@ -1,6 +1,553 @@
1
1
  #!/usr/bin/env node
2
- import { i as runDev, l as runAuditCommand, n as ScaffoldError, o as runBuild, r as runInit, t as VTTFORGE_CLI_VERSION } from "./src-BAHJHuJ7.mjs";
2
+ import { f as REMOVED_UTILS, h as _internal, i as runDev, l as runAuditCommand, n as ScaffoldError, o as runBuild, p as maskComments, r as runInit, t as VTTFORGE_CLI_VERSION } from "./src-Bof8_ypF.mjs";
3
+ import { existsSync } from "node:fs";
4
+ import { join, relative, resolve } from "node:path";
5
+ import { readFile, stat, writeFile } from "node:fs/promises";
3
6
  import { defineCommand, runMain } from "citty";
7
+ //#region src/migrate/transforms.ts
8
+ /**
9
+ * The rewrites `vttforge migrate` applies to a v13 source file.
10
+ *
11
+ * Each transform is a pure function over the file's text. It returns the new
12
+ * text, one `Change` per edit it made, and one `Note` per thing it saw and
13
+ * would not touch: a rewrite that needs a decision (which page a `game.template`
14
+ * read should become) is reported, not guessed.
15
+ *
16
+ * Text-based, like the audit rules they mirror (`VTTF-AUDIT-011` to `016`).
17
+ * The patterns are short and mechanical, and a syntax tree would not make
18
+ * `'-=key'` easier to find. Comments are left alone: every match has to
19
+ * start in code. A match inside a string literal is still rewritten, which
20
+ * is what the preview is for.
21
+ */
22
+ function lineAt(source, index) {
23
+ let line = 1;
24
+ for (let i = 0; i < index && i < source.length; i += 1) if (source[i] === "\n") line += 1;
25
+ return line;
26
+ }
27
+ /** The whole line an index sits on, trimmed, for the report. */
28
+ function lineText(source, index) {
29
+ const start = source.lastIndexOf("\n", index - 1) + 1;
30
+ const end = source.indexOf("\n", index);
31
+ return source.slice(start, end === -1 ? source.length : end).trim();
32
+ }
33
+ /**
34
+ * Replace every match, recording one change per match against the original
35
+ * text. The replacement may be a string or a function, like `String#replace`.
36
+ */
37
+ function rewrite(source, pattern, replacement, rule) {
38
+ const changes = [];
39
+ const code = maskComments(source);
40
+ return {
41
+ output: source.replace(pattern, (match, ...rest) => {
42
+ const offset = rest.find((r) => typeof r === "number") ?? 0;
43
+ if (code[offset] === "\0") return match;
44
+ const groups = rest.filter((r) => typeof r === "string");
45
+ const after = typeof replacement === "string" ? replacement : replacement(match, ...groups);
46
+ if (after !== match) changes.push({
47
+ line: lineAt(source, offset),
48
+ before: match,
49
+ after,
50
+ rule
51
+ });
52
+ return after;
53
+ }),
54
+ changes,
55
+ notes: []
56
+ };
57
+ }
58
+ function merge(...results) {
59
+ return {
60
+ output: results.at(-1)?.output ?? "",
61
+ changes: results.flatMap((r) => r.changes),
62
+ notes: results.flatMap((r) => r.notes)
63
+ };
64
+ }
65
+ /** Run transforms in sequence, each on the previous one's output. */
66
+ function pipe(source, transforms) {
67
+ const results = [];
68
+ let current = source;
69
+ for (const transform of transforms) {
70
+ const result = transform(current);
71
+ results.push(result);
72
+ current = result.output;
73
+ }
74
+ return merge(...results);
75
+ }
76
+ /**
77
+ * Bare v12 utility globals → `foundry.utils.*`; `Math.clamped` → `Math.clamp`.
78
+ *
79
+ * A name the file declares or imports itself is left alone, the same way
80
+ * `VTTF-AUDIT-011` leaves it alone. `game.template` is reported, not
81
+ * rewritten: whether it becomes `game.model` or a `documentTypes` read depends
82
+ * on what was read from it.
83
+ */
84
+ const removedGlobals = (source) => {
85
+ const own = new Set(REMOVED_UTILS.filter((name) => new RegExp(`(?:function\\s+${name}\\b|(?:const|let|var)\\s+${name}\\b|import[^;]*\\b${name}\\b|\\b${name}\\s*\\([^)]*\\)\\s*\\{)`).test(source)));
86
+ const names = REMOVED_UTILS.filter((name) => !own.has(name));
87
+ const utils = names.length ? rewrite(source, new RegExp(`(?<![\\w$.])(${names.join("|")})\\s*\\(`, "g"), (_m, name) => `foundry.utils.${name}(`, "removed-globals") : {
88
+ output: source,
89
+ changes: [],
90
+ notes: []
91
+ };
92
+ const clamped = rewrite(utils.output, /\bMath\.clamped\s*\(/g, "Math.clamp(", "removed-globals");
93
+ const notes = [];
94
+ const code = maskComments(clamped.output);
95
+ for (const match of clamped.output.matchAll(/\bgame\.template\b/g)) {
96
+ if (code[match.index ?? 0] === "\0") continue;
97
+ notes.push({
98
+ line: lineAt(clamped.output, match.index ?? 0),
99
+ rule: "removed-globals",
100
+ message: "`game.template` is gone. Read type defaults from `game.model`, or the type list from the package's `documentTypes`."
101
+ });
102
+ }
103
+ return {
104
+ ...merge(utils, clamped),
105
+ notes
106
+ };
107
+ };
108
+ /**
109
+ * `'-=key': null` → `key: _del`; `'==key': value` → `key: _replace(value)`;
110
+ * `performDeletions` → `applyOperators`; `objectsEqual` → `equals`.
111
+ */
112
+ const dataOperators = (source) => {
113
+ const deletions = rewrite(source, /(['"])((?:[\w$]+\.)*)-=([\w$.]+)\1\s*:\s*null\b/g, (_m, quote, prefix, key) => `${quote}${prefix}${key}${quote}: _del`, "data-operators");
114
+ const replacements = wrapReplacementValues(deletions.output);
115
+ const flags = rewrite(replacements.output, /\bperformDeletions\s*:/g, "applyOperators:", "data-operators");
116
+ return merge(deletions, replacements, flags, rewrite(flags.output, /\bfoundry\.utils\.objectsEqual\s*\(/g, "foundry.utils.equals(", "data-operators"));
117
+ };
118
+ function wrapReplacementValues(source) {
119
+ const changes = [];
120
+ const pattern = /(['"])((?:[\w$]+\.)*)==([\w$.]+)\1\s*:\s*/g;
121
+ const code = maskComments(source);
122
+ let out = "";
123
+ let cursor = 0;
124
+ for (const match of source.matchAll(pattern)) {
125
+ const start = match.index ?? 0;
126
+ if (code[start] === "\0") continue;
127
+ const valueStart = start + match[0].length;
128
+ const valueEnd = scanValueEnd(source, valueStart);
129
+ if (valueEnd === -1) continue;
130
+ const value = source.slice(valueStart, valueEnd).trimEnd();
131
+ const [, quote = "\"", prefix = "", key = ""] = match;
132
+ const after = `${quote}${prefix}${key}${quote}: _replace(${value})`;
133
+ out += source.slice(cursor, start) + after;
134
+ cursor = valueStart + value.length;
135
+ changes.push({
136
+ line: lineAt(source, start),
137
+ before: source.slice(start, cursor),
138
+ after,
139
+ rule: "data-operators"
140
+ });
141
+ }
142
+ out += source.slice(cursor);
143
+ return {
144
+ output: out,
145
+ changes,
146
+ notes: []
147
+ };
148
+ }
149
+ /** Index just past a value that starts at `from`: the next `,` or `}` at depth zero. */
150
+ function scanValueEnd(source, from) {
151
+ let depth = 0;
152
+ let quote = null;
153
+ for (let i = from; i < source.length; i += 1) {
154
+ const ch = source[i] ?? "";
155
+ if (quote) {
156
+ if (ch === "\\") i += 1;
157
+ else if (ch === quote) quote = null;
158
+ continue;
159
+ }
160
+ if (ch === "\"" || ch === "'" || ch === "`") quote = ch;
161
+ else if (ch === "{" || ch === "[" || ch === "(") depth += 1;
162
+ else if (ch === "}" || ch === "]" || ch === ")") {
163
+ if (depth === 0) return i;
164
+ depth -= 1;
165
+ } else if (ch === "," && depth === 0) return i;
166
+ }
167
+ return -1;
168
+ }
169
+ const ROLL_MODE_VALUES = {
170
+ publicroll: "public",
171
+ gmroll: "gm",
172
+ blindroll: "blind",
173
+ selfroll: "self"
174
+ };
175
+ const ROLL_MODE_CONSTANTS = {
176
+ PUBLIC: "public",
177
+ PRIVATE: "gm",
178
+ BLIND: "blind",
179
+ SELF: "self"
180
+ };
181
+ /**
182
+ * `rollMode` → `messageMode`, with the value mapped when it is a literal.
183
+ *
184
+ * `"roll"` meant "whatever the user's chat dropdown says", which is what an
185
+ * absent `messageMode` means now, so it becomes `undefined`. A value that is
186
+ * an expression is left for the reader, with a note.
187
+ */
188
+ const rollMode = (source) => {
189
+ const notes = [];
190
+ 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");
191
+ const key = rewrite(option.output, /\brollMode\s*:/g, (m) => m.replace("rollMode", "messageMode"), "roll-mode");
192
+ for (const change of key.changes) notes.push({
193
+ line: change.line,
194
+ rule: "roll-mode",
195
+ message: "The value is an expression. If it can be a v13 mode name, wrap it: `Roll._mapLegacyRollMode(value)`."
196
+ });
197
+ const setting = rewrite(key.output, /(['"])core\1\s*,\s*(['"])rollMode\2/g, (_m, q1, q2) => `${q1}core${q1}, ${q2}messageMode${q2}`, "roll-mode");
198
+ const modes = rewrite(setting.output, /\bCONFIG\.Dice\.rollModes\b/g, "CONFIG.ChatMessage.modes", "roll-mode");
199
+ return {
200
+ ...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")),
201
+ notes
202
+ };
203
+ };
204
+ /**
205
+ * Context-menu entries and header controls: `name` → `label`, `condition` →
206
+ * `visible`, `callback` → `onClick`. Only inside an object literal that has a
207
+ * `callback` and an `icon` or `condition`, so an unrelated `name:` elsewhere
208
+ * is not renamed. The callback's parameters change too, from `(li)` to
209
+ * `(event, target)`, and that is noted rather than rewritten.
210
+ */
211
+ const contextMenuKeys = (source) => {
212
+ const changes = [];
213
+ const notes = [];
214
+ let output = source;
215
+ const literals = objectLiterals(source);
216
+ for (const { start, end } of literals.reverse()) {
217
+ const body = output.slice(start, end);
218
+ if (!/\bcallback\s*:/.test(body) || !/\b(?:icon|condition)\s*:/.test(body)) continue;
219
+ const bodyCode = maskComments(body);
220
+ const KEYS = {
221
+ name: "label",
222
+ condition: "visible",
223
+ callback: "onClick"
224
+ };
225
+ const renamed = body.replace(/(^|[{,\s])(name|condition|callback)(\s*:)/g, (m, lead, key, colon, offset) => bodyCode[offset + lead.length] === "\0" ? m : `${lead}${KEYS[key]}${colon}`);
226
+ if (renamed === body) continue;
227
+ changes.push({
228
+ line: lineAt(source, start),
229
+ before: lineText(source, start),
230
+ after: "label / visible / onClick keys",
231
+ rule: "context-menu-keys"
232
+ });
233
+ notes.push({
234
+ line: lineAt(source, start),
235
+ rule: "context-menu-keys",
236
+ message: "`onClick` receives `(event, target)` where `callback` received the element. Check the parameter list."
237
+ });
238
+ output = output.slice(0, start) + renamed + output.slice(end);
239
+ }
240
+ return {
241
+ output,
242
+ changes,
243
+ notes
244
+ };
245
+ };
246
+ /** Every `{ ... }` span in the text, outermost first, strings and comments skipped. */
247
+ function objectLiterals(source) {
248
+ const spans = [];
249
+ const stack = [];
250
+ let quote = null;
251
+ for (let i = 0; i < source.length; i += 1) {
252
+ const ch = source[i] ?? "";
253
+ const next = source[i + 1] ?? "";
254
+ if (quote) {
255
+ if (ch === "\\") i += 1;
256
+ else if (ch === quote) quote = null;
257
+ continue;
258
+ }
259
+ if (ch === "/" && next === "/") {
260
+ i = source.indexOf("\n", i);
261
+ if (i === -1) break;
262
+ continue;
263
+ }
264
+ if (ch === "/" && next === "*") {
265
+ const close = source.indexOf("*/", i + 2);
266
+ i = close === -1 ? source.length : close + 1;
267
+ continue;
268
+ }
269
+ if (ch === "\"" || ch === "'" || ch === "`") quote = ch;
270
+ else if (ch === "{") stack.push(i);
271
+ else if (ch === "}") {
272
+ const start = stack.pop();
273
+ if (start !== void 0) spans.push({
274
+ start,
275
+ end: i + 1
276
+ });
277
+ }
278
+ }
279
+ return spans.sort((a, b) => a.start - b.start);
280
+ }
281
+ /**
282
+ * `legacyTransferral` is gone: the assignment, and the `activeEffect`
283
+ * option `registerSystem` used to take for it.
284
+ */
285
+ const legacyTransferral = (source) => {
286
+ const statement = rewrite(source, /^[ \t]*CONFIG\.ActiveEffect\.legacyTransferral\s*=[^\n]*\n?/gm, "", "legacy-transferral");
287
+ const option = rewrite(statement.output, /^[ \t]*activeEffect\s*:\s*\{\s*legacyTransferral\s*:\s*(?:true|false)\s*,?\s*\}\s*,?[ \t]*\n?/gm, "", "legacy-transferral");
288
+ return merge(statement, option, rewrite(option.output, /^[ \t]*legacyTransferral\s*:\s*(?:true|false)\s*,?[ \t]*\n?/gm, "", "legacy-transferral"));
289
+ };
290
+ /** v14 registers no core Actor or Item sheet, so there is nothing to unregister. */
291
+ const unregisterCoreSheets = (source) => rewrite(source, /^[ \t]*(?:foundry\.documents\.collections\.)?(?:Actors|Items)\.unregisterSheet\(\s*['"]core['"][^\n]*\n?/gm, "", "unregister-core-sheets");
292
+ /**
293
+ * `CONFIG.statusEffects = list;` → add each entry by id. The setter empties
294
+ * the collection first, which wipes what other packages added.
295
+ */
296
+ const statusEffectsAssignment = (source) => {
297
+ const changes = [];
298
+ let output = "";
299
+ let cursor = 0;
300
+ const pattern = /\bCONFIG\.statusEffects\s*=(?!=)\s*/g;
301
+ const code = maskComments(source);
302
+ for (const match of source.matchAll(pattern)) {
303
+ const start = match.index ?? 0;
304
+ if (code[start] === "\0") continue;
305
+ const valueStart = start + match[0].length;
306
+ const end = scanStatementEnd(source, valueStart);
307
+ if (end === -1) continue;
308
+ const after = `for (const effect of ${source.slice(valueStart, end).trim()}) CONFIG.statusEffects[effect.id] = effect;`;
309
+ output += source.slice(cursor, start) + after;
310
+ cursor = end + 1;
311
+ changes.push({
312
+ line: lineAt(source, start),
313
+ before: source.slice(start, cursor).trim(),
314
+ after,
315
+ rule: "status-effects"
316
+ });
317
+ }
318
+ output += source.slice(cursor);
319
+ return {
320
+ output,
321
+ changes,
322
+ notes: []
323
+ };
324
+ };
325
+ /** Index of the `;` that ends a statement starting at `from`, brackets balanced. */
326
+ function scanStatementEnd(source, from) {
327
+ let depth = 0;
328
+ let quote = null;
329
+ for (let i = from; i < source.length; i += 1) {
330
+ const ch = source[i] ?? "";
331
+ if (quote) {
332
+ if (ch === "\\") i += 1;
333
+ else if (ch === quote) quote = null;
334
+ continue;
335
+ }
336
+ if (ch === "\"" || ch === "'" || ch === "`") quote = ch;
337
+ else if (ch === "{" || ch === "[" || ch === "(") depth += 1;
338
+ else if (ch === "}" || ch === "]" || ch === ")") depth -= 1;
339
+ else if (ch === ";" && depth === 0) return i;
340
+ }
341
+ return -1;
342
+ }
343
+ const EFFECT_MODES = {
344
+ CUSTOM: "custom",
345
+ MULTIPLY: "multiply",
346
+ ADD: "add",
347
+ DOWNGRADE: "downgrade",
348
+ UPGRADE: "upgrade",
349
+ OVERRIDE: "override"
350
+ };
351
+ /**
352
+ * `mode: CONST.ACTIVE_EFFECT_MODES.ADD` → `type: "add"`. A root-level
353
+ * `changes` array on an effect now lives under `system.changes`; that move
354
+ * depends on where the data is built, so it is noted.
355
+ */
356
+ const activeEffectModes = (source) => {
357
+ const typed = rewrite(source, /\bmode\s*:\s*CONST\.ACTIVE_EFFECT_MODES\.(CUSTOM|MULTIPLY|ADD|DOWNGRADE|UPGRADE|OVERRIDE)\b/g, (_m, name) => `type: "${EFFECT_MODES[name]}"`, "active-effect-modes");
358
+ const bare = rewrite(typed.output, /\bCONST\.ACTIVE_EFFECT_MODES\.(CUSTOM|MULTIPLY|ADD|DOWNGRADE|UPGRADE|OVERRIDE)\b/g, (_m, name) => `"${EFFECT_MODES[name]}"`, "active-effect-modes");
359
+ const notes = typed.changes.map((c) => ({
360
+ line: c.line,
361
+ rule: "active-effect-modes",
362
+ message: "The change now belongs under `system.changes`, not a root-level `changes` array."
363
+ }));
364
+ return {
365
+ ...merge(typed, bare),
366
+ notes
367
+ };
368
+ };
369
+ /** The transforms, in the order they run. */
370
+ const SOURCE_TRANSFORMS = [
371
+ ["removed-globals", removedGlobals],
372
+ ["data-operators", dataOperators],
373
+ ["roll-mode", rollMode],
374
+ ["context-menu-keys", contextMenuKeys],
375
+ ["legacy-transferral", legacyTransferral],
376
+ ["unregister-core-sheets", unregisterCoreSheets],
377
+ ["status-effects", statusEffectsAssignment],
378
+ ["active-effect-modes", activeEffectModes]
379
+ ];
380
+ function transformSource(source) {
381
+ return pipe(source, SOURCE_TRANSFORMS.map(([, t]) => t));
382
+ }
383
+ /**
384
+ * The manifest: `type` declared, `compatibility` raised to 14 where it is
385
+ * lower. Returns `null` when nothing needed to change.
386
+ */
387
+ function transformManifest(raw, kind) {
388
+ const parsed = JSON.parse(raw);
389
+ const changes = [];
390
+ const notes = [];
391
+ if (parsed.type !== kind) {
392
+ parsed.type = kind;
393
+ changes.push({
394
+ line: 1,
395
+ before: "(no \"type\")",
396
+ after: `"type": "${kind}"`,
397
+ rule: "manifest"
398
+ });
399
+ }
400
+ const compatibility = parsed.compatibility ?? {};
401
+ for (const field of ["minimum", "verified"]) {
402
+ const current = compatibility[field];
403
+ const major = Number.parseInt(String(current ?? "0"), 10);
404
+ if (!Number.isFinite(major) || major < 14) {
405
+ compatibility[field] = "14";
406
+ changes.push({
407
+ line: 1,
408
+ before: `compatibility.${field}: ${JSON.stringify(current ?? null)}`,
409
+ after: `compatibility.${field}: "14"`,
410
+ rule: "manifest"
411
+ });
412
+ }
413
+ }
414
+ const maximum = compatibility.maximum;
415
+ if (maximum !== void 0 && Number.parseInt(String(maximum), 10) < 14) notes.push({
416
+ line: 1,
417
+ rule: "manifest",
418
+ message: `compatibility.maximum is ${JSON.stringify(maximum)}, which keeps the package off v14. Raise it or remove it.`
419
+ });
420
+ if ("gridDistance" in parsed || "gridUnits" in parsed) notes.push({
421
+ line: 1,
422
+ rule: "manifest",
423
+ message: "gridDistance / gridUnits are ignored on v14. Move them into `\"grid\": { \"type\", \"distance\", \"units\", \"diagonals\" }`."
424
+ });
425
+ parsed.compatibility = compatibility;
426
+ if (changes.length === 0) return notes.length ? {
427
+ output: raw,
428
+ changes,
429
+ notes
430
+ } : null;
431
+ const ordered = {};
432
+ for (const [key, value] of Object.entries(parsed)) {
433
+ if (key === "type") continue;
434
+ ordered[key] = value;
435
+ if (key === "id") ordered.type = parsed.type;
436
+ }
437
+ if (!("type" in ordered)) ordered.type = parsed.type;
438
+ return {
439
+ output: `${JSON.stringify(ordered, null, 2)}\n`,
440
+ changes,
441
+ notes
442
+ };
443
+ }
444
+ //#endregion
445
+ //#region src/migrate/index.ts
446
+ /**
447
+ * `vttforge migrate`: rewrite a v13 project for v14.
448
+ *
449
+ * Walks the same files the audit walks, applies the transforms, and reports
450
+ * every edit and every thing it saw and would not decide for you. Nothing is
451
+ * written unless asked: the preview is the default, because a text rewrite
452
+ * that touched a string literal is something to see before it lands.
453
+ */
454
+ async function runMigrate(options) {
455
+ const { cwd } = options;
456
+ const write = options.write === true;
457
+ if (!existsSync(cwd) || !(await stat(cwd)).isDirectory()) throw new Error(`Migrate target is not a directory: ${cwd}`);
458
+ const files = [];
459
+ for (const [name, kind] of [["system.json", "system"], ["module.json", "module"]]) {
460
+ const path = join(cwd, name);
461
+ if (!existsSync(path)) continue;
462
+ let raw;
463
+ try {
464
+ raw = await readFile(path, "utf8");
465
+ JSON.parse(raw);
466
+ } catch {
467
+ continue;
468
+ }
469
+ const result = transformManifest(raw, kind);
470
+ if (result === null) continue;
471
+ files.push({
472
+ file: name,
473
+ changes: result.changes,
474
+ notes: result.notes
475
+ });
476
+ if (write && result.changes.length > 0) await writeFile(path, result.output, "utf8");
477
+ }
478
+ for await (const path of _internal.walkSourceFiles(cwd)) {
479
+ let source;
480
+ try {
481
+ source = await readFile(path, "utf8");
482
+ } catch {
483
+ continue;
484
+ }
485
+ const result = transformSource(source);
486
+ if (result.changes.length === 0 && result.notes.length === 0) continue;
487
+ files.push({
488
+ file: relative(cwd, path),
489
+ changes: result.changes,
490
+ notes: result.notes
491
+ });
492
+ if (write && result.output !== source) await writeFile(path, result.output, "utf8");
493
+ }
494
+ files.sort((a, b) => a.file.localeCompare(b.file));
495
+ return {
496
+ cwd,
497
+ files,
498
+ written: write,
499
+ counts: {
500
+ files: files.length,
501
+ changes: files.reduce((n, f) => n + f.changes.length, 0),
502
+ notes: files.reduce((n, f) => n + f.notes.length, 0)
503
+ }
504
+ };
505
+ }
506
+ /** The report as text: one block per file, edits then notes. */
507
+ function formatMigrateReport(report) {
508
+ const lines = [];
509
+ if (report.files.length === 0) {
510
+ lines.push("Nothing to migrate. The project already reads as v14.");
511
+ return `${lines.join("\n")}\n`;
512
+ }
513
+ 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.`);
514
+ for (const file of report.files) {
515
+ lines.push("", `${file.file}`);
516
+ for (const change of file.changes) lines.push(` ${change.line}: ${oneLine(change.before)}`, ` ${" ".repeat(String(change.line).length)} → ${oneLine(change.after)}`);
517
+ for (const note of file.notes) lines.push(` ${note.line}: needs a decision: ${note.message}`);
518
+ }
519
+ if (report.counts.notes > 0) lines.push("", `${report.counts.notes} place(s) need a decision. Run \`vttforge audit\` after editing them.`);
520
+ return `${lines.join("\n")}\n`;
521
+ }
522
+ function oneLine(text) {
523
+ const flat = text.replace(/\s+/g, " ").trim();
524
+ return flat.length > 100 ? `${flat.slice(0, 97)}...` : flat;
525
+ }
526
+ //#endregion
527
+ //#region src/commands/migrate.ts
528
+ /**
529
+ * `vttforge migrate`: the CLI surface over the v13 → v14 rewrite.
530
+ *
531
+ * Exit codes:
532
+ * 0: ran, whether or not anything changed
533
+ * 1: the target is not a directory
534
+ */
535
+ async function runMigrateCommand(options = {}) {
536
+ const cwd = resolve(options.cwd ?? process.cwd());
537
+ const out = options.out ?? ((chunk) => {
538
+ process.stdout.write(chunk);
539
+ });
540
+ const report = await runMigrate({
541
+ cwd,
542
+ write: options.write === true
543
+ });
544
+ out(options.json ? `${JSON.stringify(report, null, 2)}\n` : formatMigrateReport(report));
545
+ return {
546
+ report,
547
+ exitCode: 0
548
+ };
549
+ }
550
+ //#endregion
4
551
  //#region src/cli.ts
5
552
  /**
6
553
  * vttforge command tree.
@@ -173,17 +720,54 @@ const audit = defineCommand({
173
720
  }
174
721
  }
175
722
  });
723
+ const migrate = defineCommand({
724
+ meta: {
725
+ name: "migrate",
726
+ description: "Rewrite a v13 system or module for Foundry v14 (preview by default)"
727
+ },
728
+ args: {
729
+ path: {
730
+ type: "positional",
731
+ description: "Project root to rewrite (defaults to the current directory)",
732
+ required: false
733
+ },
734
+ write: {
735
+ type: "boolean",
736
+ default: false,
737
+ description: "Write the edits. Without it, the command only reports what it would change"
738
+ },
739
+ json: {
740
+ type: "boolean",
741
+ default: false,
742
+ description: "Emit the report as JSON"
743
+ }
744
+ },
745
+ async run({ args }) {
746
+ try {
747
+ const { exitCode } = await runMigrateCommand({
748
+ cwd: args.path ? String(args.path) : void 0,
749
+ write: Boolean(args.write),
750
+ json: Boolean(args.json)
751
+ });
752
+ process.exitCode = exitCode;
753
+ } catch (error) {
754
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
755
+ process.exitCode = 1;
756
+ }
757
+ }
758
+ });
176
759
  const main = defineCommand({
177
760
  meta: {
178
761
  name: "vttforge",
179
762
  version: VTTFORGE_CLI_VERSION,
180
- description: "VTTForge CLI: scaffold, dev, build and audit for Foundry v14+ systems and modules"
763
+ description: "VTTForge CLI: scaffold, dev, build, audit and migrate for Foundry v14+ systems and modules"
181
764
  },
182
765
  subCommands: {
183
766
  init,
184
767
  dev,
185
768
  build,
186
- audit
769
+ audit,
770
+ migrate
187
771
  }
188
772
  });
189
773
  //#endregion