@datarails-ai/dr-appspace-cli 0.12.74 → 0.12.76

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +16 -2
  2. package/dist/cli.js +783 -132
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -13,7 +13,7 @@ import { fileURLToPath as fileURLToPath6 } from "url";
13
13
  // package.json
14
14
  var package_default = {
15
15
  name: "@datarails-ai/dr-appspace-cli",
16
- version: "0.12.74",
16
+ version: "0.12.76",
17
17
  description: "Datarails App Space CLI \u2014 build, try, push and publish App Space apps",
18
18
  type: "module",
19
19
  engines: {
@@ -57,7 +57,7 @@ var package_default = {
57
57
  };
58
58
 
59
59
  // src/buildInfo.ts
60
- var BUILD_TIME = "2026-11-08T22:36:01.631Z";
60
+ var BUILD_TIME = "2026-11-09T19:41:45.642Z";
61
61
  function formatBuildTime(iso) {
62
62
  if (iso === "") return "";
63
63
  const d = new Date(iso);
@@ -1102,18 +1102,18 @@ async function loginAs(host, operatorAccessToken, userId, options) {
1102
1102
  throw new Error("jwt loginas parse: expected object");
1103
1103
  }
1104
1104
  const obj5 = raw;
1105
- const access = typeof obj5["access"] === "string" ? obj5["access"] : "";
1105
+ const access2 = typeof obj5["access"] === "string" ? obj5["access"] : "";
1106
1106
  const refresh = typeof obj5["refresh"] === "string" ? obj5["refresh"] : "";
1107
- if (access === "") {
1107
+ if (access2 === "") {
1108
1108
  throw new Error("jwt loginas: empty access token");
1109
1109
  }
1110
1110
  let expiresAt;
1111
1111
  try {
1112
- expiresAt = decodeJwtExpiration(access);
1112
+ expiresAt = decodeJwtExpiration(access2);
1113
1113
  } catch (err) {
1114
1114
  throw new Error(`jwt loginas: ${msgOf3(err)}`);
1115
1115
  }
1116
- return { access, refresh, expiresAt, user: obj5["user"] };
1116
+ return { access: access2, refresh, expiresAt, user: obj5["user"] };
1117
1117
  }
1118
1118
  async function exchangeApiKey(host, apiKey, options) {
1119
1119
  const key = apiKey.trim();
@@ -1158,17 +1158,17 @@ async function exchangeApiKey(host, apiKey, options) {
1158
1158
  if (raw === null || typeof raw !== "object") {
1159
1159
  throw new Error("api-key exchange parse: expected object");
1160
1160
  }
1161
- const access = raw["access_token"];
1162
- if (typeof access !== "string" || access === "") {
1161
+ const access2 = raw["access_token"];
1162
+ if (typeof access2 !== "string" || access2 === "") {
1163
1163
  throw new Error("api-key exchange: empty access token");
1164
1164
  }
1165
1165
  let expiresAt;
1166
1166
  try {
1167
- expiresAt = decodeJwtExpiration(access);
1167
+ expiresAt = decodeJwtExpiration(access2);
1168
1168
  } catch (err) {
1169
1169
  throw new Error(`api-key exchange: ${msgOf3(err)}`);
1170
1170
  }
1171
- return { access, expiresAt };
1171
+ return { access: access2, expiresAt };
1172
1172
  }
1173
1173
  function apiKeyFingerprint(apiKey) {
1174
1174
  return createHash("sha256").update(apiKey.trim()).digest("hex").slice(0, 32);
@@ -1577,15 +1577,15 @@ var AuthorizedClient = class _AuthorizedClient {
1577
1577
  * `whoami` precedent.
1578
1578
  */
1579
1579
  getCurrentOrgId() {
1580
- const access = this._session.jwtAccess ?? "";
1581
- if (access === "") {
1580
+ const access2 = this._session.jwtAccess ?? "";
1581
+ if (access2 === "") {
1582
1582
  throw new Error(
1583
1583
  `no JWT stored for ${this._serverKey}; run dr-appspace login --server ${this._serverKey} to refresh`
1584
1584
  );
1585
1585
  }
1586
1586
  let claims;
1587
1587
  try {
1588
- claims = decodeJwtClaims(access);
1588
+ claims = decodeJwtClaims(access2);
1589
1589
  } catch (err) {
1590
1590
  const msg = err instanceof Error ? err.message : String(err);
1591
1591
  throw new Error(`decode JWT for ${this._serverKey}: ${msg}`);
@@ -2023,9 +2023,9 @@ var AuthorizedClient = class _AuthorizedClient {
2023
2023
  * mintJwt inside ensureValidJwt pick the right path based on what's set.
2024
2024
  */
2025
2025
  async ensureFreshAuth(bufferMs, signal) {
2026
- const access = this._session.jwtAccess ?? "";
2026
+ const access2 = this._session.jwtAccess ?? "";
2027
2027
  const refresh = this._session.jwtRefresh ?? "";
2028
- if (access === "" && refresh === "" && !usesApiKey(this._session)) {
2028
+ if (access2 === "" && refresh === "" && !usesApiKey(this._session)) {
2029
2029
  return;
2030
2030
  }
2031
2031
  try {
@@ -2966,8 +2966,8 @@ async function connect(opts) {
2966
2966
  email: client.email,
2967
2967
  claims() {
2968
2968
  try {
2969
- const access = client.session.jwtAccess ?? "";
2970
- return access === "" ? null : decodeJwtClaims(access);
2969
+ const access2 = client.session.jwtAccess ?? "";
2970
+ return access2 === "" ? null : decodeJwtClaims(access2);
2971
2971
  } catch {
2972
2972
  return null;
2973
2973
  }
@@ -3123,11 +3123,11 @@ function conflictGuidance(body) {
3123
3123
  return lines;
3124
3124
  }
3125
3125
  function hostsNeedingApproval(body) {
3126
- const isObj5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3127
- const found = isObj5(body) && isObj5(body["detail"]) ? body["detail"] : body;
3128
- if (!isObj5(found) || found["error"] !== "http_hosts_need_approval") return void 0;
3126
+ const isObj6 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3127
+ const found = isObj6(body) && isObj6(body["detail"]) ? body["detail"] : body;
3128
+ if (!isObj6(found) || found["error"] !== "http_hosts_need_approval") return void 0;
3129
3129
  const hosts = Array.isArray(found["hosts"]) ? found["hosts"].filter((h) => typeof h === "string") : [];
3130
- const entries = Array.isArray(found["entries"]) ? found["entries"].filter(isObj5).map((e) => ({
3130
+ const entries = Array.isArray(found["entries"]) ? found["entries"].filter(isObj6).map((e) => ({
3131
3131
  name: String(e["name"] ?? "?"),
3132
3132
  host: String(e["host"] ?? "?"),
3133
3133
  change: String(e["change"] ?? "needs approval")
@@ -5054,8 +5054,8 @@ function pyLiteral(value, { indent: indent2 = 0, width = DEFAULT_WIDTH, callable
5054
5054
  function writeSpec(data, { library = null, name = "SPEC", width = DEFAULT_WIDTH } = {}) {
5055
5055
  const problems = [];
5056
5056
  const table = tableOf(data);
5057
- const constants = /* @__PURE__ */ new Map();
5058
- const hoisted = hoist(table, [], constants, null);
5057
+ const constants2 = /* @__PURE__ */ new Map();
5058
+ const hoisted = hoist(table, [], constants2, null);
5059
5059
  const callables = /* @__PURE__ */ new Set();
5060
5060
  let text4 = null;
5061
5061
  try {
@@ -5076,7 +5076,7 @@ function writeSpec(data, { library = null, name = "SPEC", width = DEFAULT_WIDTH
5076
5076
  });
5077
5077
  }
5078
5078
  if (unknown.length > 0) return { text: null, imports: [], constants: [], problems };
5079
- const rows2 = [...constants].map(([constant, held]) => ({
5079
+ const rows2 = [...constants2].map(([constant, held]) => ({
5080
5080
  name: constant,
5081
5081
  value: held,
5082
5082
  text: `${constant} = ${pyLiteral(held, { indent: 0, width, callables, pointer: `/${constant}` })}`
@@ -5093,11 +5093,11 @@ function writeSpec(data, { library = null, name = "SPEC", width = DEFAULT_WIDTH
5093
5093
  if (problems.length > 0) return { text: null, imports: [], constants: [], problems };
5094
5094
  return { text: text4, imports, constants: rows2, problems };
5095
5095
  }
5096
- function writeModule({ docstring = null, imports = [], constants = [], tables = [], body = null } = {}) {
5096
+ function writeModule({ docstring = null, imports = [], constants: constants2 = [], tables = [], body = null } = {}) {
5097
5097
  const blocks = [];
5098
5098
  if (docstring !== null) blocks.push(asDocstring(docstring));
5099
5099
  if (imports.length > 0) blocks.push(imports.join("\n"));
5100
- if (constants.length > 0) blocks.push(constants.join("\n"));
5100
+ if (constants2.length > 0) blocks.push(constants2.join("\n"));
5101
5101
  for (const table of tables) blocks.push(table.replace(/\n+$/, ""));
5102
5102
  if (body !== null) blocks.push(body.replace(/\n+$/, ""));
5103
5103
  let text4 = "";
@@ -5237,34 +5237,34 @@ function pyString(text4) {
5237
5237
  }
5238
5238
  return out + quote;
5239
5239
  }
5240
- function hoist(value, path3, constants, key) {
5240
+ function hoist(value, path3, constants2, key) {
5241
5241
  if (Array.isArray(value)) {
5242
- const next = value.map((item, index) => hoist(item, [...path3, String(index)], constants, null));
5243
- return atLiteral(next, path3, constants, key);
5242
+ const next = value.map((item, index) => hoist(item, [...path3, String(index)], constants2, null));
5243
+ return atLiteral(next, path3, constants2, key);
5244
5244
  }
5245
5245
  if (isPlainObject(value) && !("$callable" in value) && !("$const" in value)) {
5246
5246
  const next = {};
5247
- for (const [name, held] of Object.entries(value)) next[name] = hoist(held, [...path3, name], constants, name);
5248
- return atLiteral(next, path3, constants, key);
5247
+ for (const [name, held] of Object.entries(value)) next[name] = hoist(held, [...path3, name], constants2, name);
5248
+ return atLiteral(next, path3, constants2, key);
5249
5249
  }
5250
5250
  return value;
5251
5251
  }
5252
- function atLiteral(value, path3, constants, key) {
5252
+ function atLiteral(value, path3, constants2, key) {
5253
5253
  if (path3.length === 0) return value;
5254
5254
  if (numbersIn(value) < MIN_NUMBERS) return value;
5255
5255
  if (key !== null && LITERAL_CONTEXT.test(`"${key}": `)) return value;
5256
- return nameNumbers(value, path3, constants);
5256
+ return nameNumbers(value, path3, constants2);
5257
5257
  }
5258
- function nameNumbers(value, path3, constants) {
5258
+ function nameNumbers(value, path3, constants2) {
5259
5259
  if (typeof value === "number") {
5260
- const name = constantName(path3, constants);
5261
- constants.set(name, value);
5260
+ const name = constantName(path3, constants2);
5261
+ constants2.set(name, value);
5262
5262
  return { $const: name };
5263
5263
  }
5264
- if (Array.isArray(value)) return value.map((item, index) => nameNumbers(item, [...path3, String(index)], constants));
5264
+ if (Array.isArray(value)) return value.map((item, index) => nameNumbers(item, [...path3, String(index)], constants2));
5265
5265
  if (isPlainObject(value) && !("$callable" in value) && !("$const" in value)) {
5266
5266
  const out = {};
5267
- for (const [key, held] of Object.entries(value)) out[key] = nameNumbers(held, [...path3, key], constants);
5267
+ for (const [key, held] of Object.entries(value)) out[key] = nameNumbers(held, [...path3, key], constants2);
5268
5268
  return out;
5269
5269
  }
5270
5270
  return value;
@@ -5278,11 +5278,11 @@ function numbersIn(value) {
5278
5278
  }
5279
5279
  return 0;
5280
5280
  }
5281
- function constantName(path3, constants) {
5281
+ function constantName(path3, constants2) {
5282
5282
  const base = path3.join("_").replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").toUpperCase();
5283
5283
  const start = /^[A-Z_]/.test(base) ? base : `N_${base}`;
5284
- if (!constants.has(start)) return start;
5285
- for (let n = 2; ; n += 1) if (!constants.has(`${start}_${n}`)) return `${start}_${n}`;
5284
+ if (!constants2.has(start)) return start;
5285
+ for (let n = 2; ; n += 1) if (!constants2.has(`${start}_${n}`)) return `${start}_${n}`;
5286
5286
  }
5287
5287
  function asDocstring(text4) {
5288
5288
  const body = String(text4).replace(/\\/g, "\\\\").replace(/"""/g, '\\"\\"\\"').replace(/\s+$/, "");
@@ -10973,17 +10973,17 @@ function handlerFile(contract, handlerName, written, library, transforms = {}) {
10973
10973
  "contract, not this file."
10974
10974
  ].join("\n");
10975
10975
  const imports = ["from appspace import widgets", ...written.imports].sort(natural3);
10976
- const constants = [];
10976
+ const constants2 = [];
10977
10977
  if (library !== null && typeof library.version === "string") {
10978
- constants.push("# The release of the hook library this table was built against.");
10979
- constants.push(`LIBRARY_VERSION = ${pyString2(library.version)}`);
10978
+ constants2.push("# The release of the hook library this table was built against.");
10979
+ constants2.push(`LIBRARY_VERSION = ${pyString2(library.version)}`);
10980
10980
  }
10981
- for (const row of written.constants) constants.push(row.text);
10981
+ for (const row of written.constants) constants2.push(row.text);
10982
10982
  const carried = Object.keys(transforms).length > 0;
10983
10983
  return writeModule({
10984
10984
  docstring,
10985
10985
  imports,
10986
- constants,
10986
+ constants: constants2,
10987
10987
  tables: carried ? [written.text, transformsTable(transforms)] : [written.text],
10988
10988
  body: [
10989
10989
  "def handle(ctx, payload):",
@@ -17241,9 +17241,9 @@ function whereProblems(where2, table, pointer2, who, { platform = false, noColum
17241
17241
  const problems = [];
17242
17242
  const say = (key, message, code = "app_model_mismatch") => problems.push({ code, pointer: pointer2(key), message: `${who} ${message}` });
17243
17243
  for (const key of Object.keys(where2).sort()) {
17244
- const sep7 = key.indexOf("__");
17245
- const column = sep7 < 0 ? key : key.slice(0, sep7);
17246
- const op = sep7 < 0 ? "eq" : key.slice(sep7 + 2);
17244
+ const sep8 = key.indexOf("__");
17245
+ const column = sep8 < 0 ? key : key.slice(0, sep8);
17246
+ const op = sep8 < 0 ? "eq" : key.slice(sep8 + 2);
17247
17247
  const value = where2[key];
17248
17248
  if (!WHERE_OPS.includes(op)) {
17249
17249
  say(key, `filters with "${key}", and "${op}" is no operator a where knows: ${WHERE_OPS.join(", ")}`);
@@ -17462,7 +17462,7 @@ function measuredSummary(row) {
17462
17462
  ];
17463
17463
  }
17464
17464
  const body = ["def handle(ctx, payload):", " del payload", ' table = ctx.data.table(HANDLER["table"])', " answer = {}", ...loop, " return answer"].join("\n");
17465
- const constants = [assignment("MEASURES", measures, Object.keys(measures))];
17465
+ const constants2 = [assignment("MEASURES", measures, Object.keys(measures))];
17466
17466
  if (kinds.length === 0) {
17467
17467
  return {
17468
17468
  docstring: `Answer each tile on the page with a count of the events of ${row.table}.
@@ -17474,7 +17474,7 @@ wrote it \u2014 so none counts an event of a row this caller may not see.
17474
17474
 
17475
17475
  Generated by dashboard-kit/contract compile from contract.json \u2014 edit the
17476
17476
  contract, not this file.`,
17477
- constants,
17477
+ constants: constants2,
17478
17478
  body
17479
17479
  };
17480
17480
  }
@@ -17488,7 +17488,7 @@ may not see. \`$today\` and its siblings are UTC. An average over no rows is
17488
17488
  None, which a stat shows as a dash.
17489
17489
 
17490
17490
  ` + (events ? "A count of events is what the platform recorded for rows this caller may\nread \u2014 each event its route stamped with the handler that wrote it.\n\n" : "") + "Generated by dashboard-kit/contract compile from contract.json \u2014 edit the\ncontract, not this file.",
17491
- constants,
17491
+ constants: constants2,
17492
17492
  body
17493
17493
  };
17494
17494
  }
@@ -17655,8 +17655,8 @@ function notOwnLines(row, id, verb, indent2) {
17655
17655
  function singletonSave(row, table) {
17656
17656
  const enums = enumsOf(row, table);
17657
17657
  const refs = refsOf(row, table);
17658
- const constants = Object.keys(enums).length > 0 ? [assignment("ENUMS", enums, Object.keys(enums))] : [];
17659
- if (Object.keys(refs).length > 0) constants.push(assignment("REFS", refs, Object.keys(refs)));
17658
+ const constants2 = Object.keys(enums).length > 0 ? [assignment("ENUMS", enums, Object.keys(enums))] : [];
17659
+ if (Object.keys(refs).length > 0) constants2.push(assignment("REFS", refs, Object.keys(refs)));
17660
17660
  return {
17661
17661
  docstring: `Save the ${singular(row.table)}: the table holds one row, so there is no id to send.
17662
17662
 
@@ -17668,7 +17668,7 @@ rather than written.
17668
17668
  Generated by dashboard-kit/contract compile from contract.json \u2014 edit the
17669
17669
  contract, not this file.`,
17670
17670
  imports: Object.keys(refs).length > 0 ? ["import uuid"] : [],
17671
- constants,
17671
+ constants: constants2,
17672
17672
  body: [
17673
17673
  "def handle(ctx, payload):",
17674
17674
  ...collectRow(row, enums),
@@ -17948,8 +17948,8 @@ contract, not this file.`,
17948
17948
  const enums = enumsOf(row, table);
17949
17949
  const refs = refsOf(row, table);
17950
17950
  const guarded = named5(row.guard);
17951
- const constants = Object.keys(enums).length > 0 ? [assignment("ENUMS", enums, Object.keys(enums))] : [];
17952
- if (Object.keys(refs).length > 0) constants.push(assignment("REFS", refs, Object.keys(refs)));
17951
+ const constants2 = Object.keys(enums).length > 0 ? [assignment("ENUMS", enums, Object.keys(enums))] : [];
17952
+ if (Object.keys(refs).length > 0) constants2.push(assignment("REFS", refs, Object.keys(refs)));
17953
17953
  const guardDoc = guarded ? `
17954
17954
 
17955
17955
  \`guard\` holds an edit to one state: only a row that is still ${row.guard} may be
@@ -17966,7 +17966,7 @@ is a column anyone may set.${guardDoc}
17966
17966
  Generated by dashboard-kit/contract compile from contract.json \u2014 edit the
17967
17967
  contract, not this file.`,
17968
17968
  imports: Object.keys(refs).length > 0 || guarded ? ["import uuid"] : [],
17969
- constants,
17969
+ constants: constants2,
17970
17970
  body: [
17971
17971
  "def handle(ctx, payload):",
17972
17972
  ...collectRow(row, enums),
@@ -18005,9 +18005,9 @@ contract, not this file.`,
18005
18005
  submit: (name, row, table, model) => {
18006
18006
  const enums = enumsOf(row, table);
18007
18007
  const decimals = decimalsOf(row, table);
18008
- const constants = [];
18009
- if (Object.keys(enums).length > 0) constants.push(assignment("ENUMS", enums, Object.keys(enums)));
18010
- if (decimals.length > 0) constants.push(`DECIMALS = ${pyLiteral(decimals)}`);
18008
+ const constants2 = [];
18009
+ if (Object.keys(enums).length > 0) constants2.push(assignment("ENUMS", enums, Object.keys(enums)));
18010
+ if (decimals.length > 0) constants2.push(`DECIMALS = ${pyLiteral(decimals)}`);
18011
18011
  const lines = ["def handle(ctx, payload):", ...collectRow(row, enums)];
18012
18012
  if (decimals.length > 0) {
18013
18013
  lines.push(
@@ -18021,17 +18021,17 @@ contract, not this file.`,
18021
18021
  }
18022
18022
  const refs = refsOf(row, table);
18023
18023
  if (Object.keys(refs).length > 0) {
18024
- constants.push(assignment("REFS", refs, Object.keys(refs)));
18024
+ constants2.push(assignment("REFS", refs, Object.keys(refs)));
18025
18025
  lines.push(...refLines());
18026
18026
  }
18027
18027
  const parent = linkedParent(row, model);
18028
18028
  if (parent !== null) {
18029
- constants.push(`PARENT = ${pyString(parent)}`);
18029
+ constants2.push(`PARENT = ${pyString(parent)}`);
18030
18030
  lines.push(...parentLines(row, parent, { missing: `{"error": ${pyString(`${row.by} is required`)}}`, invisible: `{"error": ${pyString(`${row.by} names no ${singular(parent)} this app can see`)}}` }));
18031
18031
  lines.push(' row[HANDLER["by"]] = parent_id');
18032
18032
  }
18033
18033
  if (isPlainObject8(row.requires)) {
18034
- constants.push(...requiresConstants(row, model));
18034
+ constants2.push(...requiresConstants(row, model));
18035
18035
  lines.push(...requiresLines(row, "saved"));
18036
18036
  }
18037
18037
  if (isPlainObject8(row.fixed) && Object.keys(row.fixed).length > 0) lines.push(' row.update(HANDLER["fixed"])');
@@ -18050,7 +18050,7 @@ browser could choose is a status anyone can choose.${linkDoc}${requiresDoc(row)}
18050
18050
  Generated by dashboard-kit/contract compile from contract.json \u2014 edit the
18051
18051
  contract, not this file.`,
18052
18052
  imports: [...parent !== null || Object.keys(refs).length > 0 ? ["import uuid"] : [], ...decimals.length > 0 ? ["from decimal import Decimal, InvalidOperation"] : []],
18053
- constants,
18053
+ constants: constants2,
18054
18054
  body: lines.join("\n")
18055
18055
  };
18056
18056
  },
@@ -21013,7 +21013,7 @@ function mergeData(contract, drafts, base, problems, did, merge = false) {
21013
21013
  const setBy = /* @__PURE__ */ new Map();
21014
21014
  const declared = (key) => /* @__PURE__ */ new Set([...Object.keys(isObj(data[key]) ? data[key] : {}), ...drafts.flatMap((draft) => Object.keys(draft[key] ?? {}))]);
21015
21015
  const taken = { reads: declared("reads"), datasets: declared("datasets") };
21016
- const rename2 = (key, name) => {
21016
+ const rename3 = (key, name) => {
21017
21017
  let fresh = `${name}_2`;
21018
21018
  for (let n = 3; taken[key].has(fresh); n += 1) fresh = `${name}_${String(n)}`;
21019
21019
  taken[key].add(fresh);
@@ -21048,7 +21048,7 @@ function mergeData(contract, drafts, base, problems, did, merge = false) {
21048
21048
  );
21049
21049
  continue;
21050
21050
  }
21051
- const fresh = rename2(key, name);
21051
+ const fresh = rename3(key, name);
21052
21052
  (key === "reads" ? readAs : datasetAs).set(name, fresh);
21053
21053
  setBy.set(`${key}.${fresh}`, { name: draft.name, value: entry });
21054
21054
  into[fresh] = clone4(entry);
@@ -21138,10 +21138,10 @@ function canonical2(value) {
21138
21138
  }
21139
21139
  function frame(skeleton, pages, appId) {
21140
21140
  const described = skeleton.app.description === void 0 ? {} : { description: skeleton.app.description };
21141
- const rendered = rendererOf2({ app: skeleton.app }) === "runtime" ? { renderer: skeleton.app.renderer } : {};
21141
+ const rendered2 = rendererOf2({ app: skeleton.app }) === "runtime" ? { renderer: skeleton.app.renderer } : {};
21142
21142
  return {
21143
21143
  v: 1,
21144
- app: { id: appId, name: skeleton.app.name, ...described, kind: "dashboard", ...rendered, routes: pages.map((plan) => plan.address) },
21144
+ app: { id: appId, name: skeleton.app.name, ...described, kind: "dashboard", ...rendered2, routes: pages.map((plan) => plan.address) },
21145
21145
  pages: pages.map(pageFrom),
21146
21146
  elements: {},
21147
21147
  data: { source: "static", widgets: {} }
@@ -25320,24 +25320,24 @@ function stripPositional(contract, { keepTree = true, order: order2 } = {}) {
25320
25320
  const ordered2 = order2 === "keys" ? uids : rank !== null ? stated2(uids) : documentOrder(elements, uids, pagesByPath.get(page));
25321
25321
  ordered2.forEach((uid, index) => renamed.set(uid, `${page}#${index + 1}`));
25322
25322
  }
25323
- const rename2 = (uid) => typeof uid === "string" && renamed.has(uid) ? renamed.get(uid) : uid;
25323
+ const rename3 = (uid) => typeof uid === "string" && renamed.has(uid) ? renamed.get(uid) : uid;
25324
25324
  const rekeyed = {};
25325
25325
  for (const [uid, element] of Object.entries(elements)) {
25326
- const next = rename2(uid);
25326
+ const next = rename3(uid);
25327
25327
  for (const key of POSITIONAL_KEYS) delete element[key];
25328
25328
  element.uid = next;
25329
- if (element.parent !== void 0) element.parent = element.parent === null ? null : rename2(element.parent);
25330
- if (Array.isArray(element.children)) element.children = element.children.map(rename2).sort(natural3);
25329
+ if (element.parent !== void 0) element.parent = element.parent === null ? null : rename3(element.parent);
25330
+ if (Array.isArray(element.children)) element.children = element.children.map(rename3).sort(natural3);
25331
25331
  if (isPlainObject10(element.grid)) for (const key of POSITIONAL_GRID_KEYS) delete element.grid[key];
25332
25332
  rekeyed[next] = element;
25333
25333
  }
25334
25334
  out.elements = sortKeys2(rekeyed);
25335
25335
  for (const page of Array.isArray(out.pages) ? out.pages : []) {
25336
25336
  if (!Array.isArray(page.tree)) continue;
25337
- if (keepTree) page.tree = page.tree.map(rename2).sort(natural3);
25337
+ if (keepTree) page.tree = page.tree.map(rename3).sort(natural3);
25338
25338
  else delete page.tree;
25339
25339
  }
25340
- if (out.bindings !== void 0) out.bindings = renameDeep(out.bindings, rename2);
25340
+ if (out.bindings !== void 0) out.bindings = renameDeep(out.bindings, rename3);
25341
25341
  for (const problem6 of Array.isArray(out.problems) ? out.problems : []) {
25342
25342
  if (typeof problem6.where === "string") problem6.where = fileOf(problem6.where);
25343
25343
  }
@@ -25409,12 +25409,12 @@ function rootsAmong(elements, uids) {
25409
25409
  }
25410
25410
  return uids.filter((uid) => !claimed.has(uid) && (elements[uid]?.parent ?? null) === null);
25411
25411
  }
25412
- function renameDeep(value, rename2) {
25413
- if (typeof value === "string") return rename2(value);
25414
- if (Array.isArray(value)) return value.map((item) => renameDeep(item, rename2));
25412
+ function renameDeep(value, rename3) {
25413
+ if (typeof value === "string") return rename3(value);
25414
+ if (Array.isArray(value)) return value.map((item) => renameDeep(item, rename3));
25415
25415
  if (isPlainObject10(value)) {
25416
25416
  const out = {};
25417
- for (const [key, held] of Object.entries(value)) out[key] = renameDeep(held, rename2);
25417
+ for (const [key, held] of Object.entries(value)) out[key] = renameDeep(held, rename3);
25418
25418
  return out;
25419
25419
  }
25420
25420
  return value;
@@ -34870,13 +34870,663 @@ function registerLogsCommand(parent) {
34870
34870
  });
34871
34871
  }
34872
34872
 
34873
+ // src/commands/appspace/migrate.ts
34874
+ import { constants } from "fs";
34875
+ import { access, lstat as lstat2, readFile as readFile11, realpath, rename as rename2, rm as rm5, writeFile as writeFile9 } from "fs/promises";
34876
+ import { basename as basename2, dirname as dirname9, join as join17, sep as sep5 } from "path";
34877
+ var MIGRATE_ROUTE = "/apps/migrate-preview";
34878
+ var RUNTIMES_NOW = [1];
34879
+ var MigrateRefused = class extends Error {
34880
+ };
34881
+ function isObj5(value) {
34882
+ return typeof value === "object" && value !== null && !Array.isArray(value);
34883
+ }
34884
+ function targetRuntime(value) {
34885
+ if (value === void 0) return 1;
34886
+ const n = /^\d+$/.test(value.trim()) ? Number(value.trim()) : NaN;
34887
+ if (n === 2) {
34888
+ throw new MigrateRefused(
34889
+ "--to-runtime 2 is not available: runtime 2 (no ctx.data, ctx.state or ctx.financeos) is proposed (DR-58160) and the platform runs runtime 1 only, so the server cannot migrate to it. Run migrate with no --to-runtime: it moves the names inside runtime 1."
34890
+ );
34891
+ }
34892
+ if (!RUNTIMES_NOW.includes(n)) {
34893
+ throw new MigrateRefused(
34894
+ `--to-runtime ${JSON.stringify(value)} is not a runtime migrate knows. Use 1 (the default).`
34895
+ );
34896
+ }
34897
+ return n;
34898
+ }
34899
+ var DIFF_PATH_RE = /^(handlers|lib)\/[A-Za-z0-9_][A-Za-z0-9_-]{0,127}\.py$/;
34900
+ var HUNK_RE = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
34901
+ var NO_NEWLINE = "\";
34902
+ function linesOf(text4) {
34903
+ const parts = text4.split(/(?<=\n)/);
34904
+ return parts.length > 0 && parts[parts.length - 1] === "" ? parts.slice(0, -1) : parts;
34905
+ }
34906
+ function applyDiff(diff, sent) {
34907
+ const lines = linesOf(diff);
34908
+ const hunks = /* @__PURE__ */ new Map();
34909
+ const invalid = () => new MigrateRefused("the diff from the server is not valid.");
34910
+ let current = null;
34911
+ for (let n = 0; n < lines.length; ) {
34912
+ const line2 = lines[n];
34913
+ if (line2.startsWith("--- a/")) {
34914
+ const next = lines[n + 1] ?? "";
34915
+ const path3 = line2.slice("--- a/".length).replace(/\n$/, "");
34916
+ if (next.replace(/\n$/, "") !== `+++ b/${path3}`) {
34917
+ throw new MigrateRefused(`the diff from the server is not valid near ${JSON.stringify(path3)}.`);
34918
+ }
34919
+ if (!DIFF_PATH_RE.test(path3) || !Object.prototype.hasOwnProperty.call(sent, path3)) {
34920
+ throw new MigrateRefused(
34921
+ `the diff from the server names ${JSON.stringify(path3)}, which is not a handler or lib file that was sent.`
34922
+ );
34923
+ }
34924
+ if (hunks.has(path3)) throw new MigrateRefused(`the diff from the server names ${path3} two times.`);
34925
+ current = [];
34926
+ hunks.set(path3, current);
34927
+ n += 2;
34928
+ continue;
34929
+ }
34930
+ const header = HUNK_RE.exec(line2);
34931
+ if (header === null || current === null) throw invalid();
34932
+ const hunk = {
34933
+ oldStart: Number(header[1]),
34934
+ oldCount: header[2] === void 0 ? 1 : Number(header[2]),
34935
+ newCount: header[4] === void 0 ? 1 : Number(header[4]),
34936
+ lines: []
34937
+ };
34938
+ current.push(hunk);
34939
+ n += 1;
34940
+ let oldLeft = hunk.oldCount;
34941
+ let newLeft = hunk.newCount;
34942
+ while (oldLeft > 0 || newLeft > 0) {
34943
+ const body = lines[n];
34944
+ if (body === void 0) throw invalid();
34945
+ if (body[0] === " ") {
34946
+ oldLeft -= 1;
34947
+ newLeft -= 1;
34948
+ } else if (body[0] === "-") oldLeft -= 1;
34949
+ else if (body[0] === "+") newLeft -= 1;
34950
+ else throw invalid();
34951
+ if (oldLeft < 0 || newLeft < 0) throw invalid();
34952
+ hunk.lines.push(body);
34953
+ n += 1;
34954
+ if (lines[n] !== void 0 && lines[n].replace(/\n$/, "") === NO_NEWLINE) {
34955
+ hunk.lines[hunk.lines.length - 1] = body.replace(/\n$/, "");
34956
+ n += 1;
34957
+ }
34958
+ }
34959
+ }
34960
+ const out = {};
34961
+ for (const [path3, fileHunks] of hunks) {
34962
+ const old = linesOf(sent[path3]);
34963
+ const result = [];
34964
+ let cursor = 0;
34965
+ for (const one of fileHunks) {
34966
+ const start = one.oldCount === 0 ? one.oldStart : one.oldStart - 1;
34967
+ if (start < cursor || start > old.length) {
34968
+ throw new MigrateRefused(`the diff from the server does not fit ${path3}.`);
34969
+ }
34970
+ result.push(...old.slice(cursor, start));
34971
+ let at = start;
34972
+ let removed = 0;
34973
+ let added = 0;
34974
+ for (const line2 of one.lines) {
34975
+ const body = line2.slice(1);
34976
+ if (line2[0] === "+") {
34977
+ result.push(body);
34978
+ added += 1;
34979
+ continue;
34980
+ }
34981
+ if (old[at] !== body) {
34982
+ throw new MigrateRefused(`the diff from the server does not fit ${path3} at line ${String(at + 1)}.`);
34983
+ }
34984
+ if (line2[0] === " ") {
34985
+ result.push(body);
34986
+ added += 1;
34987
+ }
34988
+ removed += 1;
34989
+ at += 1;
34990
+ }
34991
+ if (removed !== one.oldCount || added !== one.newCount) {
34992
+ throw new MigrateRefused(`the diff from the server does not fit ${path3}: a hunk has the wrong length.`);
34993
+ }
34994
+ cursor = at;
34995
+ }
34996
+ result.push(...old.slice(cursor));
34997
+ out[path3] = result.join("");
34998
+ }
34999
+ return out;
35000
+ }
35001
+ function mergeManifest(manifest, additions) {
35002
+ const out = { ...manifest };
35003
+ const added = [];
35004
+ const skipped = [];
35005
+ if (!isObj5(additions)) return { manifest: out, added, skipped };
35006
+ for (const key of Object.keys(additions)) {
35007
+ if (key !== "capabilities" && key !== "http") {
35008
+ skipped.push(`${key}: migrate does not know this addition; add it by hand`);
35009
+ }
35010
+ }
35011
+ const caps = additions["capabilities"];
35012
+ const words = isObj5(caps) && Array.isArray(caps["dr"]) ? caps["dr"].filter((w) => typeof w === "string") : [];
35013
+ if (words.length > 0) {
35014
+ const held = out["capabilities"];
35015
+ if (held !== void 0 && !isObj5(held)) {
35016
+ skipped.push("capabilities: it is not an object in manifest.json; add capabilities.dr by hand");
35017
+ } else {
35018
+ const capabilities = { ...held ?? {} };
35019
+ const dr = capabilities["dr"];
35020
+ if (dr !== void 0 && !Array.isArray(dr)) {
35021
+ skipped.push("capabilities.dr: it is not a list in manifest.json; add the scope words by hand");
35022
+ } else {
35023
+ const list3 = [...dr ?? []];
35024
+ for (const word of words) {
35025
+ if (!list3.includes(word)) {
35026
+ list3.push(word);
35027
+ added.push(`capabilities.dr: ${word}`);
35028
+ }
35029
+ }
35030
+ capabilities["dr"] = list3;
35031
+ out["capabilities"] = capabilities;
35032
+ }
35033
+ }
35034
+ }
35035
+ const http = additions["http"];
35036
+ if (isObj5(http) && Object.keys(http).length > 0) {
35037
+ const held = out["http"];
35038
+ if (held !== void 0 && !isObj5(held)) {
35039
+ skipped.push("http: it is not an object in manifest.json; add the http entries by hand");
35040
+ } else {
35041
+ const entries = { ...held ?? {} };
35042
+ for (const [name, entry] of Object.entries(http)) {
35043
+ if (Object.prototype.hasOwnProperty.call(entries, name)) {
35044
+ skipped.push(`http.${name}: the manifest has this name already; it is not changed`);
35045
+ continue;
35046
+ }
35047
+ Object.defineProperty(entries, name, { value: entry, enumerable: true, writable: true, configurable: true });
35048
+ added.push(`http.${name}`);
35049
+ }
35050
+ out["http"] = entries;
35051
+ }
35052
+ }
35053
+ return { manifest: out, added, skipped };
35054
+ }
35055
+ var NotJson = class extends Error {
35056
+ };
35057
+ function skipSpace(text4, i) {
35058
+ while (i < text4.length && " \r\n".includes(text4[i])) i += 1;
35059
+ return i;
35060
+ }
35061
+ function stringEnd3(text4, i) {
35062
+ if (text4[i] !== '"') throw new NotJson();
35063
+ for (let n = i + 1; n < text4.length; n++) {
35064
+ if (text4[n] === "\\") n += 1;
35065
+ else if (text4[n] === '"') return n + 1;
35066
+ }
35067
+ throw new NotJson();
35068
+ }
35069
+ function valueEnd(text4, i) {
35070
+ const c = text4[i];
35071
+ if (c === '"') return stringEnd3(text4, i);
35072
+ if (c === "{" || c === "[") return containerOf(text4, i).close + 1;
35073
+ let n = i;
35074
+ while (n < text4.length && !",}] \r\n".includes(text4[n])) n += 1;
35075
+ if (n === i) throw new NotJson();
35076
+ return n;
35077
+ }
35078
+ function containerOf(text4, open2) {
35079
+ const object = text4[open2] === "{";
35080
+ const closer = object ? "}" : "]";
35081
+ const members = [];
35082
+ let i = skipSpace(text4, open2 + 1);
35083
+ if (text4[i] === closer) return { open: open2, close: i, members };
35084
+ for (; ; ) {
35085
+ let key = null;
35086
+ const start = i;
35087
+ if (object) {
35088
+ const keyEnd = stringEnd3(text4, i);
35089
+ key = JSON.parse(text4.slice(i, keyEnd));
35090
+ i = skipSpace(text4, keyEnd);
35091
+ if (text4[i] !== ":") throw new NotJson();
35092
+ i = skipSpace(text4, i + 1);
35093
+ }
35094
+ const valueStart = i;
35095
+ const end = valueEnd(text4, i);
35096
+ members.push({ key, start: object ? valueStart : start, end });
35097
+ i = skipSpace(text4, end);
35098
+ if (text4[i] === ",") {
35099
+ i = skipSpace(text4, i + 1);
35100
+ continue;
35101
+ }
35102
+ if (text4[i] === closer) return { open: open2, close: i, members };
35103
+ throw new NotJson();
35104
+ }
35105
+ }
35106
+ function memberOf(container, key) {
35107
+ for (let n = container.members.length - 1; n >= 0; n--) {
35108
+ if (container.members[n]?.key === key) return container.members[n];
35109
+ }
35110
+ return void 0;
35111
+ }
35112
+ function styleOf(text4) {
35113
+ const newline = text4.includes("\r\n") ? "\r\n" : "\n";
35114
+ const indented = /\n([ \t]+)\S/.exec(text4);
35115
+ return { unit: indented?.[1] ?? " ", newline };
35116
+ }
35117
+ function insertion(text4, container, items, depth, style) {
35118
+ const multiline = text4.slice(container.open, container.close).includes("\n");
35119
+ const last = container.members[container.members.length - 1];
35120
+ if (!multiline) {
35121
+ const joined2 = items.join(", ");
35122
+ return last === void 0 ? { at: container.open + 1, text: joined2 } : { at: last.end, text: `, ${joined2}` };
35123
+ }
35124
+ const indent2 = style.unit.repeat(depth + 1);
35125
+ const joined = items.map((item) => `${style.newline}${indent2}${item}`).join(",");
35126
+ return last === void 0 ? { at: container.open + 1, text: joined } : { at: last.end, text: `,${joined}` };
35127
+ }
35128
+ function rendered(value, depth, style, multiline) {
35129
+ if (!multiline) return JSON.stringify(value);
35130
+ return JSON.stringify(value, null, style.unit).split("\n").join(`${style.newline}${style.unit.repeat(depth)}`);
35131
+ }
35132
+ function canonical5(value) {
35133
+ if (Array.isArray(value)) return `[${value.map(canonical5).join(",")}]`;
35134
+ if (isObj5(value)) {
35135
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical5(value[k])}`).join(",")}}`;
35136
+ }
35137
+ return JSON.stringify(value);
35138
+ }
35139
+ function manifestText(raw, merge, before) {
35140
+ if (merge.added.length === 0) return raw;
35141
+ try {
35142
+ const style = styleOf(raw);
35143
+ const start = skipSpace(raw, raw.charCodeAt(0) === 65279 ? 1 : 0);
35144
+ if (raw[start] !== "{") throw new NotJson();
35145
+ const root = containerOf(raw, start);
35146
+ const rootMultiline = raw.slice(root.open, root.close).includes("\n");
35147
+ const edits = [];
35148
+ const rootItems = [];
35149
+ const words = merge.manifest["capabilities"]?.["dr"];
35150
+ const heldCaps = before["capabilities"];
35151
+ const newWords = Array.isArray(words) ? words.slice(isObj5(heldCaps) && Array.isArray(heldCaps["dr"]) ? heldCaps["dr"].length : 0) : [];
35152
+ if (newWords.length > 0) {
35153
+ const caps = memberOf(root, "capabilities");
35154
+ if (caps === void 0) {
35155
+ rootItems.push(`"capabilities": ${rendered({ dr: newWords }, 1, style, rootMultiline)}`);
35156
+ } else {
35157
+ const capsBox = containerOf(raw, caps.start);
35158
+ const dr = memberOf(capsBox, "dr");
35159
+ if (dr === void 0) {
35160
+ const multiline = raw.slice(capsBox.open, capsBox.close).includes("\n");
35161
+ edits.push(insertion(raw, capsBox, [`"dr": ${rendered(newWords, 2, style, multiline)}`], 1, style));
35162
+ } else {
35163
+ const list3 = containerOf(raw, dr.start);
35164
+ edits.push(insertion(raw, list3, newWords.map((w) => JSON.stringify(w)), 2, style));
35165
+ }
35166
+ }
35167
+ }
35168
+ const http = merge.manifest["http"];
35169
+ const heldHttp = before["http"];
35170
+ const newEntries = isObj5(http) ? Object.keys(http).filter((name) => !(isObj5(heldHttp) && Object.prototype.hasOwnProperty.call(heldHttp, name))) : [];
35171
+ if (newEntries.length > 0 && isObj5(http)) {
35172
+ const box = memberOf(root, "http");
35173
+ if (box === void 0) {
35174
+ const entries = Object.fromEntries(newEntries.map((name) => [name, http[name]]));
35175
+ rootItems.push(`"http": ${rendered(entries, 1, style, rootMultiline)}`);
35176
+ } else {
35177
+ const httpBox = containerOf(raw, box.start);
35178
+ const multiline = raw.slice(httpBox.open, httpBox.close).includes("\n");
35179
+ edits.push(
35180
+ insertion(
35181
+ raw,
35182
+ httpBox,
35183
+ newEntries.map((name) => `${JSON.stringify(name)}: ${rendered(http[name], 2, style, multiline)}`),
35184
+ 1,
35185
+ style
35186
+ )
35187
+ );
35188
+ }
35189
+ }
35190
+ if (rootItems.length > 0) edits.push(insertion(raw, root, rootItems, 0, style));
35191
+ let out = raw;
35192
+ for (const edit of [...edits].sort((a, b) => b.at - a.at)) {
35193
+ out = out.slice(0, edit.at) + edit.text + out.slice(edit.at);
35194
+ }
35195
+ if (canonical5(JSON.parse(out)) !== canonical5(merge.manifest)) throw new NotJson();
35196
+ return out;
35197
+ } catch (err) {
35198
+ if (!(err instanceof NotJson) && !(err instanceof SyntaxError)) throw err;
35199
+ throw new MigrateRefused(
35200
+ `migrate could not add ${merge.added.join(", ")} to manifest.json in its own layout; add them by hand.`
35201
+ );
35202
+ }
35203
+ }
35204
+ function previewOf(body) {
35205
+ if (!isObj5(body) || typeof body["diff"] !== "string" || !Array.isArray(body["files"]) || !Array.isArray(body["points"]) || !isObj5(body["manifest"])) {
35206
+ throw new MigrateRefused("the server answered, but not with a migrate preview.");
35207
+ }
35208
+ return body;
35209
+ }
35210
+ function failureOf(err) {
35211
+ if (err instanceof AppSpaceHttpError) {
35212
+ const detail = isObj5(err.body) ? err.body["detail"] : void 0;
35213
+ if (err.status === 404 && detail === "Not Found" || err.status === 405) {
35214
+ return `this server has no migrate preview (POST ${MIGRATE_ROUTE}); it predates it (DR-58157).`;
35215
+ }
35216
+ if (err.status === 422 && isObj5(detail) && Array.isArray(detail["problems"])) {
35217
+ return `the server refused the package (422):
35218
+ ${detail["problems"].map((p) => ` ${String(p)}`).join("\n")}`;
35219
+ }
35220
+ return err.message;
35221
+ }
35222
+ return `could not get the migrate preview (${err instanceof Error ? err.message : String(err)}).`;
35223
+ }
35224
+ function renderPreview(preview) {
35225
+ const out = [];
35226
+ if (preview.diff !== "") out.push(preview.diff.replace(/\n$/, ""), "");
35227
+ if (preview.points.length > 0) {
35228
+ out.push(`Open points (${String(preview.points.length)}), each needs a person:`);
35229
+ const kinds = [...new Set(preview.points.map((p) => p.kind))].sort();
35230
+ for (const kind of kinds) {
35231
+ out.push(` ${kind}:`);
35232
+ for (const p of preview.points.filter((one) => one.kind === kind)) {
35233
+ const where2 = p.line === null ? p.file : `${p.file}:${String(p.line)}`;
35234
+ out.push(` ${where2} ${p.text}${p.target === void 0 ? "" : ` [${p.target}]`}`);
35235
+ }
35236
+ }
35237
+ out.push("");
35238
+ }
35239
+ const additions = Object.keys(preview.manifest);
35240
+ if (additions.length > 0) {
35241
+ out.push("manifest.json additions:", ...JSON.stringify(preview.manifest, null, 2).split("\n").map((l) => ` ${l}`), "");
35242
+ }
35243
+ const files = preview.files.length;
35244
+ out.push(
35245
+ preview.diff === "" && additions.length === 0 ? "Nothing to move: the code uses no old ctx name that the preview can rewrite." : `${String(preview.rewrites)} rewrite(s) in ${String(files)} file(s).`
35246
+ );
35247
+ return out.join("\n") + "\n";
35248
+ }
35249
+ function renderCheck(check5) {
35250
+ const out = [];
35251
+ if (check5.problems.length === 0 && check5.skipped.length === 0) {
35252
+ out.push("Package check: the push would go through.");
35253
+ }
35254
+ for (const p of check5.problems) out.push(`[${p.code}] ${p.message} ${p.fix}`.trim());
35255
+ for (const s of check5.skipped) out.push(`Not checked: ${s.what} (${s.why}).`);
35256
+ return out.join("\n") + "\n";
35257
+ }
35258
+ async function runMigrate(dir, opts) {
35259
+ try {
35260
+ targetRuntime(opts.toRuntime);
35261
+ const { manifest } = await readManifest(dir).catch((err) => {
35262
+ throw new MigrateRefused(err instanceof Error ? err.message : String(err));
35263
+ });
35264
+ const manifestSent = await readFile11(join17(dir, "manifest.json"), "utf8");
35265
+ if (canonical5(JSON.parse(manifestSent)) !== canonical5(manifest)) {
35266
+ throw new MigrateRefused("manifest.json changed while migrate read it. Run migrate again.");
35267
+ }
35268
+ const handlers = await readHandlers(join17(dir, "handlers"), await readState(dir));
35269
+ const lib = await readLib(join17(dir, "lib"));
35270
+ const sent = {};
35271
+ for (const [name, spec] of Object.entries(handlers)) sent[`handlers/${name}.py`] = spec.code;
35272
+ for (const [name, code] of Object.entries(lib)) sent[`lib/${name}.py`] = code;
35273
+ let preview;
35274
+ const client = await connect(opts).catch((err) => {
35275
+ throw new MigrateRefused(failureOf(err));
35276
+ });
35277
+ try {
35278
+ const body = await client.request(MIGRATE_ROUTE, { method: "POST", body: { manifest, handlers, lib } }).catch((err) => {
35279
+ throw new MigrateRefused(failureOf(err));
35280
+ });
35281
+ preview = previewOf(body);
35282
+ } finally {
35283
+ client.cleanup();
35284
+ }
35285
+ if (opts.write !== true) {
35286
+ if (opts.json === true) printJson({ ...preview, written: [] });
35287
+ else {
35288
+ process.stdout.write(renderPreview(preview));
35289
+ if (preview.diff !== "" || Object.keys(preview.manifest).length > 0) {
35290
+ process.stdout.write("Dry run: nothing was written. Run again with --write to apply the diff and the manifest additions.\n");
35291
+ }
35292
+ }
35293
+ return 0;
35294
+ }
35295
+ const files = applyDiff(preview.diff, sent);
35296
+ const manifestNow = await readFile11(join17(dir, "manifest.json"), "utf8");
35297
+ if (manifestNow !== manifestSent) {
35298
+ throw new MigrateRefused("manifest.json changed since migrate read it. Run migrate again.");
35299
+ }
35300
+ const merge = mergeManifest(JSON.parse(manifestSent), preview.manifest);
35301
+ const plan = [];
35302
+ for (const [path3, text4] of Object.entries(files)) {
35303
+ if (text4 !== sent[path3]) plan.push({ path: path3, old: sent[path3], text: text4 });
35304
+ }
35305
+ if (merge.added.length > 0) {
35306
+ plan.push({
35307
+ path: "manifest.json",
35308
+ old: manifestSent,
35309
+ text: manifestText(manifestSent, merge, JSON.parse(manifestSent))
35310
+ });
35311
+ }
35312
+ for (const step of plan) await writable(dir, step.path, step.old);
35313
+ const written = [];
35314
+ let check5 = null;
35315
+ let warnings = [];
35316
+ const interrupt = watchSignals();
35317
+ try {
35318
+ try {
35319
+ for (const step of plan) {
35320
+ interrupt.check();
35321
+ await replaceFile(join17(dir, step.path), step.text);
35322
+ written.push(step.path);
35323
+ }
35324
+ interrupt.check();
35325
+ } finally {
35326
+ interrupt.stop();
35327
+ }
35328
+ const compiled = await recordedDigests(dir);
35329
+ warnings = written.filter((path3) => Object.prototype.hasOwnProperty.call(compiled, path3)).map(
35330
+ (path3) => `${path3} is a file app-space compile wrote; the next compile counts this edit as a hand edit (eject it to keep it as yours, or move the contract to the new names).`
35331
+ );
35332
+ if (opts.check !== false && written.length > 0) {
35333
+ let contract = null;
35334
+ try {
35335
+ const raw = await readIfPresent(join17(dir, "contract.json"));
35336
+ contract = raw === void 0 ? null : JSON.parse(raw);
35337
+ } catch {
35338
+ contract = null;
35339
+ }
35340
+ check5 = await checkPackage(dir, {}, contract, opts, true);
35341
+ }
35342
+ } catch (err) {
35343
+ const restored = [];
35344
+ const lost = [];
35345
+ const leftovers = err instanceof TemporaryLeft ? [err.temporary] : [];
35346
+ const hold = watchSignals();
35347
+ try {
35348
+ for (const step of plan.filter((one) => written.includes(one.path)).reverse()) {
35349
+ try {
35350
+ await replaceFile(join17(dir, step.path), step.old);
35351
+ restored.push(step.path);
35352
+ } catch (undo) {
35353
+ if (undo instanceof TemporaryLeft) leftovers.push(undo.temporary);
35354
+ lost.push(step.path);
35355
+ }
35356
+ }
35357
+ } finally {
35358
+ hold.stop();
35359
+ }
35360
+ const stop = err instanceof Interrupted ? err : hold.seen();
35361
+ const why = err instanceof Error ? err.message : String(err);
35362
+ const many = leftovers.length > 1;
35363
+ const left = `the temporary file${many ? "s" : ""} ${leftovers.join(", ")} ${many ? "are" : "is"} still there: remove ${many ? "them" : "it"} by hand.`;
35364
+ const said2 = (err instanceof Interrupted ? `migrate --write stopped by ${err.signal}. ` : `migrate --write failed (${why}). `) + (restored.length > 0 ? `Put back the old text of: ${restored.join(", ")}. ` : "") + (lost.length > 0 ? `Could NOT put back: ${lost.join(", ")}; these files hold the new text.` + (leftovers.length > 0 ? ` And ${left}` : "") : leftovers.length === 0 ? "The folder is as it was." : `The files are as they were, but ${left}`);
35365
+ if (opts.json === true) printJson({ ok: false, error: said2, restored, not_restored: lost });
35366
+ process.stderr.write(`${said2}
35367
+ `);
35368
+ return stop !== void 0 ? stop.code : 1;
35369
+ }
35370
+ if (opts.json === true) {
35371
+ printJson({
35372
+ ...preview,
35373
+ written,
35374
+ manifest_added: merge.added,
35375
+ manifest_skipped: merge.skipped,
35376
+ warnings,
35377
+ check: check5
35378
+ });
35379
+ } else {
35380
+ process.stdout.write(renderPreview(preview));
35381
+ process.stdout.write(
35382
+ written.length === 0 ? "Nothing was written: the folder has the new names already.\n" : `Wrote:
35383
+ ${written.map((p) => ` ${p}
35384
+ `).join("")}`
35385
+ );
35386
+ for (const line2 of merge.added) process.stdout.write(` added ${line2}
35387
+ `);
35388
+ for (const line2 of merge.skipped) process.stderr.write(`warning: manifest.json ${line2}
35389
+ `);
35390
+ for (const line2 of warnings) process.stderr.write(`warning: ${line2}
35391
+ `);
35392
+ if (check5 !== null) process.stdout.write(renderCheck(check5));
35393
+ }
35394
+ return check5 !== null && check5.problems.length > 0 ? 1 : 0;
35395
+ } catch (err) {
35396
+ const said2 = err instanceof MigrateRefused ? err.message : `migrate failed (${err instanceof Error ? err.message : String(err)}).`;
35397
+ if (opts.json === true) printJson({ ok: false, error: `${said2} Nothing was written.` });
35398
+ process.stderr.write(`${said2} Nothing was written.
35399
+ `);
35400
+ return 1;
35401
+ }
35402
+ }
35403
+ var _io = { rename: rename2, writeFile: writeFile9, realpath, rm: rm5 };
35404
+ async function writable(dir, path3, sent) {
35405
+ const full = join17(dir, path3);
35406
+ const parts = path3.split("/");
35407
+ for (let n = 1; n < parts.length; n += 1) {
35408
+ const folder = parts.slice(0, n).join("/");
35409
+ let kind;
35410
+ try {
35411
+ kind = await lstat2(join17(dir, folder));
35412
+ } catch {
35413
+ throw new MigrateRefused(`${path3} is gone since migrate read it. Run migrate again.`);
35414
+ }
35415
+ if (!kind.isDirectory()) {
35416
+ throw new MigrateRefused(`${folder}/ is not a plain folder (a link, or another kind); migrate writes only inside the app folder.`);
35417
+ }
35418
+ }
35419
+ const root = await _io.realpath(dir);
35420
+ const parent = await _io.realpath(dirname9(full));
35421
+ if (parent !== root && !parent.startsWith(root + sep5)) {
35422
+ throw new MigrateRefused(`${path3} is outside the app folder (a linked folder leads out); migrate writes only inside the app folder.`);
35423
+ }
35424
+ let info;
35425
+ try {
35426
+ info = await lstat2(full);
35427
+ } catch {
35428
+ throw new MigrateRefused(`${path3} is gone since migrate read it. Run migrate again.`);
35429
+ }
35430
+ if (!info.isFile()) {
35431
+ throw new MigrateRefused(`${path3} is not a regular file (a link, or another kind); migrate writes only regular files.`);
35432
+ }
35433
+ try {
35434
+ await access(full, constants.W_OK);
35435
+ await access(dirname9(full), constants.W_OK);
35436
+ } catch {
35437
+ throw new MigrateRefused(`${path3} cannot be written (no permission).`);
35438
+ }
35439
+ const bytes = await readFile11(full);
35440
+ const text4 = bytes.toString("utf8");
35441
+ if (!Buffer.from(text4, "utf8").equals(bytes)) {
35442
+ throw new MigrateRefused(`${path3} is not valid UTF-8; migrate would change bytes it did not mean to.`);
35443
+ }
35444
+ if (text4 !== sent) {
35445
+ throw new MigrateRefused(`${path3} changed since migrate read it. Run migrate again.`);
35446
+ }
35447
+ }
35448
+ var temporaries = 0;
35449
+ var TemporaryLeft = class extends Error {
35450
+ constructor(temporary, cause) {
35451
+ super(`${cause instanceof Error ? cause.message : String(cause)}; and the temporary file ${temporary} could not be removed`);
35452
+ this.temporary = temporary;
35453
+ }
35454
+ temporary;
35455
+ };
35456
+ var Interrupted = class extends Error {
35457
+ constructor(signal, code) {
35458
+ super(`stopped by ${signal}`);
35459
+ this.signal = signal;
35460
+ this.code = code;
35461
+ }
35462
+ signal;
35463
+ code;
35464
+ };
35465
+ var STOP_SIGNALS = [
35466
+ ["SIGINT", 130],
35467
+ ["SIGTERM", 143]
35468
+ ];
35469
+ function watchSignals() {
35470
+ let seen;
35471
+ const handlers = STOP_SIGNALS.map(([signal, code]) => {
35472
+ const handler = () => {
35473
+ seen ??= new Interrupted(signal, code);
35474
+ };
35475
+ process.on(signal, handler);
35476
+ return [signal, handler];
35477
+ });
35478
+ return {
35479
+ check: () => {
35480
+ if (seen !== void 0) throw seen;
35481
+ },
35482
+ seen: () => seen,
35483
+ stop: () => {
35484
+ for (const [signal, handler] of handlers) process.off(signal, handler);
35485
+ }
35486
+ };
35487
+ }
35488
+ async function dropTemporary(temporary, err) {
35489
+ try {
35490
+ await _io.rm(temporary, { force: true });
35491
+ } catch {
35492
+ throw new TemporaryLeft(temporary, err);
35493
+ }
35494
+ throw err;
35495
+ }
35496
+ async function replaceFile(full, text4) {
35497
+ temporaries += 1;
35498
+ const temporary = join17(dirname9(full), `.${basename2(full)}.migrate-${String(process.pid)}-${String(temporaries)}.tmp`);
35499
+ const mode = (await lstat2(full)).mode & 511;
35500
+ let ours = false;
35501
+ try {
35502
+ await _io.writeFile(temporary, text4, { flag: "wx", mode });
35503
+ ours = true;
35504
+ await _io.rename(temporary, full);
35505
+ } catch (err) {
35506
+ if (!ours && err.code === "EEXIST") throw err;
35507
+ return dropTemporary(temporary, err);
35508
+ }
35509
+ }
35510
+ function registerMigrateCommand(parent) {
35511
+ withJsonOption(
35512
+ withServerOptions(
35513
+ parent.command("migrate [dir]").description(
35514
+ "Move a folder to the new ctx names (ctx.app.tables, ctx.app.state, ctx.dr): a dry run that prints the diff, or --write."
35515
+ ).option("--write", "Apply the diff to the files and add the manifest additions, then run the package check.").option("--to-runtime <n>", "The runtime to move to. Only 1 today: runtime 2 is proposed (DR-58160).").option("--no-check", "With --write: do not run the package check after the write.")
35516
+ )
35517
+ ).action(async (dirArg, opts) => {
35518
+ const code = await runMigrate(dirArg ?? ".", opts);
35519
+ if (code !== 0) process.exitCode = code;
35520
+ });
35521
+ }
35522
+
34873
35523
  // src/commands/appspace/test.ts
34874
- import { readFile as readFile13 } from "fs/promises";
34875
- import { join as join18, resolve as resolve16 } from "path";
35524
+ import { readFile as readFile14 } from "fs/promises";
35525
+ import { join as join19, resolve as resolve16 } from "path";
34876
35526
 
34877
35527
  // src/commands/appspace/_files.ts
34878
- import { readFile as readFile11, realpath } from "fs/promises";
34879
- import { basename as basename2, extname, resolve as resolve14, sep as sep5 } from "path";
35528
+ import { readFile as readFile12, realpath as realpath2 } from "fs/promises";
35529
+ import { basename as basename3, extname, resolve as resolve14, sep as sep6 } from "path";
34880
35530
 
34881
35531
  // src/commands/appspace/_samplePdf.ts
34882
35532
  function pdfString(text4) {
@@ -35033,7 +35683,7 @@ function readFailure(path3, full, err) {
35033
35683
  if (code === void 0 || code === "ENOENT") return new Error(`no file at ${path3} (looked for ${full}).`);
35034
35684
  return new Error(`could not read ${path3} (${String(code)}).`);
35035
35685
  }
35036
- async function resolveFile(path3, base, { read = readFile11, confine = false, realpath: real = realpath } = {}) {
35686
+ async function resolveFile(path3, base, { read = readFile12, confine = false, realpath: real = realpath2 } = {}) {
35037
35687
  if (path3 === null) {
35038
35688
  return { bytes: sampleInvoiceBytes(), filename: SAMPLE_INVOICE.filename, mimeType: SAMPLE_INVOICE.mimeType };
35039
35689
  }
@@ -35046,7 +35696,7 @@ async function resolveFile(path3, base, { read = readFile11, confine = false, re
35046
35696
  } catch (err) {
35047
35697
  throw readFailure(path3, full, err);
35048
35698
  }
35049
- if (target !== root && !target.startsWith(root + sep5)) {
35699
+ if (target !== root && !target.startsWith(root + sep6)) {
35050
35700
  throw new Error(`${path3} leads outside the app folder (to ${target}); a fixture's file lives in the folder.`);
35051
35701
  }
35052
35702
  }
@@ -35057,7 +35707,7 @@ async function resolveFile(path3, base, { read = readFile11, confine = false, re
35057
35707
  throw readFailure(path3, full, err);
35058
35708
  }
35059
35709
  if (bytes.length === 0) throw new Error(`${path3} is empty, and the platform refuses an empty upload.`);
35060
- const filename = basename2(full);
35710
+ const filename = basename3(full);
35061
35711
  return { bytes, filename, mimeType: mimeTypeOf(filename) };
35062
35712
  }
35063
35713
  function isPlainObject18(value) {
@@ -35079,7 +35729,7 @@ function fileColumnsOf(model) {
35079
35729
  }
35080
35730
  async function readFileColumns(dir) {
35081
35731
  try {
35082
- return fileColumnsOf(JSON.parse(await readFile11(resolve14(dir, "data_model.json"), "utf8")));
35732
+ return fileColumnsOf(JSON.parse(await readFile12(resolve14(dir, "data_model.json"), "utf8")));
35083
35733
  } catch {
35084
35734
  return null;
35085
35735
  }
@@ -37177,10 +37827,10 @@ async function runUiSmoke(opts) {
37177
37827
  // src/commands/appspace/_screenshot.ts
37178
37828
  import { spawn } from "child_process";
37179
37829
  import { existsSync as existsSync3, statSync as statSync3 } from "fs";
37180
- import { mkdir as mkdir8, mkdtemp as mkdtemp4, readFile as readFile12, readdir as readdir3, rm as rm5, stat as stat2, writeFile as writeFile9 } from "fs/promises";
37830
+ import { mkdir as mkdir8, mkdtemp as mkdtemp4, readFile as readFile13, readdir as readdir3, rm as rm6, stat as stat2, writeFile as writeFile10 } from "fs/promises";
37181
37831
  import { createServer } from "http";
37182
37832
  import { tmpdir as tmpdir5 } from "os";
37183
- import { delimiter, extname as extname2, join as join17, relative as relative3, resolve as resolve15, sep as sep6 } from "path";
37833
+ import { delimiter, extname as extname2, join as join18, relative as relative3, resolve as resolve15, sep as sep7 } from "path";
37184
37834
 
37185
37835
  // ../tests/vendor/fixtures/widgets/kpi.json
37186
37836
  var kpi_default = {
@@ -38207,7 +38857,7 @@ function findChrome(env = process.env, exists = isFile, appPaths = CHROME_APP_PA
38207
38857
  const dirs = (env["PATH"] ?? "").split(delimiter).filter((dir) => dir !== "");
38208
38858
  for (const name of CHROME_NAMES) {
38209
38859
  for (const dir of dirs) {
38210
- const path3 = join17(dir, name);
38860
+ const path3 = join18(dir, name);
38211
38861
  if (exists(path3)) return path3;
38212
38862
  }
38213
38863
  }
@@ -38374,7 +39024,7 @@ function contentType(path3) {
38374
39024
  function inside(root, rel) {
38375
39025
  const base = resolve15(root);
38376
39026
  const full = resolve15(base, rel);
38377
- return full === base || !full.startsWith(base + sep6) ? null : full;
39027
+ return full === base || !full.startsWith(base + sep7) ? null : full;
38378
39028
  }
38379
39029
  var Shelf = class {
38380
39030
  constructor(source, fetchImpl = fetch) {
@@ -38418,7 +39068,7 @@ var Shelf = class {
38418
39068
  const full = inside(this.source.root, rel);
38419
39069
  if (full === null) continue;
38420
39070
  try {
38421
- return { status: 200, type: contentType(full), body: await readFile12(full) };
39071
+ return { status: 200, type: contentType(full), body: await readFile13(full) };
38422
39072
  } catch {
38423
39073
  }
38424
39074
  }
@@ -38548,8 +39198,8 @@ async function startStubServer(opts) {
38548
39198
  const body = await readBody(req);
38549
39199
  const log = logOf(id);
38550
39200
  note(log.called, inApp);
38551
- const access = accessFor(opts.manifest, shot.role, opts.allowedByRole?.[shot.role], opts.sources ?? []);
38552
- if (access.allowed[inApp] === false) {
39201
+ const access2 = accessFor(opts.manifest, shot.role, opts.allowedByRole?.[shot.role], opts.sources ?? []);
39202
+ if (access2.allowed[inApp] === false) {
38553
39203
  note(log.refused, inApp);
38554
39204
  return sendJson(res, 403, { detail: `role ${shot.role} may not call ${inApp}` });
38555
39205
  }
@@ -38622,7 +39272,7 @@ function asRoot(getuid = process.getuid?.bind(process) ?? null) {
38622
39272
  return getuid !== null && getuid() === 0;
38623
39273
  }
38624
39274
  async function runChrome(run) {
38625
- const profile = await mkdtemp4(join17(tmpdir5(), "dr-appspace-shot-"));
39275
+ const profile = await mkdtemp4(join18(tmpdir5(), "dr-appspace-shot-"));
38626
39276
  const args = [
38627
39277
  // Chrome will not start as root without it, and a container's shell is
38628
39278
  // root (the managed build sandbox). Elsewhere its own sandbox stays on.
@@ -38688,7 +39338,7 @@ async function runChrome(run) {
38688
39338
  }
38689
39339
  } finally {
38690
39340
  killGroup(child);
38691
- await rm5(profile, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }).catch(() => void 0);
39341
+ await rm6(profile, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }).catch(() => void 0);
38692
39342
  }
38693
39343
  if (ok) return { ok, stdout, profile };
38694
39344
  const error = spawnError ?? (Date.now() >= deadline ? `timed out after ${String(Math.round(run.timeoutMs / 1e3))}s` : run.out === void 0 ? "Chrome printed no DOM" : "Chrome exited without writing the screenshot");
@@ -38805,13 +39455,13 @@ async function runScreenshots(opts) {
38805
39455
  seen = rows2 === null ? { look: null, skipped: measured.error ?? "the page never settled" } : { look: rows2 };
38806
39456
  }
38807
39457
  }
38808
- const out = join17(opts.outDir, file);
39458
+ const out = join18(opts.outDir, file);
38809
39459
  let id = -1;
38810
39460
  let result;
38811
39461
  for (let attempt = 0; attempt < 2 && now() < pageUntil - 500; attempt++) {
38812
39462
  id = nextId++;
38813
39463
  stub.register(id, { role });
38814
- await rm5(out, { force: true });
39464
+ await rm6(out, { force: true });
38815
39465
  result = await runChrome({
38816
39466
  chrome: opts.chrome,
38817
39467
  url: stub.urlFor(id, entry),
@@ -38840,7 +39490,7 @@ async function runScreenshots(opts) {
38840
39490
  shots[index2] = { ...entryOut, error: result.error ?? "no picture" };
38841
39491
  return;
38842
39492
  }
38843
- const bytes = await readFile12(out);
39493
+ const bytes = await readFile13(out);
38844
39494
  if (look && seen === void 0) toLook.push(index2);
38845
39495
  shots[index2] = {
38846
39496
  ...entryOut,
@@ -38884,11 +39534,11 @@ async function runScreenshots(opts) {
38884
39534
  sample,
38885
39535
  shots
38886
39536
  };
38887
- await writeFile9(join17(opts.outDir, "index.json"), JSON.stringify(index, null, 2) + "\n");
39537
+ await writeFile10(join18(opts.outDir, "index.json"), JSON.stringify(index, null, 2) + "\n");
38888
39538
  return index;
38889
39539
  }
38890
39540
  async function readLocalUi(dir) {
38891
- const root = join17(dir, "ui");
39541
+ const root = join18(dir, "ui");
38892
39542
  const out = {};
38893
39543
  const walk5 = async (folder) => {
38894
39544
  let names;
@@ -38898,16 +39548,16 @@ async function readLocalUi(dir) {
38898
39548
  return;
38899
39549
  }
38900
39550
  for (const one of names) {
38901
- const full = join17(folder, one.name);
39551
+ const full = join18(folder, one.name);
38902
39552
  if (one.isDirectory()) await walk5(full);
38903
- else if (one.isFile()) out[relative3(root, full).split(sep6).join("/")] = await readFile12(full);
39553
+ else if (one.isFile()) out[relative3(root, full).split(sep7).join("/")] = await readFile13(full);
38904
39554
  }
38905
39555
  };
38906
39556
  await walk5(root);
38907
39557
  return out;
38908
39558
  }
38909
39559
  function looksLikeShelf(root) {
38910
- return existsSync3(join17(root, "vendor"));
39560
+ return existsSync3(join18(root, "vendor"));
38911
39561
  }
38912
39562
  function renderShotTable(index, outDir) {
38913
39563
  const rows2 = index.shots.map((shot) => [
@@ -38941,7 +39591,7 @@ screenshots \u2192 ${outDir} (${String(written)} of ${String(index.shots.length
38941
39591
  `;
38942
39592
  }
38943
39593
  out += lookLine(index);
38944
- out += ` index: ${join17(outDir, "index.json")}
39594
+ out += ` index: ${join18(outDir, "index.json")}
38945
39595
  `;
38946
39596
  return out;
38947
39597
  }
@@ -40034,7 +40684,7 @@ function partFindings(runs) {
40034
40684
  }
40035
40685
  return out;
40036
40686
  }
40037
- function linesOf(text4) {
40687
+ function linesOf2(text4) {
40038
40688
  if (typeof text4 !== "string" || text4 === "") return 0;
40039
40689
  return text4.replace(/\n$/, "").split("\n").length;
40040
40690
  }
@@ -40134,13 +40784,13 @@ function partsSummary(contract, bundle, handlerCode) {
40134
40784
  }
40135
40785
  }
40136
40786
  let customUiLines = 0;
40137
- for (const module of modules) customUiLines += linesOf(bundle[module] ?? bundle[`ui/${module}`]);
40787
+ for (const module of modules) customUiLines += linesOf2(bundle[module] ?? bundle[`ui/${module}`]);
40138
40788
  let customHandlers = 0;
40139
40789
  let customHandlerLines = 0;
40140
40790
  for (const [name, handler] of Object.entries(contract.data?.app?.handlers ?? {})) {
40141
40791
  if (handler?.role !== "custom") continue;
40142
40792
  customHandlers += 1;
40143
- customHandlerLines += linesOf(handlerCode[name]);
40793
+ customHandlerLines += linesOf2(handlerCode[name]);
40144
40794
  }
40145
40795
  const components = registry2 + customUi;
40146
40796
  const summary = {
@@ -40618,7 +41268,7 @@ function collectRoles(value, previous = []) {
40618
41268
  }
40619
41269
  async function readLocalManifest(dir) {
40620
41270
  try {
40621
- return JSON.parse(await readFile13(join18(dir, "manifest.json"), "utf8"));
41271
+ return JSON.parse(await readFile14(join19(dir, "manifest.json"), "utf8"));
40622
41272
  } catch {
40623
41273
  return null;
40624
41274
  }
@@ -40758,10 +41408,10 @@ function evaluateCase(kase, res) {
40758
41408
  return problems;
40759
41409
  }
40760
41410
  async function loadFixtures(dir, explicit) {
40761
- const path3 = explicit ?? join18(dir, DEFAULT_FIXTURES);
41411
+ const path3 = explicit ?? join19(dir, DEFAULT_FIXTURES);
40762
41412
  let raw;
40763
41413
  try {
40764
- raw = await readFile13(path3, "utf8");
41414
+ raw = await readFile14(path3, "utf8");
40765
41415
  } catch {
40766
41416
  if (explicit !== void 0) throw new Error(`no fixtures file at ${path3}.`);
40767
41417
  return { fixtures: { cases: [], ui: { entry: "index.html" } } };
@@ -40776,14 +41426,14 @@ async function loadFixtures(dir, explicit) {
40776
41426
  }
40777
41427
  async function runHandlerCases(cases, dir, appId, client, roleOf = () => void 0) {
40778
41428
  const code = /* @__PURE__ */ new Map();
40779
- const lib = await readLib(join18(dir, "lib"));
41429
+ const lib = await readLib(join19(dir, "lib"));
40780
41430
  const outcomes = [];
40781
41431
  for (const kase of cases) {
40782
41432
  requirePlainName("handler", kase.handler, "read");
40783
41433
  if (!code.has(kase.handler)) {
40784
41434
  code.set(
40785
41435
  kase.handler,
40786
- await readFile13(join18(dir, "handlers", `${kase.handler}.py`), "utf8").catch(() => null)
41436
+ await readFile14(join19(dir, "handlers", `${kase.handler}.py`), "utf8").catch(() => null)
40787
41437
  );
40788
41438
  }
40789
41439
  const source = code.get(kase.handler);
@@ -41038,7 +41688,7 @@ function contractUid(contract, page, component) {
41038
41688
  }
41039
41689
  async function isDashboardFolder2(dir) {
41040
41690
  try {
41041
- const doc = JSON.parse(await readFile13(join18(dir, "contract.json"), "utf8"));
41691
+ const doc = JSON.parse(await readFile14(join19(dir, "contract.json"), "utf8"));
41042
41692
  return doc.app?.kind === "dashboard";
41043
41693
  } catch {
41044
41694
  return false;
@@ -41239,7 +41889,7 @@ function mergeDomComponents(contract, components, page) {
41239
41889
  async function writeMergedContract(dir, page, components) {
41240
41890
  let contract;
41241
41891
  try {
41242
- contract = JSON.parse(await readFile13(contractPath(dir), "utf8"));
41892
+ contract = JSON.parse(await readFile14(contractPath(dir), "utf8"));
41243
41893
  } catch {
41244
41894
  contract = await extractContract(dir);
41245
41895
  }
@@ -41249,7 +41899,7 @@ async function writeMergedContract(dir, page, components) {
41249
41899
  async function uiIsStale(dir, entry, stored) {
41250
41900
  if (stored === void 0) return false;
41251
41901
  try {
41252
- const local = await readFile13(join18(dir, "ui", entry));
41902
+ const local = await readFile14(join19(dir, "ui", entry));
41253
41903
  return !local.equals(Buffer.from(stored, "utf8"));
41254
41904
  } catch {
41255
41905
  return false;
@@ -41337,7 +41987,7 @@ function untouchedHandlers(declared, cases, interactions, runs = []) {
41337
41987
  async function readSeed(dir) {
41338
41988
  let parsed2;
41339
41989
  try {
41340
- parsed2 = JSON.parse(await readFile13(join18(dir, "seed.json"), "utf8"));
41990
+ parsed2 = JSON.parse(await readFile14(join19(dir, "seed.json"), "utf8"));
41341
41991
  } catch {
41342
41992
  return null;
41343
41993
  }
@@ -41353,7 +42003,7 @@ async function readSeed(dir) {
41353
42003
  }
41354
42004
  async function handlerOwnership(dir, pushed) {
41355
42005
  try {
41356
- const local = JSON.parse(await readFile13(join18(dir, "contract.json"), "utf8"));
42006
+ const local = JSON.parse(await readFile14(join19(dir, "contract.json"), "utf8"));
41357
42007
  const owned = ownershipOf(local);
41358
42008
  if (owned !== null) return owned;
41359
42009
  } catch {
@@ -41681,7 +42331,7 @@ function registerTestCommand(parent) {
41681
42331
  const files = pushedPages ? store.bundle : await readLocalUi(dir);
41682
42332
  const pages = pushedPages ? store.pages : orderPages(Object.keys(files));
41683
42333
  const manifest = pushedPages && typeof store.manifest === "object" && store.manifest !== null ? store.manifest : await readLocalManifest(dir);
41684
- const outDir = resolve16(opts.out ?? join18(dir, ".screenshots"));
42334
+ const outDir = resolve16(opts.out ?? join19(dir, ".screenshots"));
41685
42335
  const index = await runScreenshots({
41686
42336
  appId,
41687
42337
  pages: choosePages(opts.pages, pages, fixtures.ui.entry).load,
@@ -41800,12 +42450,12 @@ ${String(failed)} failure(s).
41800
42450
  }
41801
42451
 
41802
42452
  // src/commands/appspace/try.ts
41803
- import { readFile as readFile14 } from "fs/promises";
41804
- import { join as join19 } from "path";
42453
+ import { readFile as readFile15 } from "fs/promises";
42454
+ import { join as join20 } from "path";
41805
42455
  function collect2(value, previous = []) {
41806
42456
  return [...previous, value];
41807
42457
  }
41808
- async function readPayloadOption(raw, read = (path3) => readFile14(path3, "utf8")) {
42458
+ async function readPayloadOption(raw, read = (path3) => readFile15(path3, "utf8")) {
41809
42459
  if (raw.startsWith("@")) {
41810
42460
  const path3 = raw.slice(1);
41811
42461
  if (path3 === "") throw new Error("--payload @ names no file; write --payload @./payload.json.");
@@ -41885,15 +42535,15 @@ function registerTryCommand(parent) {
41885
42535
  ).action(async (handler, opts) => {
41886
42536
  requirePlainName("handler", handler, "read");
41887
42537
  const appId = await readManifestId(opts.dir);
41888
- const code = await readFile14(
41889
- join19(opts.dir, "handlers", `${handler}.py`),
42538
+ const code = await readFile15(
42539
+ join20(opts.dir, "handlers", `${handler}.py`),
41890
42540
  "utf8"
41891
42541
  ).catch(() => {
41892
42542
  throw new Error(
41893
42543
  `no handlers/${handler}.py in ${opts.dir} \u2014 is this an app folder?`
41894
42544
  );
41895
42545
  });
41896
- const lib = await readLib(join19(opts.dir, "lib"));
42546
+ const lib = await readLib(join20(opts.dir, "lib"));
41897
42547
  let payload = await readPayloadOption(opts.payload ?? "{}");
41898
42548
  const files = parseFileSpecs(opts.file ?? []);
41899
42549
  const withFiles = payloadForFiles(payload, files);
@@ -42011,8 +42661,8 @@ function registerPublishCommands(parent) {
42011
42661
  }
42012
42662
 
42013
42663
  // src/commands/appspace/scaffold.ts
42014
- import { mkdir as mkdir9, readdir as readdir4, stat as stat3, writeFile as writeFile10 } from "fs/promises";
42015
- import { dirname as dirname9, join as join20 } from "path";
42664
+ import { mkdir as mkdir9, readdir as readdir4, stat as stat3, writeFile as writeFile11 } from "fs/promises";
42665
+ import { dirname as dirname10, join as join21 } from "path";
42016
42666
 
42017
42667
  // src/commands/appspace/starters.ts
42018
42668
  var STARTER_KINDS = ["dashboard", "app"];
@@ -42369,7 +43019,7 @@ async function existingFiles(dir, relPaths) {
42369
43019
  const present3 = [];
42370
43020
  for (const rel of relPaths) {
42371
43021
  try {
42372
- await stat3(join20(dir, rel));
43022
+ await stat3(join21(dir, rel));
42373
43023
  present3.push(rel);
42374
43024
  } catch {
42375
43025
  }
@@ -42408,13 +43058,13 @@ function registerScaffoldCommand(parent) {
42408
43058
  const table = ownsData ? (opts.table ?? DEFAULT_TABLE).trim() : void 0;
42409
43059
  const record2 = ownsData ? ((opts.record ?? "").trim() || singularize(table ?? DEFAULT_TABLE)).trim() : void 0;
42410
43060
  checkNames({ id, table, record: record2 });
42411
- const dir = (dirArg ?? "").trim() || join20(".", id);
43061
+ const dir = (dirArg ?? "").trim() || join21(".", id);
42412
43062
  await checkTarget(dir, opts.force === true);
42413
43063
  const contract = starterContract(kind, { id, name, table, record: record2 });
42414
43064
  const overwritten = opts.force === true ? await existingFiles(dir, [CONTRACT_FILE]) : [];
42415
- const target = join20(dir, CONTRACT_FILE);
42416
- await mkdir9(dirname9(target), { recursive: true });
42417
- await writeFile10(target, `${JSON.stringify(contract, null, 2)}
43065
+ const target = join21(dir, CONTRACT_FILE);
43066
+ await mkdir9(dirname10(target), { recursive: true });
43067
+ await writeFile11(target, `${JSON.stringify(contract, null, 2)}
42418
43068
  `);
42419
43069
  if (opts.json === true) {
42420
43070
  printJson({ id, name, dir, kind, table, record: record2, files: [CONTRACT_FILE], overwritten });
@@ -42656,6 +43306,7 @@ function registerAppSpaceCommand(root) {
42656
43306
  registerCompileCommand(cmd);
42657
43307
  registerShipCommand(cmd);
42658
43308
  registerEjectCommand(cmd);
43309
+ registerMigrateCommand(cmd);
42659
43310
  registerPublishCommands(cmd);
42660
43311
  registerSecretsCommand(cmd);
42661
43312
  }