@vttforge/cli 0.12.0 → 0.13.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,10 @@
1
1
  #!/usr/bin/env node
2
- import { _ as definesName, a as runDev, g as bareUsePattern, h as LEGACY_GLOBALS, i as runInit, m as maskComments, n as runLintCommand, p as REMOVED_UTILS, r as ScaffoldError, s as runBuild, t as VTTFORGE_CLI_VERSION, u as runAuditCommand, y as _internal } from "./src-CzzrhCN-.mjs";
2
+ import { _ as definesName, a as runDev, g as bareUsePattern, h as LEGACY_GLOBALS, i as runInit, m as maskComments, n as runLintCommand, p as REMOVED_UTILS, r as ScaffoldError, s as runBuild, t as VTTFORGE_CLI_VERSION, u as runAuditCommand, x as runReleaseRules, y as _internal } from "./src-5a2deycw.mjs";
3
3
  import { existsSync } from "node:fs";
4
4
  import { dirname, join, relative, resolve } from "node:path";
5
- import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
5
+ import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
6
6
  import { defineCommand, runMain } from "citty";
7
+ import { parse } from "@babel/parser";
7
8
  //#region src/migrate/data-models.ts
8
9
  const RICH_TEXT_KEYS = /^(description|biography|bio|notes|details)$/i;
9
10
  function fieldFor(key, value, path, notes, indent) {
@@ -37,11 +38,11 @@ function fieldFor(key, value, path, notes, indent) {
37
38
  function safeKey(key) {
38
39
  return /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key);
39
40
  }
40
- function pascal(name) {
41
+ function pascal$1(name) {
41
42
  return name.replace(/(^|[^A-Za-z0-9])([a-z0-9])/g, (_m, _s, c) => c.toUpperCase()).replace(/[^A-Za-z0-9]/g, "");
42
43
  }
43
- function camel(name) {
44
- const p = pascal(name);
44
+ function camel$1(name) {
45
+ const p = pascal$1(name);
45
46
  return p.charAt(0).toLowerCase() + p.slice(1);
46
47
  }
47
48
  function schemaBody(data, path, notes) {
@@ -70,7 +71,7 @@ function planDataModels(template, { style = "plain", lang = "js", dir = "scripts
70
71
  if (fragmentNames.length > 0) {
71
72
  const fns = fragmentNames.map((name) => {
72
73
  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
+ return `/** The \`${name}\` template, as the types that listed it spread it. */\nexport function ${camel$1(name)}Fields(f) {\n return {\n${body}\n };\n}`;
74
75
  }).join("\n\n");
75
76
  const tsHint = lang === "ts" ? "// @ts-nocheck: the field constructors are typed by the runtime, not by this file\n" : "";
76
77
  files.push({
@@ -84,10 +85,10 @@ function planDataModels(template, { style = "plain", lang = "js", dir = "scripts
84
85
  const own = doc[type] ?? {};
85
86
  const listed = (own.templates ?? []).filter((t) => t !== "base");
86
87
  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 spreads = listed.filter((t) => t in templates).map((t) => ` ...${camel$1(t)}Fields(f),`).join("\n");
88
89
  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` : "";
90
+ const className = `${pascal$1(type)}Data`;
91
+ const importLine = listed.length ? `import { ${listed.filter((t) => t in templates).map((t) => `${camel$1(t)}Fields`).join(", ")} } from './templates.${ext === "ts" ? "js" : "mjs"}';\n` : "";
91
92
  const schemaFn = `${fieldsLine(style)}\n return {\n${[spreads, body].filter(Boolean).join("\n")}\n };`;
92
93
  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
94
  files.push({
@@ -101,7 +102,7 @@ function planDataModels(template, { style = "plain", lang = "js", dir = "scripts
101
102
  modelNames.push(`${type}: ${className}`);
102
103
  registrations.push(`import { ${className} } from './${docDir.replace(/^scripts\//, "")}/${type}-data.${ext === "ts" ? "js" : "mjs"}';`);
103
104
  }
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
+ if (types.length) registrations.push(style === "sdk" ? `// registerSystem({ ${document === "Actor" ? "actorDataModels" : document === "Item" ? "itemDataModels" : `${camel$1(document)}DataModels`}: { ${modelNames.join(", ")} } })` : `// Hooks.once('init', () => Object.assign(CONFIG.${document}.dataModels, { ${modelNames.join(", ")} }));`);
105
106
  }
106
107
  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
108
  return {
@@ -112,6 +113,1090 @@ function planDataModels(template, { style = "plain", lang = "js", dir = "scripts
112
113
  };
113
114
  }
114
115
  //#endregion
116
+ //#region src/migrate/sheet-templates.ts
117
+ /**
118
+ * One opening tag: the name, the attribute run, and the self-closing slash.
119
+ * Exactly three capture groups — `editTemplate` reads the replacer's `offset`
120
+ * as the fourth argument, so a fourth group would shift every reported line.
121
+ * A fresh regex per call: a shared global one carries `lastIndex` between
122
+ * `readTabIds`, `elementRange` and `String#replace`.
123
+ */
124
+ const tagRe = () => /<([a-zA-Z][\w-]*)((?:\s*\{\{[^{}]*\}\}|\s+[^\s=>/{]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?|(?<=\}\})[^\s=>/{]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?)*)\s*(\/?)>/g;
125
+ /** The value of one attribute in a tag's attribute run, or null when absent. */
126
+ function attr(attrs, name) {
127
+ const m = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`).exec(attrs);
128
+ return m ? m[1] ?? m[2] ?? m[3] ?? "" : null;
129
+ }
130
+ function hasClass(attrs, cls) {
131
+ return (attr(attrs, "class") ?? "").split(/\s+/).includes(cls);
132
+ }
133
+ /** Only `.class` and `#id` selectors match; anything else stays for `_onRender`. */
134
+ function matches(attrs, selector) {
135
+ const m = /^([.#])([A-Za-z_][\w-]*)/.exec(selector.trim());
136
+ if (!m) return false;
137
+ const [, kind = "", name = ""] = m;
138
+ if (!name) return false;
139
+ return kind === "." ? hasClass(attrs, name) : attr(attrs, "id") === name;
140
+ }
141
+ function lineOf(text, index) {
142
+ let n = 1;
143
+ for (let i = 0; i < index; i += 1) if (text[i] === "\n") n += 1;
144
+ return n;
145
+ }
146
+ /**
147
+ * Index range of the first element a selector opens, through its closing tag.
148
+ * Depth-aware on the tag name, so a nested `<div>` inside the match does not
149
+ * end it early.
150
+ */
151
+ function elementRange(template, selector) {
152
+ for (const m of template.matchAll(tagRe())) {
153
+ const [whole, name, attrs = ""] = m;
154
+ if (m.index === void 0 || !name || !matches(attrs, selector)) continue;
155
+ const open = new RegExp(`<${name}\\b`, "g");
156
+ const close = new RegExp(`</${name}\\s*>`, "g");
157
+ let depth = 1;
158
+ let pos = m.index + whole.length;
159
+ while (depth > 0) {
160
+ open.lastIndex = pos;
161
+ close.lastIndex = pos;
162
+ const o = open.exec(template);
163
+ const c = close.exec(template);
164
+ if (!c) return [m.index, template.length];
165
+ if (o && o.index < c.index) {
166
+ depth += 1;
167
+ pos = o.index + o[0].length;
168
+ } else {
169
+ depth -= 1;
170
+ pos = c.index + c[0].length;
171
+ }
172
+ }
173
+ return [m.index, pos];
174
+ }
175
+ return null;
176
+ }
177
+ /**
178
+ * The `data-tab` values under a tabs nav, in document order. A value holding
179
+ * an expression is skipped: its id is only known at render time.
180
+ */
181
+ function readTabIds(template, navSelector) {
182
+ const range = elementRange(template, navSelector);
183
+ if (!range) return [];
184
+ const nav = template.slice(range[0], range[1]);
185
+ const ids = [];
186
+ for (const m of nav.matchAll(tagRe())) {
187
+ const id = attr(m[2] ?? "", "data-tab");
188
+ if (id && !id.includes("{{")) ids.push(id);
189
+ }
190
+ return ids;
191
+ }
192
+ /**
193
+ * Add the attributes the generated sheet needs, and report each opening tag
194
+ * that changed. Every other byte of the template is left where it was.
195
+ */
196
+ function editTemplate(template, opts) {
197
+ const edits = [];
198
+ const navRanges = opts.navSelectors.map((selector) => elementRange(template, selector)).filter((range) => range !== null);
199
+ const inNav = (index) => navRanges.some(([start, end]) => index >= start && index < end);
200
+ return {
201
+ output: template.replace(tagRe(), (whole, name, attrs, selfClose, offset) => {
202
+ const add = [];
203
+ const hasAction = attr(attrs, "data-action") !== null;
204
+ if (!hasAction) {
205
+ for (const action of opts.actions) if (matches(attrs, action.selector)) {
206
+ add.push(`data-action="${action.name}"`);
207
+ break;
208
+ }
209
+ }
210
+ const tab = attr(attrs, "data-tab");
211
+ const needsGroup = attr(attrs, "data-group") === null;
212
+ let withClass = attrs;
213
+ const isNavLink = tab !== null && inNav(offset);
214
+ const isPane = tab !== null && !isNavLink && hasClass(attrs, "tab");
215
+ if (isNavLink) {
216
+ if (!hasAction && !add.some((one) => one.startsWith("data-action="))) add.push("data-action=\"vttforgeTab\"");
217
+ if (needsGroup) add.push("data-group=\"primary\"");
218
+ } else if (isPane && needsGroup) add.push("data-group=\"primary\"");
219
+ if ((isNavLink || isPane) && tab !== null && !tab.includes("{{") && !/\{\{\s*tabs\./.test(attrs)) {
220
+ const marker = `{{tabs.${tab}.cssClass}}`;
221
+ withClass = /\sclass\s*=\s*"([^"]*)"/.test(attrs) ? attrs.replace(/(\sclass\s*=\s*")([^"]*)(")/, (_m, open, value, close) => `${open}${value.trimEnd()} ${marker}${close}`) : attrs;
222
+ if (withClass === attrs) add.push(`class="${marker}"`);
223
+ }
224
+ if (add.length === 0 && withClass === attrs) return whole;
225
+ const after = `<${name}${withClass.replace(/\s+$/, "")}${add.length > 0 ? ` ${add.join(" ")}` : ""}${selfClose ? " /" : ""}>`;
226
+ edits.push({
227
+ line: lineOf(template, offset),
228
+ before: whole,
229
+ after
230
+ });
231
+ return after;
232
+ }),
233
+ edits,
234
+ formRoot: /^\s*<form\b/.test(template)
235
+ };
236
+ }
237
+ //#endregion
238
+ //#region src/migrate/parse.ts
239
+ /**
240
+ * The parse side of `migrate --sheets`: an AST for the class structure, and
241
+ * the few lookups the planner needs. Bodies are never re-printed from the
242
+ * tree; the planner slices the original text by node range.
243
+ */
244
+ const CONVERTED = /* @__PURE__ */ new Set(["ActorSheet", "ItemSheet"]);
245
+ const UNSUPPORTED = /* @__PURE__ */ new Set([
246
+ "Application",
247
+ "FormApplication",
248
+ "Dialog",
249
+ "DocumentSheet"
250
+ ]);
251
+ function parseSource(source, lang) {
252
+ return parse(source, {
253
+ sourceType: "module",
254
+ errorRecovery: true,
255
+ attachComment: false,
256
+ plugins: lang === "ts" ? ["typescript", "decorators"] : ["decorators"]
257
+ });
258
+ }
259
+ function text(source, node) {
260
+ return source.slice(node.start ?? 0, node.end ?? 0);
261
+ }
262
+ /** Depth-first over every child node. Return `false` from `visit` to skip a subtree. */
263
+ function walk(node, visit) {
264
+ if (!node || typeof node.type !== "string") return;
265
+ if (visit(node) === false) return;
266
+ for (const key of Object.keys(node)) {
267
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
268
+ const value = node[key];
269
+ if (Array.isArray(value)) for (const v of value) walk(v, visit);
270
+ else if (value && typeof value === "object" && "type" in value) walk(value, visit);
271
+ }
272
+ }
273
+ /** `foundry.appv1.sheets.ActorSheet` → the leaf name, or the identifier itself. */
274
+ function superName(cls) {
275
+ const s = cls.superClass;
276
+ if (!s) return null;
277
+ if (s.type === "Identifier") return s.name;
278
+ if (s.type === "MemberExpression" && s.property.type === "Identifier") return s.property.name;
279
+ return null;
280
+ }
281
+ function classesOf(ast) {
282
+ const out = [];
283
+ walk(ast.program, (n) => {
284
+ if (n.type === "ClassDeclaration") {
285
+ out.push({
286
+ name: n.id?.name ?? "",
287
+ node: n
288
+ });
289
+ return false;
290
+ }
291
+ if (n.type === "ExportDefaultDeclaration" && n.declaration.type === "ClassDeclaration") {
292
+ const base = superName(n.declaration) ?? "Sheet";
293
+ out.push({
294
+ name: n.declaration.id?.name ?? `Default${base}`,
295
+ node: n.declaration
296
+ });
297
+ return false;
298
+ }
299
+ if (n.type === "VariableDeclarator" && n.init?.type === "ClassExpression" && n.id.type === "Identifier") {
300
+ out.push({
301
+ name: n.id.name,
302
+ node: n.init
303
+ });
304
+ return false;
305
+ }
306
+ });
307
+ return out;
308
+ }
309
+ function findSheetClasses(ast, source) {
310
+ const found = [];
311
+ for (const { name, node } of classesOf(ast)) {
312
+ const base = superName(node);
313
+ if (!base || !CONVERTED.has(base) || !node.superClass) continue;
314
+ found.push({
315
+ name,
316
+ base,
317
+ node,
318
+ superText: text(source, node.superClass)
319
+ });
320
+ }
321
+ return found;
322
+ }
323
+ function unsupportedBases(ast, source) {
324
+ const out = [];
325
+ for (const { name, node } of classesOf(ast)) {
326
+ const base = superName(node);
327
+ if (!base || !UNSUPPORTED.has(base) || !node.superClass) continue;
328
+ out.push({
329
+ name,
330
+ superText: text(source, node.superClass),
331
+ line: node.loc?.start.line ?? 0
332
+ });
333
+ }
334
+ return out;
335
+ }
336
+ function methodOf(cls, name, opts = {}) {
337
+ for (const member of cls.body.body) {
338
+ if (member.type !== "ClassMethod") continue;
339
+ if (member.key.type !== "Identifier" || member.key.name !== name) continue;
340
+ if (opts.static !== void 0 && Boolean(member.static) !== opts.static) continue;
341
+ if (opts.kind !== void 0 && member.kind !== opts.kind) continue;
342
+ return member;
343
+ }
344
+ return null;
345
+ }
346
+ //#endregion
347
+ //#region src/migrate/sheet-bodies.ts
348
+ /**
349
+ * Text rewrites applied to method bodies carried over from an Application v1
350
+ * sheet. Each one is scoped to the slice the planner hands it, so a pattern
351
+ * here never sees the rest of the file.
352
+ *
353
+ * Nothing is re-printed from a syntax tree: the bodies keep the author's
354
+ * spacing and comments, and every rewrite is a replacement the reader can
355
+ * find in the diff. What cannot be decided mechanically becomes a
356
+ * `// TODO(migrate)` line above the code that needs the decision, and the
357
+ * same message comes back in `todos` so the report can list it.
358
+ */
359
+ const TODO = (msg) => `// TODO(migrate): ${msg}`;
360
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
361
+ const camel = (s) => s.replace(/-+(\w)/g, (_m, c) => c.toUpperCase());
362
+ /** Replace outside comments and strings; the mask keeps them out of reach. */
363
+ function replaceCode(code, pattern, replacement) {
364
+ const masked = maskComments(code, { strings: true });
365
+ return code.replace(pattern, (match, ...rest) => {
366
+ const offset = rest.find((r) => typeof r === "number") ?? 0;
367
+ if (masked[offset] === "\0") return match;
368
+ return replacement(match, ...rest.filter((r) => typeof r === "string"));
369
+ });
370
+ }
371
+ /** Put a TODO line above the line that holds `index`. */
372
+ function todoAt(code, index, msg) {
373
+ const lineStart = code.lastIndexOf("\n", index - 1) + 1;
374
+ const indent = /^[ \t]*/.exec(code.slice(lineStart))?.[0] ?? "";
375
+ return `${code.slice(0, lineStart)}${indent}${TODO(msg)}\n${code.slice(lineStart)}`;
376
+ }
377
+ /** The jQuery calls with no one-to-one DOM rewrite. */
378
+ const LEFTOVER_JQUERY = /\$\(|\.(?:val|text|html|prop|toggle|slideToggle|slideUp|slideDown|show|hide|addClass|removeClass|toggleClass|siblings|children|find|css)\(/g;
379
+ const JQUERY_MSG = "jQuery left here; use the DOM on `target` / `this.element`";
380
+ /**
381
+ * A handler body from `activateListeners`, with `event.currentTarget` folded
382
+ * into the `target` the action receives and the jQuery data readers turned
383
+ * into `dataset`.
384
+ */
385
+ function rewriteHandlerBody(body, eventParam, htmlParam, targetName = "target") {
386
+ const todos = [];
387
+ let code = body;
388
+ if (eventParam) {
389
+ const ev = esc(eventParam);
390
+ code = replaceCode(code, new RegExp(`\\$\\(\\s*${ev}\\.currentTarget\\s*\\)`, "g"), () => targetName);
391
+ if (targetName !== `${eventParam}.currentTarget`) code = replaceCode(code, new RegExp(`\\b${ev}\\.currentTarget\\b`, "g"), () => targetName);
392
+ }
393
+ code = replaceCode(code, /\.data\(\s*(['"])([\w-]+)\1\s*\)/g, (_m, _q, key) => `.dataset.${camel(key)}`);
394
+ code = replaceCode(code, /\.attr\(\s*(['"])data-([\w-]+)\1\s*\)/g, (_m, _q, key) => `.dataset.${camel(key)}`);
395
+ code = replaceCode(code, /\.parents\(/g, () => ".closest(");
396
+ if (htmlParam) code = replaceCode(code, new RegExp(`\\b${esc(htmlParam)}\\.find\\(`, "g"), () => "this.element.querySelectorAll(");
397
+ code = replaceCode(code, /this\.element\.find\(/g, () => "this.element.querySelectorAll(");
398
+ const masked = maskComments(code, { strings: true });
399
+ const lines = /* @__PURE__ */ new Set();
400
+ for (const m of code.matchAll(LEFTOVER_JQUERY)) {
401
+ const at = m.index ?? 0;
402
+ if (masked[at] === "\0") continue;
403
+ lines.add(code.lastIndexOf("\n", at - 1) + 1);
404
+ }
405
+ for (const lineStart of [...lines].sort((a, b) => b - a)) {
406
+ code = todoAt(code, lineStart, JQUERY_MSG);
407
+ todos.unshift(JQUERY_MSG);
408
+ }
409
+ return {
410
+ code,
411
+ todos
412
+ };
413
+ }
414
+ /**
415
+ * `getData()` becomes `_prepareContext(options)`. V2 hands back a much
416
+ * smaller context, so the keys a v1 body expects to already be there are
417
+ * assigned right after the `super` call — unless the method assigns them
418
+ * itself without reading the old value first.
419
+ */
420
+ function rewriteGetData(methodText, base) {
421
+ const todos = [];
422
+ const params = /^(\s*)(async\s+)?getData\s*\(([^)]*)\)/.exec(methodText)?.[3]?.trim() ?? "";
423
+ let code = methodText.replace(/^(\s*)(async\s+)?getData\s*\(([^)]*)\)/, (_m, indent) => `${indent}async _prepareContext(options)`);
424
+ code = replaceCode(code, /super\.getData\(\s*[^)]*\)/g, () => "super._prepareContext(options)");
425
+ const varMatch = /(?:const|let|var)\s+(\w+)\s*=\s*(?:await\s+)?super\._prepareContext\(options\)\s*;/.exec(code);
426
+ const v = varMatch?.[1] ?? "context";
427
+ const own = base === "ActorSheet" ? "actor" : "item";
428
+ const wanted = [
429
+ [own, `${v}.${own} = this.document;`],
430
+ ["data", `${v}.data = this.document;`],
431
+ ["system", `${v}.system = this.document.system;`]
432
+ ];
433
+ if (base === "ActorSheet") wanted.push(["items", `${v}.items = [...this.document.items];`]);
434
+ wanted.push(["editable", `${v}.editable = this.isEditable;`], ["owner", `${v}.owner = this.document.isOwner;`]);
435
+ const masked = maskComments(code, { strings: true });
436
+ const inject = wanted.filter(([key]) => {
437
+ const assigned = new RegExp(`\\b${esc(v)}\\.${key}\\s*=(?!=)`).test(masked);
438
+ const read = new RegExp(`\\b${esc(v)}\\.${key}\\b(?!\\s*=(?!=))`).test(masked);
439
+ return !assigned || read;
440
+ }).map(([, line]) => line);
441
+ if (varMatch) {
442
+ const at = varMatch.index + varMatch[0].length;
443
+ const indent = /^[ \t]*/.exec(code.slice(code.lastIndexOf("\n", varMatch.index) + 1))?.[0] ?? " ";
444
+ code = `${code.slice(0, at)}${inject.map((l) => `\n${indent}${l}`).join("")}${code.slice(at)}`;
445
+ } else if (inject.length > 0) {
446
+ const msg = `set ${inject.join(" ")} on the context before returning it`;
447
+ code = todoAt(code, code.indexOf("{") + 1, msg);
448
+ todos.push(msg);
449
+ }
450
+ if (params !== "" && params !== "options") {
451
+ const msg = `\`getData(${params})\` took its own parameters; \`_prepareContext(options)\` does not. Read what the body needs from \`options\` or \`this.document\``;
452
+ code = todoAt(code, code.indexOf("{") + 1, msg);
453
+ todos.push(msg);
454
+ }
455
+ return {
456
+ code,
457
+ todos
458
+ };
459
+ }
460
+ /**
461
+ * `_onDropItem(event, data)` becomes `onDropItem(item, event)`: the SDK base
462
+ * resolves the dropped document before it calls the hook, so the raw drop
463
+ * payload the v1 body read is gone.
464
+ */
465
+ function rewriteDropMethod(methodText, which) {
466
+ const lower = which.toLowerCase();
467
+ const sig = new RegExp(`_onDrop${which}\\s*\\(\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\)`);
468
+ const m = sig.exec(methodText);
469
+ if (!m) return {
470
+ code: methodText,
471
+ todos: []
472
+ };
473
+ const eventName = m[1] ?? "event";
474
+ const dataName = m[2] ?? "data";
475
+ const param = new RegExp(`\\b(?:const|let|var)\\s+(?:${lower}\\b|\\{[^}]*\\b${lower}\\b[^}]*\\}|\\[[^\\]]*\\b${lower}\\b[^\\]]*\\])`).test(methodText) ? `dropped${which}` : lower;
476
+ let code = methodText.replace(sig, `onDrop${which}(${param}, ${eventName})`);
477
+ const todos = [];
478
+ if (which === "Item") code = replaceCode(code, /super\._onDropItem\([^)]*\)/g, () => `this.document.createEmbeddedDocuments('Item', [${param}.toObject()])`);
479
+ else code = replaceCode(code, new RegExp(`super\\._onDrop${which}\\([^)]*\\)`, "g"), () => `super.onDrop${which}(${param}, ${eventName})`);
480
+ code = replaceCode(code, new RegExp(`\\b${esc(dataName)}\\b`, "g"), () => `${param}.toDragData()`);
481
+ const msg = which === "Item" ? `the base hands the resolved Item as \`${param}\`; the old \`${dataName}\` payload is now \`${param}.toDragData()\`, read \`${param}\` directly where you can. The old super call created it on the actor, which is what the createEmbeddedDocuments line does now (a drop from the same actor used to re-sort instead). Return true when the drop was handled, undefined to let the base do its default` : `the base hands the resolved Actor as \`${param}\`; the old \`${dataName}\` payload is now \`${param}.toDragData()\`, read \`${param}\` directly where you can. Return true when the drop was handled`;
482
+ code = todoAt(code, code.indexOf("{") + 1, msg);
483
+ todos.push(msg);
484
+ return {
485
+ code,
486
+ todos
487
+ };
488
+ }
489
+ /** `Dialog.confirm({ ... })`: the options literal is group 1. Non-greedy, so a nested `}` ends it early; `balanced` catches that. */
490
+ const CONFIRM_CALL = /\bDialog\.confirm\(\s*\{([\s\S]*?)\}\s*\)/g;
491
+ const NEW_DIALOG = /\bnew\s+Dialog\s*\(/g;
492
+ const UNREADABLE_MSG = "Dialog.confirm here could not be read (a nested object or a comma inside an option); rewrite it as DialogV2.confirm({ window: { title }, content, yes: { callback }, no: { callback } }) by hand";
493
+ const NEW_DIALOG_MSG = "Dialog v1 (removed in v16); rebuild with DialogV2.prompt / DialogV2.wait, buttons as { action, label, callback }";
494
+ /** Whether every bracket opened in `text` (outside strings and comments) is closed. */
495
+ function balanced(text) {
496
+ const masked = maskComments(text, { strings: true });
497
+ const pairs = /* @__PURE__ */ new Map([
498
+ [")", "("],
499
+ ["]", "["],
500
+ ["}", "{"]
501
+ ]);
502
+ const stack = [];
503
+ for (let i = 0; i < masked.length; i += 1) {
504
+ const ch = masked[i];
505
+ if (ch === void 0 || ch === "\0") continue;
506
+ if (ch === "(" || ch === "[" || ch === "{") stack.push(ch);
507
+ else if (pairs.has(ch)) {
508
+ if (stack.pop() !== pairs.get(ch)) return false;
509
+ }
510
+ }
511
+ return stack.length === 0;
512
+ }
513
+ /** The top-level `key: value` pairs of an object literal's inner text. */
514
+ function topLevelPairs(inner) {
515
+ const masked = maskComments(inner, { strings: true });
516
+ const pairs = [];
517
+ let depth = 0;
518
+ let start = 0;
519
+ const flush = (end) => {
520
+ const raw = inner.slice(start, end).trim();
521
+ if (!raw) return;
522
+ if (raw.startsWith("...")) {
523
+ pairs.push({
524
+ key: raw,
525
+ value: "",
526
+ spread: true
527
+ });
528
+ return;
529
+ }
530
+ const colon = raw.indexOf(":");
531
+ if (colon === -1) {
532
+ pairs.push({
533
+ key: raw,
534
+ value: raw,
535
+ spread: false
536
+ });
537
+ return;
538
+ }
539
+ pairs.push({
540
+ key: raw.slice(0, colon).trim(),
541
+ value: raw.slice(colon + 1).trim(),
542
+ spread: false
543
+ });
544
+ };
545
+ for (let i = 0; i < masked.length; i += 1) {
546
+ const ch = masked[i];
547
+ if (ch === "\0") continue;
548
+ if (ch === "(" || ch === "[" || ch === "{") depth += 1;
549
+ else if (ch === ")" || ch === "]" || ch === "}") depth -= 1;
550
+ else if (ch === "," && depth === 0) {
551
+ flush(i);
552
+ start = i + 1;
553
+ }
554
+ }
555
+ flush(inner.length);
556
+ return pairs;
557
+ }
558
+ /**
559
+ * The DialogV2.confirm call for a Dialog.confirm options literal, or `null`
560
+ * when the literal could not be read. `missing` names what the rewrite left
561
+ * behind (a spread, an option with no V2 slot). `defaultYes` is dropped on
562
+ * purpose: DialogV2 has no equivalent.
563
+ */
564
+ function readConfirmOptions(inner) {
565
+ if (!balanced(inner)) return {
566
+ code: null,
567
+ missing: []
568
+ };
569
+ const missing = [];
570
+ const found = {};
571
+ for (const pair of topLevelPairs(inner)) {
572
+ if (pair.spread) {
573
+ missing.push(`the spread ${pair.key}`);
574
+ continue;
575
+ }
576
+ const key = pair.key.replace(/^['"]|['"]$/g, "");
577
+ if (key === "title" || key === "content" || key === "yes" || key === "no") found[key] = pair.value;
578
+ else if (key !== "defaultYes" && key !== "rejectClose" && key !== "options") missing.push(key);
579
+ }
580
+ return {
581
+ code: `DialogV2.confirm({ ${[
582
+ found.title ? `window: { title: ${found.title} }` : "",
583
+ found.content ? `content: ${found.content}` : "",
584
+ found.yes ? `yes: { callback: ${found.yes} }` : "",
585
+ found.no ? `no: { callback: ${found.no} }` : ""
586
+ ].filter(Boolean).join(", ")} })`,
587
+ missing
588
+ };
589
+ }
590
+ function rewriteDialogs(code) {
591
+ const todos = [];
592
+ const confirmMask = maskComments(code, { strings: true });
593
+ const hits = [];
594
+ for (const m of code.matchAll(CONFIRM_CALL)) {
595
+ const start = m.index ?? 0;
596
+ if (confirmMask[start] === "\0") continue;
597
+ const read = readConfirmOptions(m[1] ?? "");
598
+ hits.push({
599
+ start,
600
+ end: start + m[0].length,
601
+ code: read.code,
602
+ missing: read.missing
603
+ });
604
+ }
605
+ let out = code;
606
+ for (const hit of hits.reverse()) {
607
+ if (hit.code !== null) out = `${out.slice(0, hit.start)}${hit.code}${out.slice(hit.end)}`;
608
+ if (hit.code === null) {
609
+ out = todoAt(out, hit.start, UNREADABLE_MSG);
610
+ todos.unshift(UNREADABLE_MSG);
611
+ } else if (hit.missing.length > 0) {
612
+ const msg = `Dialog.confirm options left behind: ${hit.missing.join(", ")}; move them onto the DialogV2.confirm call by hand`;
613
+ out = todoAt(out, hit.start, msg);
614
+ todos.unshift(msg);
615
+ }
616
+ }
617
+ const dialogMask = maskComments(out, { strings: true });
618
+ const starts = [];
619
+ for (const m of out.matchAll(NEW_DIALOG)) {
620
+ const at = m.index ?? 0;
621
+ if (dialogMask[at] !== "\0") starts.push(at);
622
+ }
623
+ for (const at of starts.reverse()) {
624
+ out = todoAt(out, at, NEW_DIALOG_MSG);
625
+ todos.push(NEW_DIALOG_MSG);
626
+ }
627
+ return {
628
+ code: out,
629
+ todos
630
+ };
631
+ }
632
+ //#endregion
633
+ //#region src/migrate/sheet-listeners.ts
634
+ const EVENTS = /* @__PURE__ */ new Set([
635
+ "click",
636
+ "dblclick",
637
+ "change",
638
+ "contextmenu",
639
+ "input",
640
+ "keydown",
641
+ "keyup",
642
+ "focus",
643
+ "blur",
644
+ "mouseenter",
645
+ "mouseleave",
646
+ "submit"
647
+ ]);
648
+ const FIRST_CLASS_OR_ID = /[.#]([A-Za-z_][\w-]*)/;
649
+ const SEPARATOR = /[-_]+(\w)/g;
650
+ function actionName(selector, taken) {
651
+ const captured = FIRST_CLASS_OR_ID.exec(selector)?.[1];
652
+ if (!captured) return null;
653
+ const base = captured.replace(SEPARATOR, (_, c) => c.toUpperCase()).replace(/^[A-Z]/, (c) => c.toLowerCase());
654
+ let name = base;
655
+ let i = 2;
656
+ while (taken.has(name)) {
657
+ name = `${base}${i}`;
658
+ i += 1;
659
+ }
660
+ taken.add(name);
661
+ return name;
662
+ }
663
+ /** `html.find(SEL)` with `html` being the listener's parameter → the selector. */
664
+ function findSelector(callee, htmlParam) {
665
+ if (callee.type !== "CallExpression") return null;
666
+ const c = callee.callee;
667
+ if (c.type !== "MemberExpression" || c.object.type !== "Identifier" || c.object.name !== htmlParam) return null;
668
+ if (c.property.type !== "Identifier" || c.property.name !== "find") return null;
669
+ const [arg] = callee.arguments;
670
+ return arg && arg.type === "StringLiteral" ? arg.value : null;
671
+ }
672
+ /** `this._onX.bind(this)` → `_onX`; `(ev) => this._onX(ev)` → `_onX`. */
673
+ function forwardedMethod(handler) {
674
+ if (handler.type === "CallExpression" && handler.callee.type === "MemberExpression" && handler.callee.property.type === "Identifier" && handler.callee.property.name === "bind" && handler.callee.object.type === "MemberExpression" && handler.callee.object.object.type === "ThisExpression" && handler.callee.object.property.type === "Identifier") return handler.callee.object.property.name;
675
+ if (handler.type === "ArrowFunctionExpression") {
676
+ let call = null;
677
+ if (handler.body.type === "CallExpression") call = handler.body;
678
+ else if (handler.body.type === "BlockStatement" && handler.body.body.length === 1) {
679
+ const only = handler.body.body[0];
680
+ if (only?.type === "ExpressionStatement" && only.expression.type === "CallExpression") call = only.expression;
681
+ if (only?.type === "ReturnStatement" && only.argument?.type === "CallExpression") call = only.argument;
682
+ }
683
+ if (call && call.callee.type === "MemberExpression" && call.callee.object.type === "ThisExpression" && call.callee.property.type === "Identifier" && call.arguments.length <= 1) {
684
+ const [a] = call.arguments;
685
+ const p = handler.params[0];
686
+ if (!a || a.type === "Identifier" && p?.type === "Identifier" && a.name === p.name) return call.callee.property.name;
687
+ }
688
+ }
689
+ return null;
690
+ }
691
+ /**
692
+ * `html.find(SEL).<event>(H)` or `html.find(SEL).on('<event>', H)` → the parts,
693
+ * or `null` when the statement is not a jQuery binding this can translate.
694
+ */
695
+ function boundEvent(expr, htmlParam) {
696
+ if (expr.type !== "CallExpression") return null;
697
+ if (expr.callee.type !== "MemberExpression" || expr.callee.property.type !== "Identifier") return null;
698
+ const receiver = expr.callee.object;
699
+ if (receiver.type === "Super") return null;
700
+ const selector = findSelector(receiver, htmlParam);
701
+ if (selector === null) return null;
702
+ const calleeName = expr.callee.property.name;
703
+ if (EVENTS.has(calleeName)) {
704
+ const handler = expr.arguments[0];
705
+ return handler ? {
706
+ selector,
707
+ event: calleeName,
708
+ handler
709
+ } : null;
710
+ }
711
+ if (calleeName === "on" && expr.arguments.length === 2) {
712
+ const first = expr.arguments[0];
713
+ const handler = expr.arguments[1];
714
+ if (first?.type === "StringLiteral" && handler) return {
715
+ selector,
716
+ event: first.value,
717
+ handler
718
+ };
719
+ }
720
+ return null;
721
+ }
722
+ function extractListeners(cls, source) {
723
+ const out = {
724
+ actions: [],
725
+ listeners: [],
726
+ leftovers: [],
727
+ htmlParam: "html"
728
+ };
729
+ const method = methodOf(cls.node, "activateListeners");
730
+ if (!method) return out;
731
+ const p = method.params[0];
732
+ const htmlParam = p?.type === "Identifier" ? p.name : "html";
733
+ out.htmlParam = htmlParam;
734
+ const taken = /* @__PURE__ */ new Set();
735
+ const leftover = (stmt) => {
736
+ out.leftovers.push({
737
+ line: stmt.loc?.start.line ?? 0,
738
+ text: text(source, stmt)
739
+ });
740
+ };
741
+ const consider = (stmt) => {
742
+ if (stmt.type !== "ExpressionStatement") return;
743
+ const e = stmt.expression;
744
+ if (e.type === "AwaitExpression") return;
745
+ if (e.type !== "CallExpression") return;
746
+ if (e.callee.type !== "MemberExpression" || e.callee.property.type !== "Identifier") return;
747
+ if (e.callee.object.type === "Super") return;
748
+ const bound = boundEvent(e, htmlParam);
749
+ if (!bound) {
750
+ leftover(stmt);
751
+ return;
752
+ }
753
+ const { selector, event, handler } = bound;
754
+ if (event !== "click") {
755
+ out.listeners.push({
756
+ selector,
757
+ event,
758
+ handlerText: text(source, handler)
759
+ });
760
+ return;
761
+ }
762
+ const name = actionName(selector, taken);
763
+ if (name === null) {
764
+ leftover(stmt);
765
+ return;
766
+ }
767
+ const forwarded = forwardedMethod(handler);
768
+ if (forwarded) {
769
+ out.actions.push({
770
+ name,
771
+ selector,
772
+ kind: "method",
773
+ method: forwarded,
774
+ param: null,
775
+ body: null,
776
+ isAsync: false
777
+ });
778
+ return;
779
+ }
780
+ if (handler.type === "ArrowFunctionExpression" || handler.type === "FunctionExpression") {
781
+ const p0 = handler.params[0];
782
+ out.actions.push({
783
+ name,
784
+ selector,
785
+ kind: "inline",
786
+ method: null,
787
+ param: p0?.type === "Identifier" ? p0.name : null,
788
+ body: text(source, handler.body),
789
+ isAsync: Boolean(handler.async)
790
+ });
791
+ return;
792
+ }
793
+ leftover(stmt);
794
+ };
795
+ /** A guard such as `if (!this.options.editable) return;`: V2 sheets gate through isEditable. */
796
+ const isGuard = (stmt) => {
797
+ if (stmt.type !== "IfStatement" || stmt.alternate) return false;
798
+ const c = stmt.consequent;
799
+ if (c.type === "ReturnStatement") return true;
800
+ return c.type === "BlockStatement" && c.body.length === 1 && c.body[0]?.type === "ReturnStatement";
801
+ };
802
+ const visit = (stmts) => {
803
+ for (const stmt of stmts) {
804
+ if (isGuard(stmt)) continue;
805
+ if (stmt.type === "IfStatement") {
806
+ const branches = [stmt.consequent, stmt.alternate].filter((b) => Boolean(b));
807
+ for (const b of branches) visit(b.type === "BlockStatement" ? b.body : [b]);
808
+ out.leftovers.push({
809
+ line: stmt.loc?.start.line ?? 0,
810
+ text: `if (${text(source, stmt.test)}) guarded the bindings above it; V2 actions run regardless, gate inside the handler`
811
+ });
812
+ continue;
813
+ }
814
+ if (stmt.type === "BlockStatement") {
815
+ visit(stmt.body);
816
+ continue;
817
+ }
818
+ consider(stmt);
819
+ }
820
+ };
821
+ visit(method.body.body);
822
+ return out;
823
+ }
824
+ //#endregion
825
+ //#region src/migrate/sheet-options.ts
826
+ function keyName(p) {
827
+ if (p.key.type === "Identifier") return p.key.name;
828
+ if (p.key.type === "StringLiteral") return p.key.value;
829
+ return null;
830
+ }
831
+ const NOT_A_VALUE = /* @__PURE__ */ new Set([
832
+ "ArrayPattern",
833
+ "ObjectPattern",
834
+ "AssignmentPattern",
835
+ "RestElement"
836
+ ]);
837
+ function props(obj) {
838
+ const out = [];
839
+ for (const p of obj.properties) {
840
+ if (p.type !== "ObjectProperty") continue;
841
+ const k = keyName(p);
842
+ if (k && !NOT_A_VALUE.has(p.value.type)) out.push([k, p.value]);
843
+ }
844
+ return out;
845
+ }
846
+ function str(e) {
847
+ return e.type === "StringLiteral" ? e.value : null;
848
+ }
849
+ function num(e) {
850
+ return e.type === "NumericLiteral" ? e.value : null;
851
+ }
852
+ function bool(e) {
853
+ return e.type === "BooleanLiteral" ? e.value : null;
854
+ }
855
+ /** The options literal: the last object argument of the returned call, or the returned object. */
856
+ function optionsLiteral(method) {
857
+ let found = null;
858
+ walk(method.body, (n) => {
859
+ if (found) return false;
860
+ if (n.type !== "ReturnStatement" || !n.argument) return void 0;
861
+ const arg = n.argument;
862
+ if (arg.type === "ObjectExpression") found = arg;
863
+ else if (arg.type === "CallExpression") {
864
+ const last = [...arg.arguments].reverse().find((a) => a.type === "ObjectExpression");
865
+ if (last?.type === "ObjectExpression") found = last;
866
+ }
867
+ return false;
868
+ });
869
+ return found;
870
+ }
871
+ function extractOptions(cls, source) {
872
+ const out = {
873
+ classes: null,
874
+ width: null,
875
+ height: null,
876
+ resizable: null,
877
+ submitOnChange: null,
878
+ template: null,
879
+ templateGetter: methodOf(cls.node, "template", {
880
+ kind: "get",
881
+ static: false
882
+ }),
883
+ tabs: [],
884
+ dragDrop: null,
885
+ unknown: []
886
+ };
887
+ const method = methodOf(cls.node, "defaultOptions", {
888
+ static: true,
889
+ kind: "get"
890
+ });
891
+ const literal = method ? optionsLiteral(method) : null;
892
+ if (!literal) return out;
893
+ for (const [key, value] of props(literal)) switch (key) {
894
+ case "classes":
895
+ out.classes = text(source, value);
896
+ break;
897
+ case "width":
898
+ out.width = num(value);
899
+ break;
900
+ case "height":
901
+ out.height = num(value);
902
+ break;
903
+ case "resizable":
904
+ out.resizable = bool(value);
905
+ break;
906
+ case "submitOnChange":
907
+ out.submitOnChange = bool(value);
908
+ break;
909
+ case "template":
910
+ out.template = str(value);
911
+ break;
912
+ case "dragDrop":
913
+ out.dragDrop = text(source, value);
914
+ break;
915
+ case "tabs":
916
+ out.tabs.push(...readTabs(value));
917
+ break;
918
+ default: out.unknown.push(key);
919
+ }
920
+ return out;
921
+ }
922
+ function readTabs(value) {
923
+ if (value.type !== "ArrayExpression") return [];
924
+ const tabs = [];
925
+ for (const el of value.elements) {
926
+ if (el?.type !== "ObjectExpression") continue;
927
+ const t = Object.fromEntries(props(el));
928
+ const nav = t.navSelector ? str(t.navSelector) : null;
929
+ if (!nav) continue;
930
+ tabs.push({
931
+ navSelector: nav,
932
+ contentSelector: t.contentSelector ? str(t.contentSelector) : null,
933
+ initial: t.initial ? str(t.initial) : null
934
+ });
935
+ }
936
+ return tabs;
937
+ }
938
+ const q = (s) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
939
+ function renderStatics(opts, tabIds, todo) {
940
+ const lines = [];
941
+ lines.push(" /** @override */");
942
+ lines.push(" static DEFAULT_OPTIONS = foundry.utils.mergeObject(");
943
+ lines.push(" super.DEFAULT_OPTIONS,");
944
+ lines.push(" {");
945
+ if (opts.classes) lines.push(` classes: ${opts.classes},`);
946
+ if (opts.width !== null || opts.height !== null) {
947
+ const parts = [opts.width !== null ? `width: ${opts.width}` : "", opts.height !== null ? `height: ${opts.height}` : ""].filter(Boolean);
948
+ lines.push(` position: { ${parts.join(", ")} },`);
949
+ }
950
+ if (opts.resizable !== null) lines.push(` window: { resizable: ${opts.resizable} },`);
951
+ lines.push(` form: { submitOnChange: ${opts.submitOnChange ?? true} },`);
952
+ lines.push(" actions: {}, // filled below");
953
+ lines.push(" },");
954
+ lines.push(" { inplace: false },");
955
+ lines.push(" );");
956
+ for (const key of opts.unknown) lines.push(` ${todo(`${key} from defaultOptions has no V2 equivalent here; move it by hand or drop it`)}`);
957
+ if (opts.tabs.length > 0) {
958
+ lines.push("", " /** @override */", " static TABS = {");
959
+ for (const [i, tab] of opts.tabs.entries()) {
960
+ const group = i === 0 ? "primary" : `group${i + 1}`;
961
+ const ids = tabIds[tab.navSelector] ?? [];
962
+ const initial = tab.initial ?? ids[0] ?? "";
963
+ if (ids.length === 0) lines.push(` ${todo(`tab ids for ${tab.navSelector} were not found in the template; list them here`)}`);
964
+ lines.push(` ${group}: { tabs: [${ids.map((id) => `{ id: ${q(id)} }`).join(", ")}], initial: ${q(initial)} },`);
965
+ }
966
+ lines.push(" };");
967
+ }
968
+ if (opts.dragDrop) lines.push("", " /** @override */", ` static DRAG_DROP = ${opts.dragDrop};`);
969
+ lines.push("", " /** @override */", " static PARTS = {");
970
+ if (opts.template) lines.push(` sheet: { template: ${q(opts.template)} },`);
971
+ else lines.push(` ${todo("the template is chosen at runtime (get template); name one part per type here or override _configureRenderParts")}`, ` sheet: { template: '' },`);
972
+ lines.push(" };");
973
+ return lines.join("\n");
974
+ }
975
+ //#endregion
976
+ //#region src/migrate/sheets.ts
977
+ /** v1 lifecycle methods a sheet used to override; V2 has other hooks for the same jobs. */
978
+ const V1_LIFECYCLE = /* @__PURE__ */ new Set([
979
+ "setPosition",
980
+ "_getHeaderButtons",
981
+ "_render",
982
+ "_renderInner",
983
+ "_replaceHTML",
984
+ "_onSubmit",
985
+ "_getSubmitData",
986
+ "_onChangeInput",
987
+ "activateEditor",
988
+ "close"
989
+ ]);
990
+ const HANDLED = /* @__PURE__ */ new Set([
991
+ "defaultOptions",
992
+ "getData",
993
+ "activateListeners",
994
+ "_onDropItem",
995
+ "_onDropActor"
996
+ ]);
997
+ const ACTIONS_PLACEHOLDER = " actions: {}, // filled below";
998
+ function methodName(m) {
999
+ return m.key.type === "Identifier" ? m.key.name : null;
1000
+ }
1001
+ const pascal = (s) => s.replace(/^[a-z]/, (c) => c.toUpperCase());
1002
+ const single = (s) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
1003
+ /** Re-indent a member slice so its first line sits at two spaces. */
1004
+ function reindent(memberText) {
1005
+ const lines = memberText.split("\n");
1006
+ const first = lines[0] ?? "";
1007
+ const rest = lines.slice(1);
1008
+ const indents = rest.filter((l) => l.trim().length > 0).map((l) => /^[ \t]*/.exec(l)?.[0].length ?? 0);
1009
+ const min = indents.length > 0 ? Math.min(...indents) : 0;
1010
+ const strip = Math.max(0, min - 4);
1011
+ const body = rest.map((l) => {
1012
+ if (l.trim().length === 0) return "";
1013
+ const own = /^[ \t]*/.exec(l)?.[0].length ?? 0;
1014
+ return l.slice(Math.min(strip, own));
1015
+ });
1016
+ return [` ${first.trimStart()}`, ...body].join("\n");
1017
+ }
1018
+ /** Ensure `(event, target)` on a handler method, keeping the event name it used. */
1019
+ function handlerSignature(methodText, name) {
1020
+ const escaped = name.replace(/[$]/g, "\\$");
1021
+ const sig = new RegExp(`^(\\s*(?:async\\s+)?${escaped}\\s*\\()([^)]*)(\\))`);
1022
+ const m = sig.exec(methodText);
1023
+ if (!m) return {
1024
+ code: methodText,
1025
+ eventParam: null
1026
+ };
1027
+ const eventParam = (m[2] ?? "").split(",").map((p) => p.trim()).filter(Boolean)[0] ?? null;
1028
+ const first = eventParam ?? "event";
1029
+ return {
1030
+ code: methodText.replace(sig, `$1${first}, target$3`),
1031
+ eventParam
1032
+ };
1033
+ }
1034
+ /** The first parameter name of a method, from its signature text. */
1035
+ function firstParam(methodText, name) {
1036
+ const escaped = name.replace(/[$]/g, "\\$");
1037
+ const first = (new RegExp(`^\\s*(?:async\\s+)?${escaped}\\s*\\(([^)]*)\\)`).exec(methodText)?.[1] ?? "").split(",")[0]?.trim();
1038
+ return first ? first : null;
1039
+ }
1040
+ /** Lines after the first sit at `spaces`, keeping their relative indentation. */
1041
+ function indentTo(snippet, spaces) {
1042
+ const lines = snippet.split("\n");
1043
+ const rest = lines.slice(1);
1044
+ const indents = rest.filter((l) => l.trim().length > 0).map((l) => /^[ \t]*/.exec(l)?.[0].length ?? 0);
1045
+ const min = indents.length > 0 ? Math.min(...indents) : 0;
1046
+ const pad = " ".repeat(spaces);
1047
+ return [(lines[0] ?? "").trimStart(), ...rest.map((l) => l.trim().length === 0 ? "" : `${pad}${l.slice(Math.min(min, /^[ \t]*/.exec(l)?.[0].length ?? 0))}`)].join("\n");
1048
+ }
1049
+ /** A block body lifted out of `activateListeners`: inner lines at four spaces, the brace at two. */
1050
+ function dedentBlock(block) {
1051
+ const lines = block.split("\n");
1052
+ if (lines.length < 2) return block;
1053
+ const inner = lines.slice(1, -1);
1054
+ const indents = inner.filter((l) => l.trim().length > 0).map((l) => /^[ \t]*/.exec(l)?.[0].length ?? 0);
1055
+ const min = indents.length > 0 ? Math.min(...indents) : 0;
1056
+ const body = inner.map((l) => l.trim().length === 0 ? "" : ` ${l.slice(Math.min(min, /^[ \t]*/.exec(l)?.[0].length ?? 0))}`);
1057
+ return [
1058
+ lines[0] ?? "{",
1059
+ ...body,
1060
+ " }"
1061
+ ].join("\n");
1062
+ }
1063
+ function importLines(source, lang) {
1064
+ const ast = parseSource(source, lang);
1065
+ const lines = [];
1066
+ for (const n of ast.program.body) if (n.type === "ImportDeclaration") lines.push(text(source, n));
1067
+ return lines;
1068
+ }
1069
+ function isExported(source, cls) {
1070
+ const start = cls.node.start ?? 0;
1071
+ const before = source.slice(Math.max(0, start - 40), start);
1072
+ return /export\s+(?:default\s+)?$/.test(before) || new RegExp(`export\\s+\\{[^}]*\\b${cls.name}\\b`).test(source);
1073
+ }
1074
+ function planClass(cls, source, tabIds) {
1075
+ const base = cls.base === "ActorSheet" ? "BaseActorSheet" : "BaseItemSheet";
1076
+ const own = cls.base === "ActorSheet" ? "actor" : "item";
1077
+ const options = extractOptions(cls, source);
1078
+ const listeners = extractListeners(cls, source);
1079
+ const templates = /* @__PURE__ */ new Set();
1080
+ const navs = /* @__PURE__ */ new Set();
1081
+ let usesDialogV2 = false;
1082
+ if (options.template) templates.add(options.template);
1083
+ if (options.templateGetter) {
1084
+ for (const m of text(source, options.templateGetter).matchAll(/["'`]([^"'`$]+\.(?:hbs|html))["'`]/g)) if (m[1]) templates.add(m[1]);
1085
+ }
1086
+ for (const t of options.tabs) navs.add(t.navSelector);
1087
+ const members = [];
1088
+ const todo = (msg) => TODO(msg);
1089
+ const actionEntries = listeners.actions.map((a) => ({
1090
+ name: a.name,
1091
+ selector: a.selector,
1092
+ method: a.kind === "method" && a.method ? a.method : `_on${pascal(a.name)}`
1093
+ }));
1094
+ const actionsBlock = actionEntries.length === 0 ? " actions: {}," : ` actions: {\n${actionEntries.map((a) => ` ${a.name}: ${cls.name}.prototype.${a.method},`).join("\n")}\n },`;
1095
+ const statics = options.templateGetter ? {
1096
+ ...options,
1097
+ template: null
1098
+ } : options;
1099
+ members.push(renderStatics(statics, tabIds, todo).replace(ACTIONS_PLACEHOLDER, actionsBlock));
1100
+ if (!methodOf(cls.node, own, { kind: "get" })) members.push(` get ${own}() {\n return this.document;\n }`);
1101
+ if (options.templateGetter) members.push(reindent(text(source, options.templateGetter)));
1102
+ const getData = methodOf(cls.node, "getData");
1103
+ if (getData) members.push(rewriteGetData(reindent(text(source, getData)), cls.base).code);
1104
+ if (listeners.listeners.length > 0) {
1105
+ const body = listeners.listeners.map((l) => {
1106
+ const param = /^\s*(?:async\s+)?\(?\s*(\w+)/.exec(l.handlerText)?.[1] ?? null;
1107
+ const handler = /^\s*(?:async\s+)?(?:\(|\w+\s*=>|function\b)/.test(l.handlerText) ? indentTo(rewriteHandlerBody(l.handlerText, param, listeners.htmlParam, param ? `${param}.currentTarget` : "target").code, 6) : l.handlerText;
1108
+ return ` for (const el of this.element.querySelectorAll(${single(l.selector)})) {\n el.addEventListener(${single(l.event)}, ${handler});\n }`;
1109
+ }).join("\n");
1110
+ members.push(` /** @override */\n _onRender(context, options) {\n super._onRender(context, options);\n${body}\n }`);
1111
+ }
1112
+ const handlerNames = new Set(listeners.actions.filter((a) => a.kind === "method" && a.method).map((a) => a.method));
1113
+ const listenerTargets = new Set(listeners.listeners.flatMap((l) => [...l.handlerText.matchAll(/this\.(\w+)/g)].map((m) => m[1] ?? "")));
1114
+ const applyDialogs = (code) => {
1115
+ const d = rewriteDialogs(code);
1116
+ if (/DialogV2\./.test(d.code)) usesDialogV2 = true;
1117
+ return d.code;
1118
+ };
1119
+ for (const member of cls.node.body.body) {
1120
+ if (member.type !== "ClassMethod" && member.type !== "ClassProperty" && member.type !== "ClassPrivateMethod") continue;
1121
+ const name = member.type === "ClassMethod" ? methodName(member) : null;
1122
+ if (name && HANDLED.has(name)) continue;
1123
+ if (name === "template" && member.type === "ClassMethod" && member.kind === "get") continue;
1124
+ let code = reindent(text(source, member));
1125
+ if (name && handlerNames.has(name)) {
1126
+ const sig = handlerSignature(code, name);
1127
+ code = rewriteHandlerBody(sig.code, sig.eventParam, null).code;
1128
+ } else if (name && listenerTargets.has(name)) {
1129
+ const ev = firstParam(code, name);
1130
+ code = rewriteHandlerBody(code, ev, null, ev ? `${ev}.currentTarget` : "target").code;
1131
+ } else if (member.type === "ClassMethod") code = rewriteHandlerBody(code, null, null).code;
1132
+ if (name && V1_LIFECYCLE.has(name)) code = ` ${todo(`${name} is an Application v1 lifecycle override; ApplicationV2 sizes, submits and builds its header itself. Review it against the V2 method of the same job, or delete it`)}\n${code}`;
1133
+ if (name === "_updateObject") code = ` ${todo("_updateObject is gone on V2; DocumentSheetV2 submits the form itself. Move any shaping into _prepareSubmitData or delete this")}\n${code}`;
1134
+ members.push(applyDialogs(code));
1135
+ }
1136
+ for (const which of ["Item", "Actor"]) {
1137
+ const m = methodOf(cls.node, `_onDrop${which}`);
1138
+ if (!m) continue;
1139
+ members.push(applyDialogs(rewriteDropMethod(reindent(text(source, m)), which).code));
1140
+ }
1141
+ const inline = listeners.actions.filter((a) => a.kind === "inline");
1142
+ for (const a of inline) {
1143
+ const method = `_on${pascal(a.name)}`;
1144
+ const rewritten = applyDialogs(rewriteHandlerBody(a.body ?? "{}", a.param, null).code).trim();
1145
+ const body = rewritten.startsWith("{") ? dedentBlock(rewritten) : `{\n return ${rewritten};\n }`;
1146
+ members.push(` ${a.isAsync ? "async " : ""}${method}(${a.param ?? "event"}, target) ${body}`);
1147
+ }
1148
+ for (const l of listeners.leftovers) members.push(` ${todo(`from activateListeners, line ${l.line}: ${l.text.replace(/\s+/g, " ")}`)}`);
1149
+ return {
1150
+ block: `${isExported(source, cls) ? "export " : ""}class ${cls.name} extends ${base}() {\n${members.join("\n\n")}\n}`,
1151
+ base,
1152
+ actions: actionEntries,
1153
+ templates: [...templates],
1154
+ navs: [...navs],
1155
+ usesDialogV2
1156
+ };
1157
+ }
1158
+ function planSheetFile(relPath, source, opts) {
1159
+ const lang = relPath.endsWith(".ts") ? "ts" : opts.lang;
1160
+ const ast = parseSource(source, lang);
1161
+ const classes = findSheetClasses(ast, source);
1162
+ const notes = unsupportedBases(ast, source).map((u) => `${relPath}:${u.line} ${u.name} extends ${u.superText}; only ActorSheet and ItemSheet are converted, this one stays as it is`);
1163
+ if (classes.length === 0) return {
1164
+ files: [],
1165
+ notes
1166
+ };
1167
+ const dot = relPath.lastIndexOf(".");
1168
+ const to = `${relPath.slice(0, dot)}.v2${relPath.slice(dot)}`;
1169
+ const outputs = classes.map((cls) => ({
1170
+ cls,
1171
+ out: planClass(cls, source, opts.tabIds)
1172
+ }));
1173
+ const header = [`import { ${[...new Set(outputs.map((o) => o.out.base))].join(", ")} } from '@vttforge/core';`, ...importLines(source, lang)];
1174
+ if (outputs.some((o) => o.out.usesDialogV2)) header.push("", "const { DialogV2 } = foundry.applications.api;");
1175
+ const fileSource = `${header.join("\n")}\n\n${outputs.map((o) => o.out.block).join("\n\n")}\n`;
1176
+ const marker = "TODO(migrate): ";
1177
+ const todos = fileSource.split("\n").flatMap((line, i) => {
1178
+ const at = line.indexOf(marker);
1179
+ return at === -1 ? [] : [{
1180
+ line: i + 1,
1181
+ message: line.slice(at + 15).trim()
1182
+ }];
1183
+ });
1184
+ return {
1185
+ files: outputs.map(({ cls, out }) => ({
1186
+ from: relPath,
1187
+ to,
1188
+ className: cls.name,
1189
+ base: out.base,
1190
+ source: fileSource,
1191
+ actions: out.actions,
1192
+ todos,
1193
+ templates: out.templates,
1194
+ tabNavSelectors: out.navs
1195
+ })),
1196
+ notes
1197
+ };
1198
+ }
1199
+ //#endregion
115
1200
  //#region src/migrate/transforms.ts
116
1201
  /**
117
1202
  * The rewrites `vttforge migrate` applies to a v13 source file.
@@ -866,6 +1951,15 @@ async function runMigrate(options) {
866
1951
  });
867
1952
  if (write && result.output !== source) await writeFile(path, result.output, "utf8");
868
1953
  }
1954
+ for (const finding of await runReleaseRules(cwd)) files.push({
1955
+ file: finding.filePath,
1956
+ changes: [],
1957
+ notes: [{
1958
+ line: finding.line ?? 1,
1959
+ rule: finding.ruleId,
1960
+ message: `${finding.message} ${finding.remediation ?? ""}`.trim()
1961
+ }]
1962
+ });
869
1963
  files.sort((a, b) => a.file.localeCompare(b.file));
870
1964
  const report = {
871
1965
  cwd,
@@ -911,12 +2005,124 @@ async function runMigrate(options) {
911
2005
  };
912
2006
  }
913
2007
  }
2008
+ if (options.sheets) report.sheets = await planSheets(cwd, write, options.lang ?? "js");
914
2009
  return report;
915
2010
  }
2011
+ /** Every `.hbs` / `.html` under `templates/`, project-relative. */
2012
+ async function allTemplates(cwd) {
2013
+ const root = join(cwd, "templates");
2014
+ if (!existsSync(root)) return [];
2015
+ const out = [];
2016
+ const visit = async (dir) => {
2017
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
2018
+ const full = join(dir, entry.name);
2019
+ if (entry.isDirectory()) await visit(full);
2020
+ else if (/\.(?:hbs|html)$/.test(entry.name)) out.push(relative(cwd, full));
2021
+ }
2022
+ };
2023
+ await visit(root);
2024
+ return out.sort();
2025
+ }
2026
+ /** Project-relative path for a Foundry template path such as `systems/<id>/templates/x.html`. */
2027
+ function localTemplate(cwd, foundryPath) {
2028
+ const rel = /^(?:systems|modules)\/[^/]+\/(.+)$/.exec(foundryPath)?.[1] ?? foundryPath;
2029
+ return existsSync(join(cwd, rel)) ? rel : null;
2030
+ }
2031
+ async function planSheets(cwd, write, lang) {
2032
+ const files = [];
2033
+ const templates = [];
2034
+ const notes = [];
2035
+ const generated = /* @__PURE__ */ new Map();
2036
+ for await (const path of _internal.walkSourceFiles(cwd)) {
2037
+ const rel = relative(cwd, path);
2038
+ if (/\.v2\.[cm]?[jt]s$/.test(rel)) continue;
2039
+ let raw;
2040
+ try {
2041
+ raw = await readFile(path, "utf8");
2042
+ } catch {
2043
+ continue;
2044
+ }
2045
+ if (!/\b(?:ActorSheet|ItemSheet)\b/.test(raw)) continue;
2046
+ const source = transformSource(raw).output;
2047
+ let probe;
2048
+ try {
2049
+ probe = planSheetFile(rel, source, {
2050
+ lang,
2051
+ tabIds: {}
2052
+ });
2053
+ } catch (error) {
2054
+ const reason = error instanceof Error ? error.message : String(error);
2055
+ notes.push(`${rel} could not be parsed and was skipped: ${reason}`);
2056
+ continue;
2057
+ }
2058
+ notes.push(...probe.notes);
2059
+ if (probe.files.length === 0) continue;
2060
+ let templatePaths = [...new Set(probe.files.flatMap((f) => f.templates))].map((t) => localTemplate(cwd, t)).filter((t) => t !== null);
2061
+ if (templatePaths.length === 0) {
2062
+ const every = await allTemplates(cwd);
2063
+ const other = probe.files[0]?.base === "BaseItemSheet" ? /(?:^|\/)actors?\//i : /(?:^|\/)items?\//i;
2064
+ templatePaths = every.filter((t) => !other.test(t));
2065
+ }
2066
+ const navSelectors = [...new Set(probe.files.flatMap((f) => f.tabNavSelectors))];
2067
+ const tabIds = {};
2068
+ for (const t of templatePaths) {
2069
+ const tpl = await readFile(join(cwd, t), "utf8");
2070
+ for (const nav of navSelectors) {
2071
+ if (tabIds[nav]) continue;
2072
+ const ids = readTabIds(tpl, nav);
2073
+ if (ids.length > 0) tabIds[nav] = ids;
2074
+ }
2075
+ }
2076
+ const plan = planSheetFile(rel, source, {
2077
+ lang,
2078
+ tabIds
2079
+ });
2080
+ for (const f of plan.files) {
2081
+ const { source: out, ...rest } = f;
2082
+ files.push(rest);
2083
+ generated.set(f.to, out);
2084
+ notes.push(`Point registerSheet at ${f.className} from ${f.to} (a written key such as "<id>.${f.base === "BaseActorSheet" ? "actor" : "item"}"), then delete the old class.`);
2085
+ }
2086
+ const actions = plan.files.flatMap((f) => f.actions.map((a) => ({
2087
+ name: a.name,
2088
+ selector: a.selector
2089
+ })));
2090
+ for (const t of templatePaths) {
2091
+ const r = editTemplate(await readFile(join(cwd, t), "utf8"), {
2092
+ actions,
2093
+ navSelectors
2094
+ });
2095
+ if (r.edits.length === 0) continue;
2096
+ templates.push({
2097
+ file: t,
2098
+ edits: r.edits,
2099
+ formRoot: r.formRoot
2100
+ });
2101
+ if (r.formRoot) notes.push(`${t} opens with <form>; the SDK sheet already is one. Remove it once the old class is gone (audit rule 008).`);
2102
+ if (write && r.edits.length > 0) await writeFile(join(cwd, t), r.output, "utf8");
2103
+ }
2104
+ }
2105
+ for (const [to, out] of generated) {
2106
+ const target = join(cwd, to);
2107
+ if (existsSync(target)) {
2108
+ notes.unshift(`${to} exists and was left alone.`);
2109
+ continue;
2110
+ }
2111
+ if (write) {
2112
+ await mkdir(dirname(target), { recursive: true });
2113
+ await writeFile(target, out, "utf8");
2114
+ }
2115
+ }
2116
+ return {
2117
+ files,
2118
+ templates,
2119
+ notes: [...new Set(notes)]
2120
+ };
2121
+ }
916
2122
  /** The report as text: one block per file, edits then notes. */
917
2123
  function formatMigrateReport(report) {
918
2124
  const lines = [];
919
- if (report.files.length === 0 && !report.dataModels) {
2125
+ if (report.files.length === 0 && !report.dataModels && !report.sheets) {
920
2126
  lines.push("Nothing to migrate. The project already reads as v14.");
921
2127
  return `${lines.join("\n")}\n`;
922
2128
  }
@@ -936,6 +2142,24 @@ function formatMigrateReport(report) {
936
2142
  if (dm.registration) lines.push("", "Register the models at init:", ...dm.registration.split("\n").map((l) => ` ${l}`));
937
2143
  for (const n of dm.notes) lines.push(` needs a decision: ${n}`);
938
2144
  }
2145
+ if (report.sheets) {
2146
+ const s = report.sheets;
2147
+ const targets = [...new Set(s.files.map((f) => f.to))];
2148
+ lines.push("", report.written ? `Wrote ${targets.length} sheet file(s) on the SDK bases:` : `Would write ${targets.length} sheet file(s) on the SDK bases:`);
2149
+ for (const f of s.files) {
2150
+ lines.push(` ${f.to}: ${f.className} extends ${f.base}()`);
2151
+ for (const a of f.actions) lines.push(` action ${a.name} ← ${a.selector} (${a.method})`);
2152
+ for (const t of f.todos) lines.push(` ${t.line}: needs a decision: ${t.message}`);
2153
+ }
2154
+ if (s.templates.length > 0) {
2155
+ lines.push("", report.written ? "Edited templates:" : "Would edit templates:");
2156
+ for (const t of s.templates) {
2157
+ lines.push(` ${t.file}`);
2158
+ for (const e of t.edits) lines.push(` ${e.line}: ${oneLine(e.before)}`, ` ${" ".repeat(String(e.line).length)} → ${oneLine(e.after)}`);
2159
+ }
2160
+ }
2161
+ for (const n of s.notes) lines.push(` needs a decision: ${n}`);
2162
+ }
939
2163
  return `${lines.join("\n")}\n`;
940
2164
  }
941
2165
  function oneLine(text) {
@@ -961,7 +2185,8 @@ async function runMigrateCommand(options = {}) {
961
2185
  write: options.write === true,
962
2186
  dataModels: options.dataModels === true,
963
2187
  style: options.style,
964
- lang: options.lang
2188
+ lang: options.lang,
2189
+ sheets: options.sheets === true
965
2190
  });
966
2191
  out(options.json ? `${JSON.stringify(report, null, 2)}\n` : formatMigrateReport(report));
967
2192
  return {
@@ -1187,7 +2412,7 @@ const audit = defineCommand({
1187
2412
  const migrate = defineCommand({
1188
2413
  meta: {
1189
2414
  name: "migrate",
1190
- description: "Rewrite a v13 system or module for Foundry v14 (preview by default)"
2415
+ description: "Rewrite a v13 system or module for Foundry v14 (preview by default); --data-models and --sheets write the v16 replacements"
1191
2416
  },
1192
2417
  args: {
1193
2418
  path: {
@@ -1218,7 +2443,12 @@ const migrate = defineCommand({
1218
2443
  lang: {
1219
2444
  type: "string",
1220
2445
  default: "js",
1221
- description: "For --data-models: \"js\" writes .mjs, \"ts\" writes .ts"
2446
+ description: "For --data-models and --sheets: \"js\" writes .mjs, \"ts\" writes .ts"
2447
+ },
2448
+ sheets: {
2449
+ type: "boolean",
2450
+ default: false,
2451
+ description: "Also write a V2 sheet file (on the SDK bases) next to each Application v1 sheet class, and the data-action attributes its templates need"
1222
2452
  }
1223
2453
  },
1224
2454
  async run({ args }) {
@@ -1229,7 +2459,8 @@ const migrate = defineCommand({
1229
2459
  json: Boolean(args.json),
1230
2460
  dataModels: Boolean(args["data-models"]),
1231
2461
  style: String(args.style) === "sdk" ? "sdk" : "plain",
1232
- lang: String(args.lang) === "ts" ? "ts" : "js"
2462
+ lang: String(args.lang) === "ts" ? "ts" : "js",
2463
+ sheets: Boolean(args.sheets)
1233
2464
  });
1234
2465
  process.exitCode = exitCode;
1235
2466
  } catch (error) {