@voltro/cli 0.48.0 → 0.49.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.
Files changed (98) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/dist/{apiBuild-Dz8TJSxp.js → apiBuild-QmYHaCF4.js} +1 -1
  3. package/dist/apiBuild-dZbHdqMg.js +2 -0
  4. package/dist/bin.js +1 -1
  5. package/dist/{build-DLme2ppa.js → build-Bi4O_g7T.js} +6 -6
  6. package/dist/{checkCommand-Dals7g-I.js → checkCommand-D8vjQXQt.js} +3 -3
  7. package/dist/{checkCommand-BUBqPBlI.js → checkCommand-udbQpphy.js} +1 -1
  8. package/dist/{codegenCommand-L6vacVRW.js → codegenCommand-DApSH7hK.js} +39 -47
  9. package/dist/{codemodRunner-DSZjgyCL.js → codemodRunner-De1_316I.js} +562 -492
  10. package/dist/{commands-CAxFLqG4.js → commands-a5PxCaIg.js} +68 -60
  11. package/dist/{dashboardCommand-CJC8Kg-s.js → dashboardCommand-DaoUUqJS.js} +1 -1
  12. package/dist/dataCommand-CJv_OMoS.js +1156 -0
  13. package/dist/dataProfile-Du3ztYxv.js +51 -0
  14. package/dist/{dbCommand-ZGNItjoJ.js → dbCommand-Bf7Cy0mn.js} +2 -2
  15. package/dist/dbCommand-Bnl7MSGC.js +2 -0
  16. package/dist/{dev-lvnVq5RD.js → dev-C31Nvlbv.js} +1 -1
  17. package/dist/{dev-cGGsLNn6.js → dev-DFVuzOj7.js} +1 -1
  18. package/dist/{doctorCommand-BK0qu7eD.js → doctorCommand-B3uraeAe.js} +12 -12
  19. package/dist/doctorCommand-CPL6EhrW.js +2 -0
  20. package/dist/{dormancyCommand-CyIk-zq4.js → dormancyCommand-QUXQ9yoz.js} +1 -1
  21. package/dist/{embeddingsCommand-D7TLklps.js → embeddingsCommand-Zw1-rYSF.js} +1 -1
  22. package/dist/{envCommand-BHxKkGXq.js → envCommand-DtaJ4xEf.js} +1 -1
  23. package/dist/{evolveCommand-CQh6dw21.js → evolveCommand-JDD3hE1i.js} +2 -2
  24. package/dist/{frameworkTableAssembly-BNod_DKN.js → frameworkTableAssembly-BwJVEKLr.js} +3 -3
  25. package/dist/frameworkTableAssembly-CVDB2hCq.js +2 -0
  26. package/dist/index.js +1 -1
  27. package/dist/{infoCommand-CuNl9cbh.js → infoCommand-COsUC1DB.js} +1 -1
  28. package/dist/{migrate-CL5Ed01M.js → migrate-D3MK9BpK.js} +2 -2
  29. package/dist/{runtimeTrace-C0SlIoQY.js → runtimeTrace-Di6fcndp.js} +1 -1
  30. package/dist/{sdkgen-BXm7zx7F.js → sdkgen-CIi5gM17.js} +1 -1
  31. package/dist/serveCommand-CzSDngKm.js +2 -0
  32. package/dist/serveCommand-N3udT49p.js +2362 -0
  33. package/dist/serveEntry.js +5 -5
  34. package/dist/{subcommandNames-CKG5Dz3a.js → subcommandNames-DpYs3DXr.js} +12 -2
  35. package/dist/{updateCommand-BlyXavoG.js → updateCommand-2BfbeMvp.js} +1 -1
  36. package/dist/updateCommand-CtYm7aKH.js +2 -0
  37. package/dist/{webhooksCommand-QlAk_tED.js → webhooksCommand-CwX9IzvJ.js} +1 -1
  38. package/package.json +29 -17
  39. package/templates/AGENTS.md +1 -1
  40. package/templates/agent-docs/_index.md +1 -1
  41. package/templates/agent-docs/cli.md +71 -13
  42. package/templates/agent-docs/whats-new.md +34 -47
  43. package/templates/apps/api-ai/package.json +7 -7
  44. package/templates/apps/api-auth/package.json +8 -8
  45. package/templates/apps/api-backend/package.json +7 -7
  46. package/templates/apps/api-backend-deactivation/package.json +7 -7
  47. package/templates/apps/api-backend-mail/package.json +8 -8
  48. package/templates/apps/api-backend-mariadb/package.json +9 -9
  49. package/templates/apps/api-backend-sqlite/package.json +8 -8
  50. package/templates/apps/api-backend-storage/package.json +8 -8
  51. package/templates/apps/api-cms/package.json +10 -10
  52. package/templates/apps/api-collab/package.json +8 -8
  53. package/templates/apps/api-data-advanced/package.json +8 -8
  54. package/templates/apps/api-durable/package.json +8 -8
  55. package/templates/apps/api-feature-flags/package.json +9 -9
  56. package/templates/apps/api-governance/package.json +8 -8
  57. package/templates/apps/api-kv/package.json +8 -8
  58. package/templates/apps/api-moderation/package.json +8 -8
  59. package/templates/apps/api-observability/package.json +8 -8
  60. package/templates/apps/api-ratelimit/package.json +8 -8
  61. package/templates/apps/api-rbac/package.json +8 -8
  62. package/templates/apps/api-rest/package.json +7 -7
  63. package/templates/apps/api-saas/package.json +11 -11
  64. package/templates/apps/api-saas-starter/package.json +10 -10
  65. package/templates/apps/api-search/package.json +8 -8
  66. package/templates/apps/api-status/package.json +8 -8
  67. package/templates/apps/api-versioning/package.json +8 -8
  68. package/templates/apps/api-webhooks/package.json +9 -9
  69. package/templates/apps/changelog/package.json +6 -6
  70. package/templates/apps/edge-functions/package.json +2 -2
  71. package/templates/apps/frontend-admin/package.json +8 -8
  72. package/templates/apps/frontend-app/package.json +9 -9
  73. package/templates/apps/frontend-auth/package.json +8 -8
  74. package/templates/apps/frontend-blank/package.json +7 -7
  75. package/templates/apps/frontend-cms/package.json +9 -9
  76. package/templates/apps/frontend-collab/package.json +10 -10
  77. package/templates/apps/frontend-contact/package.json +7 -7
  78. package/templates/apps/frontend-dashboard/package.json +7 -7
  79. package/templates/apps/frontend-docs/package.json +7 -7
  80. package/templates/apps/frontend-i18n/package.json +6 -6
  81. package/templates/apps/frontend-landing/package.json +7 -7
  82. package/templates/apps/frontend-portal/package.json +8 -8
  83. package/templates/apps/frontend-saas/package.json +8 -8
  84. package/templates/apps/frontend-spa/package.json +7 -7
  85. package/templates/apps/frontend-ssr/package.json +7 -7
  86. package/templates/apps/frontend-ssr-api/package.json +8 -8
  87. package/templates/apps/frontend-static-blog/package.json +6 -6
  88. package/templates/apps/frontend-status/package.json +8 -8
  89. package/templates/apps/mobile-app/package.json +4 -4
  90. package/dist/apiBuild-DOnvi2zm.js +0 -2
  91. package/dist/dataCommand-hIaq2iKY.js +0 -1052
  92. package/dist/dataProfile-Cm0YVKSy.js +0 -18
  93. package/dist/dbCommand-D1Q33ktl.js +0 -2
  94. package/dist/doctorCommand-CWgUPye-.js +0 -2
  95. package/dist/frameworkTableAssembly-Rft-DPUg.js +0 -2
  96. package/dist/serveCommand-CV3YO9L3.js +0 -2035
  97. package/dist/serveCommand-ZP_Cb-yz.js +0 -2
  98. package/dist/updateCommand-CT5AvVg7.js +0 -2
@@ -1,1052 +0,0 @@
1
- import { t as e } from "./cliError-BmdYnghb.js";
2
- import { c as t, i as n, o as r, z as i } from "./dev-lvnVq5RD.js";
3
- import { n as a, t as o } from "./cliArgs-D4p8n7EE.js";
4
- import { r as s } from "./dialectDriver-czCHYpeH.js";
5
- import { t as c } from "./dataProfile-Cm0YVKSy.js";
6
- import { o as l, t as u } from "./inspectFetch-EMuhTG_9.js";
7
- import { r as d } from "./dbCommand-ZGNItjoJ.js";
8
- import { resolve as f } from "node:path";
9
- import { createLogger as p } from "@voltro/logger";
10
- import { IMPORT_RUNS_TABLE as m, connectionIdentity as h, normaliseTarget as g, sameDatabase as _, streamTable as v } from "@voltro/database";
11
- import { Effect as y, Stream as b } from "effect";
12
- import { SqlClient as x } from "@effect/sql";
13
- import { declaredSnapshot as ee, fingerprintSchema as te, introspectSchema as ne } from "@voltro/database/sql";
14
- import { STORAGE_REFS_TABLE as re, resolveStorageProvider as S } from "@voltro/plugin-storage";
15
- import { createHash as ie } from "node:crypto";
16
- import { asImportError as ae, assessLiveImport as oe, backupArtifactName as C, backupCommand as se, classificationFromSnapshot as ce, decryptStream as w, encryptStream as le, packBundle as ue, peekBundle as T, previewMasking as de, restoreCommand as E, runExport as D, runImport as O, runNativeStep as k, storageAssetSink as fe, storageAssetSource as pe, storageBlobSink as me, storageBlobSource as he, unpackBundle as ge, unpackBundleToDir as A } from "@voltro/data-transfer";
17
- import { request as _e } from "node:http";
18
- import { request as ve } from "node:https";
19
- //#region src/longRequest.ts
20
- var ye = /* @__PURE__ */ new Set([
21
- "ECONNREFUSED",
22
- "ETIMEDOUT",
23
- "EHOSTUNREACH",
24
- "ENETUNREACH",
25
- "ENOTFOUND",
26
- "ECONNRESET",
27
- "EAI_AGAIN"
28
- ]), j = class extends Error {
29
- url;
30
- cause;
31
- constructor(e, t) {
32
- let n = (() => {
33
- try {
34
- return new URL(e).host;
35
- } catch {
36
- return e;
37
- }
38
- })();
39
- super(`the instance at ${n} is not answering (${t.code ?? "connect failed"}).`), this.url = e, this.cause = t, this.name = "InstanceUnreachable";
40
- }
41
- }, M = class extends Error {
42
- elapsedMs;
43
- url;
44
- constructor(e, t) {
45
- super(`no response after ${Math.round(e / 1e3)}s`), this.elapsedMs = e, this.url = t, this.name = "LongRequestTimeout";
46
- }
47
- }, N = async (e, t, n, r) => {
48
- let i = new URL(e), a = i.protocol === "https:" ? ve : _e, o = Date.now();
49
- return await new Promise((s, c) => {
50
- let l = a({
51
- protocol: i.protocol,
52
- hostname: i.hostname,
53
- port: i.port === "" ? void 0 : Number(i.port),
54
- path: `${i.pathname}${i.search}`,
55
- method: "POST",
56
- headers: n
57
- }, (e) => {
58
- let t = [];
59
- e.on("data", (e) => t.push(e)), e.on("end", () => s({
60
- status: e.statusCode ?? 0,
61
- headers: Object.fromEntries(Object.entries(e.headers).map(([e, t]) => [e, Array.isArray(t) ? t.join(", ") : String(t ?? "")])),
62
- body: Buffer.concat(t)
63
- })), e.on("error", c);
64
- });
65
- if (r?.timeoutMs !== void 0 && r.timeoutMs > 0 && l.setTimeout(r.timeoutMs, () => {
66
- l.destroy(new M(Date.now() - o, e));
67
- }), l.on("error", (t) => c(ye.has(t.code ?? "") ? new j(e, t) : t)), typeof t == "string" || Buffer.isBuffer(t)) {
68
- l.end(t);
69
- return;
70
- }
71
- (async () => {
72
- try {
73
- for await (let e of t) l.write(Buffer.from(e)) || await new Promise((e) => l.once("drain", () => e()));
74
- l.end();
75
- } catch (e) {
76
- l.destroy(e);
77
- }
78
- })();
79
- });
80
- }, be = (e) => `${e.message}\n That address came from --api-url (or VOLTRO_API_URL) — it is the running instance, not the database.\n Nothing was sent, so nothing was imported. Check the instance is up and reachable from here\n (a VPN, an ingress or a stopped deployment are the usual three), e.g. curl -sS ${e.url}/_voltro/inspect/app`, xe = (e, t) => `the instance did not answer within ${Math.round(e.elapsedMs / 1e3)}s. This is a client-side deadline, not a failure on the server: the upload itself finished long before, and the response arrives only when the import does. The instance is very probably STILL IMPORTING and will finish.\n` + (t === "replace" ? " Do NOT simply re-run: --mode replace empties the target first, so a second run started while the first is mid-flight would empty it under the first one. Check the instance's log for the import's completion, and check the target's row counts, before deciding." : ` Re-running the same bundle is safe once the first run has finished (--mode ${t} is idempotent), but check the instance's log first — the work may already be done.`) + "\n To keep a deadline anyway, pass --timeout <seconds>; the default is to wait.", Se = 16777216, Ce = async function* (e, t) {
81
- let n = [], r = 0, i = 0, a = function* (e) {
82
- let t = Buffer.concat(n);
83
- n = [], r = 0;
84
- let a = {
85
- bytes: t,
86
- offset: i,
87
- final: e
88
- };
89
- i += t.byteLength, yield a;
90
- };
91
- for await (let a of e) for (n.push(Buffer.from(a)), r += a.byteLength; r >= t;) {
92
- let e = Buffer.concat(n), a = e.subarray(0, t), o = e.subarray(t);
93
- n = o.byteLength > 0 ? [Buffer.from(o)] : [], r = o.byteLength;
94
- let s = {
95
- bytes: Buffer.from(a),
96
- offset: i,
97
- final: !1
98
- };
99
- i += a.byteLength, yield s;
100
- }
101
- yield* a(!0);
102
- }, we = (e) => ie("sha256").update(Buffer.from(e)).digest("hex"), Te = async (e) => {
103
- let t = 0, n = 0, r = {
104
- status: 0,
105
- body: {}
106
- };
107
- for await (let i of Ce(e.stream, e.chunkBytes)) {
108
- if (i.offset + i.bytes.byteLength <= e.alreadyHeld && !i.final) {
109
- n++;
110
- continue;
111
- }
112
- let a = Math.max(0, e.alreadyHeld - i.offset), o = a > 0 ? i.bytes.subarray(a) : i.bytes, s = i.offset + a;
113
- if (o.byteLength === 0 && !i.final) {
114
- n++;
115
- continue;
116
- }
117
- if (i.final && e.onFinalChunk?.(), r = await e.target.send(Buffer.from(o), {
118
- ...e.baseHeaders,
119
- "content-type": "application/octet-stream",
120
- "x-import-upload-id": e.uploadId,
121
- "x-import-upload-key": e.key,
122
- "x-import-chunk-offset": String(s),
123
- ...i.final ? { "x-import-chunk-final": "1" } : {}
124
- }), n++, t += o.byteLength, e.onProgress?.(t), r.status >= 400) break;
125
- }
126
- return {
127
- status: r.status,
128
- body: r.body,
129
- chunks: n,
130
- bytes: t,
131
- resumedFrom: e.alreadyHeld
132
- };
133
- }, P = "voltro-backup-stamp.json", Ee = (e) => ({
134
- stampVersion: 1,
135
- dialect: e.dialect,
136
- schemaFingerprint: e.schemaFingerprint,
137
- voltroVersion: e.voltroVersion,
138
- createdAt: e.createdAt
139
- }), De = (e) => {
140
- let t;
141
- try {
142
- t = JSON.parse(e);
143
- } catch {
144
- return null;
145
- }
146
- if (typeof t != "object" || !t) return null;
147
- let n = t;
148
- if (n.stampVersion !== 1 || typeof n.dialect != "string" || typeof n.voltroVersion != "string" || typeof n.createdAt != "string") return null;
149
- let r = n.schemaFingerprint;
150
- return r !== null && typeof r != "string" ? null : {
151
- stampVersion: 1,
152
- dialect: n.dialect,
153
- schemaFingerprint: r,
154
- voltroVersion: n.voltroVersion,
155
- createdAt: n.createdAt
156
- };
157
- }, Oe = (e) => {
158
- let { stamp: t, currentDialect: n, currentFingerprint: r } = e;
159
- if (t === null) return {
160
- warn: `no ${P} beside the dump — an older/handmade backup. Cannot verify dialect or schema version; make sure this dump is a ${n} dump.`,
161
- info: []
162
- };
163
- let i = [`backup produced by @voltro/cli ${t.voltroVersion} at ${t.createdAt}`, `schema fingerprint: ${t.schemaFingerprint ?? "<none recorded>"}`];
164
- return t.dialect === n ? t.schemaFingerprint !== null && r !== null && t.schemaFingerprint !== r ? {
165
- warn: `schema skew — the backup's schema (${t.schemaFingerprint.slice(0, 12)}) differs from what this code declares (${r.slice(0, 12)}). Run \`voltro db apply\` after the restore, or the app may boot against a schema it doesn't understand.`,
166
- info: i
167
- } : { info: i } : {
168
- refuse: `dialect mismatch — backup is a ${t.dialect} dump, but DB_DIALECT is ${n}. A cross-dialect restore is never valid.`,
169
- info: i
170
- };
171
- }, F = (e) => {
172
- try {
173
- let t = new URL(e), n = t.pathname.replace(/^\//, "");
174
- return `${t.hostname.toLowerCase()}:${t.port || "(default)"}/${n}`;
175
- } catch {
176
- return e.trim();
177
- }
178
- }, ke = (e) => {
179
- let t = e.flagUrl ?? e.envUrl;
180
- if (t === void 0 || t.trim() === "") return {
181
- ok: !1,
182
- error: "no drill target — pass `--drill-url <url>` or set `DRILL_DB_URL`. The drill restores into a THROWAWAY database (never the live one), so it needs its own connection."
183
- };
184
- let n = F(t);
185
- return e.liveKeys.some((e) => e === n) ? {
186
- ok: !1,
187
- error: `drill target (${n}) is the LIVE database — a restore drill must target a throwaway DB, never production. It would --clean and overwrite it.`
188
- } : {
189
- ok: !0,
190
- url: t
191
- };
192
- }, Ae = (e) => {
193
- let { stampFingerprint: t, restoredFingerprint: n, restoredTableCount: r } = e;
194
- return r === 0 ? {
195
- pass: !1,
196
- lines: ["FAIL — the restore produced ZERO tables. The dump is empty or unreadable; this backup would NOT recover your app."]
197
- } : t !== null && n !== null && t !== n ? {
198
- pass: !1,
199
- lines: [`FAIL — restored ${r} table(s), but the schema fingerprint (${n.slice(0, 12)}) does NOT match the backup's stamp (${t.slice(0, 12)}).`, "The restore did not reproduce the schema that was backed up — the artifact is inconsistent."]
200
- } : t === null || n === null ? {
201
- pass: !0,
202
- lines: [`PASS (partial) — restored ${r} table(s) into the throwaway DB.`, "No stamped fingerprint to cross-check the schema shape (older/hand-made backup) — the bytes restore, but the shape was not verified."]
203
- } : {
204
- pass: !0,
205
- lines: [`PASS — restored ${r} table(s); schema fingerprint matches the backup stamp (${n.slice(0, 12)}).`]
206
- };
207
- }, I = p({ scope: "voltro:data" }), je = async () => {
208
- try {
209
- let { createRequire: e } = await import("node:module"), { join: t } = await import("node:path"), { readFileSync: n } = await import("node:fs"), r = e(t(process.cwd(), "package.json")).resolve("@voltro/cli/package.json");
210
- return JSON.parse(n(r, "utf8")).version ?? "unknown";
211
- } catch {
212
- return "unknown";
213
- }
214
- }, L = async (e) => {
215
- try {
216
- return te(await W(e));
217
- } catch {
218
- return null;
219
- }
220
- }, R = (e) => {
221
- if (e.event !== "done") return;
222
- let t = e.total === void 0 ? "" : ` / ${e.total}`;
223
- I.info(`${e.phase} [${e.index + 1}/${e.tableCount}] ${e.table}`, { rows: `${e.rowsDone}${t}` });
224
- }, Me = async (e) => {
225
- let t = (e) => e?.meta?.databaseId;
226
- if (e) {
227
- let n = await u({
228
- name: "target",
229
- url: e
230
- }, "/_voltro/inspect/app");
231
- if (n.kind === "ok") return {
232
- label: e,
233
- databaseId: t(n.data)
234
- };
235
- }
236
- for (let e of await l()) {
237
- let n = await u(e, "/_voltro/inspect/app");
238
- if (n.kind === "ok") return {
239
- label: `${e.name} (${e.url})`,
240
- databaseId: t(n.data)
241
- };
242
- }
243
- return null;
244
- }, z = async (e) => {
245
- let t = e.includes("--allow-live"), n = t ? null : await Me(B(e, "--api-url")), i = h({
246
- dialect: H(),
247
- ...r()
248
- }), a = g({
249
- dialect: H(),
250
- ...r()
251
- }), { refuse: o, message: s } = oe({
252
- liveInstance: n?.label ?? null,
253
- allowLive: t,
254
- sameTarget: _(i, n?.databaseId),
255
- ...a === void 0 ? {} : { targetLabel: `${a.host}:${a.port}/${a.database}` }
256
- });
257
- return !o || (I.error(s ?? "refusing: live instance detected"), !1);
258
- }, B = a, Ne = [
259
- "--api-url",
260
- "--bundle-key",
261
- "--compression",
262
- "--consistency",
263
- "--drill-url",
264
- "--chunk-size",
265
- "--exclude",
266
- "--limit",
267
- "--mode",
268
- "--no-atomic",
269
- "--on-conflict",
270
- "--passphrase",
271
- "--profile",
272
- "--tables",
273
- "--target",
274
- "--timeout",
275
- "--tenant",
276
- "--token"
277
- ], V = (e) => o(e, Ne), H = () => {
278
- let t = (process.env.DB_DIALECT ?? "postgres").toLowerCase();
279
- if (t === "memory") throw new e("voltro data: requires a real dialect, not DB_DIALECT=memory.");
280
- return t;
281
- }, U = async (e, t) => {
282
- let n = (await s(e)).makeSqlLayer(t);
283
- return y.runPromise(x.SqlClient.pipe(y.flatMap(ne), y.provide(n)));
284
- }, W = (e) => U(e, r()), Pe = () => {
285
- let e = r(), t = [];
286
- return e.url && t.push(F(e.url)), (e.host || e.database) && t.push(`${(e.host ?? "localhost").toLowerCase()}:${e.port ?? "(default)"}/${e.database ?? ""}`), t;
287
- }, G = async () => {
288
- let r = process.cwd(), i = await t(r);
289
- if (!i) throw new e("voltro data: no app.config.ts found in the current directory.");
290
- let a = await n(i, void 0), o = H();
291
- return {
292
- store: a,
293
- snapshot: await W(o),
294
- dialect: o
295
- };
296
- }, K = (e) => v(e, {
297
- table: re,
298
- chunkSize: 500
299
- }).pipe(b.map((e) => ({
300
- key: String(e.key),
301
- contentType: String(e.contentType ?? "application/octet-stream"),
302
- size: Number(e.size ?? 0)
303
- }))), q = (e) => !!e && e.endsWith(".vbundle"), J = (e) => B(e, "--passphrase") ?? process.env.VOLTRO_BUNDLE_KEY, Fe = (e) => e.includes("--encrypt") || B(e, "--passphrase") !== void 0 || process.env.VOLTRO_BUNDLE_KEY !== void 0, Ie = async (e, t) => {
304
- let { createWriteStream: n } = await import("node:fs"), { pipeline: r } = await import("node:stream/promises"), { Readable: i } = await import("node:stream");
305
- await r(i.from(e), n(t));
306
- }, Y = (e) => ({ async *[Symbol.asyncIterator]() {
307
- let { createReadStream: t } = await import("node:fs");
308
- for await (let n of t(e)) yield n instanceof Uint8Array ? n : new Uint8Array(n);
309
- } }), Le = async (e, t) => {
310
- if (t !== void 0 || e === void 0) return null;
311
- try {
312
- let { resolve: t, join: n } = await import("node:path"), r = await import("node:fs/promises"), i = t(process.cwd(), e), a = q(e) ? (await T(Y(i), ["manifest.json"])).get("manifest.json") : await r.readFile(n(i, "manifest.json"));
313
- if (a === void 0) return null;
314
- let o = (JSON.parse(Buffer.from(a).toString("utf8")).tables ?? []).map((e) => e.name).filter((e) => typeof e == "string");
315
- return o.length > 0 ? o : null;
316
- } catch {
317
- return null;
318
- }
319
- }, X = (e) => (e ?? "").split(",").map((e) => e.trim()).filter(Boolean), Re = (t, n) => {
320
- let r = B(t, "--tenant"), i = B(t, "--tables"), a = B(t, "--exclude");
321
- if (a !== void 0) {
322
- if (i !== void 0) throw new e("voltro data export: --exclude and --tables are two ways to say the same thing; use one.");
323
- if (r !== void 0) throw new e("voltro data export: --exclude does not apply to --tenant, whose table set is derived from the tenant closure.");
324
- let t = X(a), o = new Set(n), s = t.filter((e) => !o.has(e));
325
- if (s.length > 0) throw new e(`voltro data export: --exclude names ${s.length} table(s) that do not exist: ${s.join(", ")}. An exclusion that excludes nothing would leave the run looking like it worked.`);
326
- return {
327
- kind: "all",
328
- exclude: t
329
- };
330
- }
331
- return r ? {
332
- kind: "tenant",
333
- tenantId: r
334
- } : i ? {
335
- kind: "tables",
336
- tables: X(i)
337
- } : { kind: "all" };
338
- }, ze = async () => {
339
- let e = await d(process.cwd());
340
- return ce(ee(e));
341
- }, Be = "voltro/tenant", Ve = async () => {
342
- let e = (await d(process.cwd())).filter((e) => (e.appliedMixins ?? []).some((e) => e.id === Be)).map((e) => e.tableName);
343
- return e.length > 0 ? e : void 0;
344
- }, He = (e) => {
345
- for (let t of e.tables) if (t.samples.length !== 0) {
346
- console.log(`\n ${t.table}`);
347
- for (let e of t.samples) console.log(` ${e.column} [${e.action}] ${JSON.stringify(e.before)} → ${JSON.stringify(e.after)}`);
348
- }
349
- if (e.leaks.length > 0) {
350
- console.log("\n ⚠ possible leaks in KEPT columns:");
351
- for (let t of e.leaks) console.log(` ${t.table}.${t.column} looks like ${t.pattern}: ${JSON.stringify(t.sample)}`);
352
- }
353
- if (e.unclassified.length > 0) {
354
- console.log("\n ✗ unclassified (would BLOCK a real export — add .sensitive()/.safe() or a policy override):");
355
- for (let t of e.unclassified) console.log(` ${t}`);
356
- } else console.log("\n ✓ every exported column is classified — safe to run.");
357
- }, Ue = async (t) => {
358
- let { resolve: n, join: r } = await import("node:path"), i = await import("node:fs/promises"), a = B(t.args, "--chunk-size"), o = a === void 0 ? Se : Math.round(Number(a) * 1024 * 1024);
359
- if (!Number.isFinite(o) || o <= 0) throw new e(`--chunk-size expects a positive number of megabytes, got '${String(a)}'`);
360
- let s = t.stream[Symbol.asyncIterator](), c = [], l = 0, u = !1;
361
- for (; l <= o;) {
362
- let e = await s.next();
363
- if (e.done === !0) {
364
- u = !0;
365
- break;
366
- }
367
- c.push(Buffer.from(e.value)), l += e.value.byteLength;
368
- }
369
- if (u && l <= o) return {
370
- kind: "small",
371
- body: Buffer.concat(c)
372
- };
373
- let d = n(process.cwd(), t.bundleDir), f = we(q(t.bundleDir) ? await i.readFile(d) : await i.readFile(r(d, "manifest.json"))), p = `up-${f.slice(0, 32)}`, m = await N(t.url, Buffer.alloc(0), {
374
- ...t.headers,
375
- "x-import-upload-id": p,
376
- "x-import-probe": "1"
377
- }, Q(t.args)), h = m.status === 200 ? Number(JSON.parse(m.body.toString("utf8")).bytes ?? 0) : 0;
378
- h > 0 && t.log.info("api import: resuming a chunked upload the instance already holds", { bytes: h });
379
- let g = (async function* () {
380
- for (let e of c) yield e;
381
- for (;;) {
382
- let e = await s.next();
383
- if (e.done === !0) return;
384
- yield e.value;
385
- }
386
- })(), _ = 0, v = await Te({
387
- stream: g,
388
- chunkBytes: o,
389
- uploadId: p,
390
- key: f,
391
- alreadyHeld: h,
392
- baseHeaders: t.headers,
393
- onProgress: (e) => {
394
- _++, t.log.info(`api import: uploading — chunk ${_}, ${Math.round(e / 1024)} KiB sent`);
395
- },
396
- onFinalChunk: () => {
397
- t.log.info("api import: upload done — the instance is importing now. This request stays open until it finishes, which on a full bundle is minutes, and nothing more is printed until then. It is not a hang; the instance logs the import itself.");
398
- },
399
- target: { send: async (e, n) => {
400
- let r = await N(t.url, e, n, Q(t.args)), i = {};
401
- try {
402
- i = JSON.parse(r.body.toString("utf8") || "{}");
403
- } catch {}
404
- return {
405
- status: r.status,
406
- body: i
407
- };
408
- } }
409
- });
410
- return t.log.info("api import: uploaded in chunks", {
411
- chunks: v.chunks,
412
- bytes: v.bytes,
413
- ...v.resumedFrom > 0 ? { resumedFrom: v.resumedFrom } : {}
414
- }), {
415
- kind: "sent",
416
- res: {
417
- status: v.status,
418
- headers: {},
419
- body: Buffer.from(JSON.stringify(v.body))
420
- }
421
- };
422
- }, We = (e) => `--mode replace with --no-atomic against a ${e ? "RUNNING instance" : "live database"}: the target is empty between the delete and the load, and anything the application writes in that window can collide with a row from the bundle — or survive the import as a row the bundle never carried. Drop --no-atomic to run the whole load in one transaction (concurrent writers then wait instead of racing), or stop the traffic for the duration.`, Z = (e, t) => e.includes("--no-atomic") ? !1 : e.includes("--atomic") || t === "replace", Ge = (e, t, n) => {
423
- if (t !== "replace" || e.includes("--no-rollback")) return;
424
- let r = B(e, "--rollback-dir");
425
- return r === void 0 ? i(n) : f(r);
426
- }, Ke = (e, t, n) => {
427
- let r = Ge(e, t, n);
428
- return {
429
- ...r === void 0 ? {} : { rollbackDir: r },
430
- recordInterruption: !0,
431
- via: "direct"
432
- };
433
- }, Q = (t) => {
434
- let n = B(t, "--timeout");
435
- if (n === void 0) return {};
436
- let r = Number(n);
437
- if (!Number.isFinite(r) || r <= 0) throw new e(`--timeout expects a positive number of seconds, got '${n}'`);
438
- return { timeoutMs: Math.round(r * 1e3) };
439
- }, qe = async (e) => {
440
- let t = B(e, "--target") === "api", n = B(e, "--bundle-key"), r = V(e);
441
- if (!r && !(t && n)) return I.error("usage: voltro data export <outDir> [--target direct|api] [--api-url <url>] [--token <secret>] [--timeout <seconds>] [--profile <name>] [--tenant <id>] [--tables a,b] [--exclude a,b] [--bundle-key <storage-key>] [--assets] [--compression zstd|gzip|none] [--consistency live|snapshot] [--dry-run]"), 1;
442
- if (t) {
443
- let t = B(e, "--api-url");
444
- if (!t) return I.error("--target api requires --api-url <url> (the running instance)"), 1;
445
- let i = B(e, "--token") ?? process.env.VOLTRO_DATA_TRANSFER_SECRET;
446
- if (!i) return I.error("--target api requires --token <secret> (or VOLTRO_DATA_TRANSFER_SECRET) matching the instance secret"), 1;
447
- let a = B(e, "--tables"), o = B(e, "--exclude");
448
- if (o !== void 0 && a !== void 0) return I.error("voltro data export: --exclude and --tables are two ways to say the same thing; use one."), 1;
449
- let s = {
450
- ...B(e, "--profile") ? { profile: B(e, "--profile") } : {},
451
- ...B(e, "--tenant") ? { tenant: B(e, "--tenant") } : {},
452
- ...a ? { tables: a.split(",").map((e) => e.trim()).filter(Boolean) } : {},
453
- ...o ? { exclude: o.split(",").map((e) => e.trim()).filter(Boolean) } : {},
454
- ...B(e, "--consistency") === "snapshot" ? { consistency: "snapshot" } : {},
455
- ...B(e, "--compression") ? { compression: B(e, "--compression") } : {},
456
- ...e.includes("--assets") ? { assets: !0 } : {},
457
- ...n ? { bundleKey: n } : {}
458
- }, c;
459
- try {
460
- c = await N(`${t.replace(/\/+$/, "")}/_voltro/admin/export`, JSON.stringify(s), {
461
- "content-type": "application/json",
462
- authorization: `Bearer ${i}`
463
- }, Q(e));
464
- } catch (e) {
465
- if (e instanceof M) return I.error(`api export: the instance did not answer within ${Math.round(e.elapsedMs / 1e3)}s. That is a client-side deadline, not a server failure — the response arrives only when the export does. Nothing was written locally; re-run, or pass --timeout <seconds> (the default is to wait).`), 1;
466
- if (e instanceof j) return I.error(`api export: ${be(e)}`), 1;
467
- throw e;
468
- }
469
- if (c.status < 200 || c.status >= 300) return I.error(`api export failed: HTTP ${c.status} — ${c.body.toString("utf8")}`), 1;
470
- if (n) return I.info("api export complete (pushed to storage)", {
471
- via: t,
472
- ...JSON.parse(c.body.toString("utf8"))
473
- }), 0;
474
- let { resolve: l } = await import("node:path"), u = new Uint8Array(c.body);
475
- return await A((async function* () {
476
- yield u;
477
- })(), l(process.cwd(), r)), I.info("api export complete (downloaded from the running instance)", {
478
- outDir: r,
479
- tables: c.headers["x-export-tables"],
480
- rows: c.headers["x-export-rows"],
481
- masked: c.headers["x-export-masked"]
482
- }), 0;
483
- }
484
- if (!r) return I.error("a <outDir> is required for a direct export"), 1;
485
- let i = B(e, "--profile"), a = i ? await c(i, { allowPath: !0 }) : {}, { store: o, snapshot: s, dialect: l } = await G(), u = e.includes("--assets") || a.assets === !0, d = u ? S({}) : void 0, f = B(e, "--compression") ?? a.compression, p = B(e, "--consistency") === "snapshot" ? "snapshot" : a.consistency ?? "live", m = a.masking, h = a.subset, g = a.scope ?? Re(e, s.tables.map((e) => e.name)), _ = m ? await ze() : void 0, v = g.kind === "tenant" ? await Ve() : void 0, b = v ? { tenantTables: v } : {};
486
- if (e.includes("--dry-run")) {
487
- let e = g.kind === "tables" && g.tables ? [...g.tables] : s.tables.map((e) => e.name);
488
- if (I.info("export DRY RUN — nothing was written", {
489
- outDir: r,
490
- tables: e.length,
491
- scope: g.kind,
492
- consistency: p,
493
- compression: f ?? "zstd",
494
- assets: u,
495
- masking: m ? "profile policy applies" : "none"
496
- }), I.info(`would export: ${e.join(", ")}`), !m) return 0;
497
- let t = await y.runPromise(de({
498
- store: o,
499
- snapshot: s,
500
- masking: m,
501
- ..._ ? { classification: _ } : {},
502
- ...h ? {} : {
503
- scope: g,
504
- ...b
505
- }
506
- }));
507
- return He(t), +(t.unclassified.length > 0);
508
- }
509
- if (q(r)) {
510
- let t = await import("node:os"), n = await import("node:fs/promises"), { resolve: i, join: a } = await import("node:path"), c = await n.mkdtemp(a(t.tmpdir(), "voltro-export-"));
511
- try {
512
- let t = await y.runPromise(D({
513
- store: o,
514
- snapshot: s,
515
- dialect: l,
516
- outDir: c,
517
- ...h ? { subset: h } : {
518
- scope: g,
519
- ...b
520
- },
521
- consistency: p,
522
- ...f ? { compression: f } : {},
523
- ...m ? { masking: m } : {},
524
- ..._ ? { classification: _ } : {},
525
- onProgress: R
526
- })), n = ue({
527
- dir: c,
528
- ...d ? { blobs: he(d, () => K(o)) } : {}
529
- }), a = Fe(e);
530
- if (a) {
531
- let t = J(e);
532
- if (!t) return I.error("--encrypt requires --passphrase <p> or VOLTRO_BUNDLE_KEY (a dedicated key, NOT the transfer secret)"), 1;
533
- n = le(n, t);
534
- }
535
- return await Ie(n, i(process.cwd(), r)), I.info("export complete (single file)", {
536
- file: r,
537
- encrypted: a,
538
- assets: u,
539
- tables: t.tables.length,
540
- rows: t.tables.reduce((e, t) => e + t.rowCount, 0)
541
- }), 0;
542
- } finally {
543
- await n.rm(c, {
544
- recursive: !0,
545
- force: !0
546
- });
547
- }
548
- }
549
- let x = await y.runPromise(D({
550
- store: o,
551
- snapshot: s,
552
- dialect: l,
553
- outDir: r,
554
- ...h ? { subset: h } : {
555
- scope: g,
556
- ...b
557
- },
558
- consistency: p,
559
- ...f ? { compression: f } : {},
560
- ...m ? { masking: m } : {},
561
- ..._ ? { classification: _ } : {},
562
- ...d ? { assets: pe(d, () => K(o)) } : {},
563
- onProgress: R
564
- }));
565
- return I.info("export complete", {
566
- outDir: r,
567
- tables: x.tables.length,
568
- rows: x.tables.reduce((e, t) => e + t.rowCount, 0),
569
- assets: x.assets.count,
570
- compression: x.compression,
571
- ...x.masking ? { maskedColumns: x.masking.transformed.length } : {}
572
- }), 0;
573
- }, Je = () => "dry run checked: schema fit, cross-dialect portability, mode legality, the table selection. It did NOT read per-table checksums (those stream during the load) and cannot see conflicts that depend on the target's current rows.", Ye = (e) => {
574
- let t = B(e, "--tables");
575
- return {
576
- ...t ? { tables: t.split(",").map((e) => e.trim()).filter(Boolean) } : {},
577
- ...e.includes("--dry-run") ? { dryRun: !0 } : {}
578
- };
579
- }, Xe = (e) => ({
580
- tables: e.tablesWritten,
581
- rows: e.rowsWritten,
582
- carried: e.manifest.tables.reduce((e, t) => e + t.rowCount, 0),
583
- ...e.tablesSkipped > 0 ? {
584
- skippedTables: e.tablesSkipped,
585
- skippedRows: e.rowsSkipped
586
- } : {}
587
- }), Ze = (e, t) => {
588
- if (e.includes("--dry-run")) {
589
- I.info("import DRY RUN — nothing was written", t), I.info(Je());
590
- return;
591
- }
592
- if (t.rows === 0 && typeof t.skippedRows == "number" && t.skippedRows !== 0) {
593
- I.info("import complete — 0 rows written, every table was already applied by an earlier run of this bundle directory", t);
594
- return;
595
- }
596
- I.info("import complete", t);
597
- }, Qe = Symbol("refused"), $e = (e) => {
598
- let t = ae(e) ?? e;
599
- if (t?._tag !== "RowsRefusedError" || !Array.isArray(t.rows)) return !1;
600
- let n = t.rows, r = n.filter((e) => !e.derived), i = Number(t.totalCount ?? n.length), a = Number(t.primaryCount ?? r.length);
601
- I.error(`import refused ${i} row(s), of which ${a} are the actual failures — the rest could not land because a row they reference did not.`);
602
- let o = Array.isArray(t.byTable) ? t.byTable : [];
603
- o.length > 1 && I.error(` by table: ${o.map((e) => `${e.table} ${e.refused}`).join(", ")}`);
604
- for (let e of r) I.error(` ${e.table} ${e.id} ${e.reason}`);
605
- n.length < i && I.error(` (the list above is capped at ${n.length} of ${i} — the counts by table are complete)`);
606
- let s = i - a;
607
- return s > 0 && I.error(` … and ${s} row(s) behind them. Fix the ${a} above and re-run; they resolve with their parents.`), !0;
608
- }, et = (e) => {
609
- let t = typeof e == "string" ? e : e.toString("utf8"), n = t;
610
- try {
611
- let e = JSON.parse(t), r = e.error ?? e.message;
612
- typeof r == "string" && (n = r);
613
- } catch {}
614
- let r = n.indexOf("RowsRefusedError");
615
- if (r < 0) return;
616
- let i = n.indexOf("{", r);
617
- if (i < 0) return;
618
- let a = 0, o = !1, s = !1;
619
- for (let e = i; e < n.length; e++) {
620
- let t = n[e];
621
- if (o) {
622
- if (s) {
623
- s = !1;
624
- continue;
625
- }
626
- if (t === "\\") {
627
- s = !0;
628
- continue;
629
- }
630
- t === "\"" && (o = !1);
631
- continue;
632
- }
633
- if (t === "\"") {
634
- o = !0;
635
- continue;
636
- }
637
- if (t === "{") a++;
638
- else if (t === "}" && --a === 0) try {
639
- let t = JSON.parse(n.slice(i, e + 1));
640
- return Array.isArray(t.rows) ? {
641
- _tag: "RowsRefusedError",
642
- ...t
643
- } : void 0;
644
- } catch {
645
- return;
646
- }
647
- }
648
- }, tt = async (e) => {
649
- let t = B(e, "--target") === "api", n = B(e, "--bundle-key"), i = V(e);
650
- if (!i && !(t && n)) return I.error("usage: voltro data import <bundleDir> [--target direct|api] [--api-url <url>] [--token <secret>] [--timeout <seconds>] [--bundle-key <storage-key>] [--tables a,b] [--mode upsert|append|replace] [--on-conflict skip|fail] [--atomic] [--assets] [--no-verify] [--force] [--allow-live] [--dry-run] (--force: import despite schema drift AND cross-dialect warnings; --dry-run: report what would move, write nothing)"), 1;
651
- let a = B(e, "--mode") ?? "upsert", o = B(e, "--on-conflict") ?? "skip";
652
- if (t) {
653
- let t = B(e, "--api-url");
654
- if (!t) return I.error("--target api requires --api-url <url> (the running instance)"), 1;
655
- let r = B(e, "--token") ?? process.env.VOLTRO_DATA_TRANSFER_SECRET;
656
- if (!r) return I.error("--target api requires --token <secret> (or VOLTRO_DATA_TRANSFER_SECRET) matching the instance secret"), 1;
657
- let s = B(e, "--tables"), c = B(e, "--rollback-key");
658
- a === "replace" && c === void 0 && I.warn("api replace: no rollback capture — this run empties the target first and nothing was asked to be kept.\n Pass --rollback-key <storage-key> and the INSTANCE stores the target's current rows in its own\n object storage before deleting them, which is the one place that survives the pod going away.");
659
- let l = {
660
- authorization: `Bearer ${r}`,
661
- "x-import-mode": a,
662
- "x-import-on-conflict": o,
663
- ...Z(e, a) ? { "x-import-atomic": "1" } : {},
664
- ...e.includes("--no-atomic") ? { "x-import-atomic": "0" } : {},
665
- ...c === void 0 ? {} : { "x-import-rollback-key": c },
666
- ...e.includes("--force") ? { "x-import-force": "1" } : {},
667
- ...e.includes("--dry-run") ? { "x-import-dry-run": "1" } : {},
668
- ...s ? { "x-import-tables": s } : {}
669
- }, { resolve: u } = await import("node:path"), d;
670
- if (n) l["content-type"] = "application/json", d = JSON.stringify({ bundleKey: n });
671
- else if (q(i)) {
672
- let t = Y(u(process.cwd(), i)), n = J(e);
673
- n && (t = w(t, n)), l["content-type"] = "application/octet-stream", d = t;
674
- } else await (await import("node:fs/promises")).access(u(process.cwd(), i, "assets", "index.ndjson")).then(() => !0, () => !1) && I.warn("this directory bundle has assets; --target api uploads DATA ONLY. Pack a single-file `.vbundle` (voltro data export <name>.vbundle --assets) to transfer assets over the API."), l["content-type"] = "application/octet-stream", d = ue({ dir: u(process.cwd(), i) });
675
- if (a === "replace") {
676
- let r = await Le(i, n);
677
- {
678
- let i = r === null ? { bundleKey: n } : { tables: r }, a = await N(`${t.replace(/\/+$/, "")}/_voltro/admin/import`, JSON.stringify(i), {
679
- ...l,
680
- "content-type": "application/json",
681
- "x-import-preflight": "1"
682
- }, Q(e)).catch(() => null), o = a !== null && a.status === 200 ? JSON.parse(a.body.toString("utf8")) : null;
683
- o === null ? I.warn("api replace: the instance did not answer the preflight (an older build does not have it). The run still works; the decision will only be visible in the pod log.") : o.staged === !0 ? I.info(`api replace: the instance WILL stage — ${o.stagedTables ?? 0} table(s) load into copies and the\n target keeps its rows until one short swap at the end. Interrupting the load leaves the target intact.`) : I.warn(`api replace: the instance will NOT stage — it empties the target first and refills it, so an
684
- interrupted run leaves the target empty.\n Reason: ${o.reason ?? "not stated"}`);
685
- }
686
- }
687
- a === "replace" && !Z(e, a) && I.warn(We(!0));
688
- let f = `${t.replace(/\/+$/, "")}/_voltro/admin/import`, p;
689
- try {
690
- let t = typeof d == "string" ? null : await Ue({
691
- stream: d,
692
- url: f,
693
- headers: l,
694
- bundleDir: i,
695
- args: e,
696
- log: I
697
- });
698
- (t === null || t.kind === "small") && I.info("api import: uploading the bundle — this request stays open until the instance has imported it"), p = t === null ? await N(f, d, l, Q(e)) : t.kind === "sent" ? t.res : await N(f, t.body, l, Q(e));
699
- } catch (e) {
700
- if (e instanceof M) return I.error(`api import: ${xe(e, a)}`), 1;
701
- if (e instanceof j) return I.error(`api import: ${be(e)}`), 1;
702
- throw e;
703
- }
704
- if (p.status < 200 || p.status >= 300) return $e(et(p.body)) || I.error(`api import failed: HTTP ${p.status} — ${p.body.toString("utf8")}`), 1;
705
- let m = JSON.parse(p.body.toString("utf8"));
706
- return e.includes("--dry-run") ? (I.info("api import DRY RUN — nothing was written", {
707
- via: t,
708
- ...m
709
- }), I.info(Je()), 0) : (I.info("api import complete (imported by the running instance)", {
710
- via: t,
711
- ...m
712
- }), 0);
713
- }
714
- if (!i) return I.error("a <bundleDir> is required for a direct import"), 1;
715
- if (!await z(e)) return 1;
716
- a === "replace" && e.includes("--allow-live") && !Z(e, a) && I.warn(We(!1));
717
- let { store: s, snapshot: c } = await G();
718
- c.tables.some((e) => e.name === m) || I.warn(`this target has no \`${m}\` table, so this import will not be recorded.\n The import itself is unaffected. \`voltro db apply\` creates it.`), c.tables.some((e) => e.name === m) || I.warn(`this target has no \`${m}\` table, so this import will not be recorded.\n The import itself is unaffected. \`voltro db apply\` creates it.`);
719
- let l = e.includes("--force"), u = (e) => I.warn(e), d = e.includes("--assets") ? S({}) : void 0, f = H() === "postgres" ? (await import("@voltro/sql-postgres")).makePgCopySession(r()) : void 0;
720
- if (q(i)) {
721
- let t = await import("node:os"), n = await import("node:fs/promises"), { resolve: r, join: p } = await import("node:path"), m = await n.mkdtemp(p(t.tmpdir(), "voltro-import-"));
722
- try {
723
- let t = Y(r(process.cwd(), i)), n = J(e);
724
- return n && (t = w(t, n)), await ge(t, {
725
- dir: m,
726
- blobs: me(d ?? S({}))
727
- }), Ze(e, {
728
- file: i,
729
- ...Xe(await y.runPromise(O({
730
- store: s,
731
- bundleDir: m,
732
- mode: a,
733
- onConflict: o,
734
- atomic: Z(e, a),
735
- ...Ke(e, a, i),
736
- verify: !e.includes("--no-verify"),
737
- targetDialect: H(),
738
- allowIncompatible: l,
739
- targetSnapshot: c,
740
- force: l,
741
- onWarn: u,
742
- onProgress: R,
743
- assetsAlreadyRestored: !0,
744
- ...Ye(e),
745
- ...f ? { copyLoader: f } : {}
746
- })))
747
- }), 0;
748
- } finally {
749
- await f?.close(), await n.rm(m, {
750
- recursive: !0,
751
- force: !0
752
- });
753
- }
754
- }
755
- let p = await y.runPromise(O({
756
- ...Ke(e, a, i),
757
- store: s,
758
- bundleDir: i,
759
- mode: a,
760
- onConflict: o,
761
- atomic: Z(e, a),
762
- verify: !e.includes("--no-verify"),
763
- targetDialect: H(),
764
- allowIncompatible: l,
765
- targetSnapshot: c,
766
- force: l,
767
- onWarn: u,
768
- onProgress: R,
769
- ...Ye(e),
770
- ...d ? { assets: fe(d) } : {},
771
- ...f ? { copyLoader: f } : {}
772
- })).catch((e) => {
773
- if ($e(e)) return Qe;
774
- throw e;
775
- }).finally(() => f?.close());
776
- return typeof p == "symbol" ? 1 : (Ze(e, {
777
- bundleDir: i,
778
- ...Xe(p),
779
- assets: p.manifest.assets.count
780
- }), 0);
781
- }, nt = () => {
782
- let e = r();
783
- return {
784
- ...e.url ? { url: e.url } : {},
785
- ...e.host ? { host: e.host } : {},
786
- ...e.port ? { port: e.port } : {},
787
- ...e.username ? { username: e.username } : {},
788
- ...e.password ? { password: e.password } : {},
789
- ...e.database ? { database: e.database } : {}
790
- };
791
- }, rt = async (e) => {
792
- let t = V(e);
793
- if (!t) return I.error("usage: voltro data backup <outDir> (native pg_dump/mysqldump/… + consistent artifact)"), 1;
794
- let n = H(), { mkdir: r, writeFile: i } = await import("node:fs/promises"), { join: a } = await import("node:path");
795
- await r(t, { recursive: !0 });
796
- let o = a(t, C(n));
797
- await y.runPromise(k(se(n, nt(), o)));
798
- let s = Ee({
799
- dialect: n,
800
- schemaFingerprint: await L(n),
801
- voltroVersion: await je(),
802
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
803
- });
804
- return await i(a(t, P), `${JSON.stringify(s, null, 2)}\n`, "utf8"), I.info("native backup complete", {
805
- dialect: n,
806
- artifact: o,
807
- stamp: P,
808
- schemaFingerprint: s.schemaFingerprint ?? "<none>",
809
- assets: "NOT included — use `voltro data export --assets` for rows + blobs"
810
- }), 0;
811
- }, it = async (e, t) => {
812
- let n = H(), { join: r } = await import("node:path"), { readFile: i } = await import("node:fs/promises"), a = r(e, C(n)), o = ke({
813
- flagUrl: B(t, "--drill-url"),
814
- envUrl: process.env.DRILL_DB_URL,
815
- liveKeys: Pe()
816
- });
817
- if (!o.ok) return I.error(`restore --drill: ${o.error}`), 1;
818
- let s = await i(r(e, P), "utf8").then(De, () => null);
819
- if (s && s.dialect !== n) return I.error(`restore --drill: backup is a ${s.dialect} dump but DB_DIALECT is ${n} — cross-dialect restore is never valid.`), 1;
820
- I.info("restore drill: restoring into throwaway DB", {
821
- dialect: n,
822
- target: F(o.url)
823
- }), await y.runPromise(k(E(n, { url: o.url }, a)));
824
- let c = null, l = 0;
825
- try {
826
- let e = await U(n, { url: o.url });
827
- c = te(e), l = e.tables.length;
828
- } catch (e) {
829
- return I.error(`restore --drill: could not introspect the restored DB — ${String(e)}`), 1;
830
- }
831
- let u = Ae({
832
- stampFingerprint: s?.schemaFingerprint ?? null,
833
- restoredFingerprint: c,
834
- restoredTableCount: l
835
- });
836
- for (let e of u.lines) u.pass ? I.info(`restore drill: ${e}`) : I.error(`restore drill: ${e}`);
837
- return +!u.pass;
838
- }, at = async (e) => {
839
- let t = V(e);
840
- if (!t) return I.error("usage: voltro data restore <backupDir> [--allow-live] [--api-url <url>] [--force] [--drill [--drill-url <url>]] (native pg_restore/mysql/…)"), 1;
841
- if (e.includes("--drill")) return it(t, e);
842
- if (!await z(e)) return 1;
843
- let n = H(), { join: r } = await import("node:path"), { readFile: i } = await import("node:fs/promises"), a = r(t, C(n)), o = Oe({
844
- stamp: await i(r(t, P), "utf8").then(De, () => null),
845
- currentDialect: n,
846
- currentFingerprint: await L(n)
847
- });
848
- for (let e of o.info) I.info(`backup stamp: ${e}`);
849
- if (o.warn && I.warn(o.warn), o.refuse) {
850
- if (!e.includes("--force")) return I.error(`restore refused: ${o.refuse} (pass --force to override)`), 1;
851
- I.warn(`restore proceeding despite: ${o.refuse} (--force)`);
852
- }
853
- return await y.runPromise(k(E(n, nt(), a))), I.info("native restore complete", {
854
- dialect: n,
855
- artifact: a
856
- }), 0;
857
- }, ot = async (e) => {
858
- let t = V(e);
859
- if (!t) return I.error("usage: voltro data inspect <file.vbundle|dir> [--json] [--passphrase <p>]"), 1;
860
- let { resolve: n, join: r } = await import("node:path"), i = await import("node:fs/promises"), a = n(process.cwd(), t);
861
- if ((await i.stat(a).catch(() => void 0))?.isDirectory()) {
862
- let n = r(a, "manifest.json"), o = r(a, "README.md");
863
- if (!e.includes("--json")) {
864
- let e = await i.readFile(o, "utf8").catch(() => void 0);
865
- if (e !== void 0) return console.log(e), 0;
866
- }
867
- let s = await i.readFile(n, "utf8").catch(() => void 0);
868
- return s === void 0 ? (I.error(`'${t}' is a directory but holds no manifest.json — is it an unpacked bundle? (a bundle exported with --target api is always unpacked into a directory, even when the path ends in .vbundle)`), 1) : (console.log(s), 0);
869
- }
870
- let o = J(e), s = () => {
871
- let e = Y(a);
872
- return o ? w(e, o) : e;
873
- };
874
- if (e.includes("--json")) {
875
- let e = (await T(s(), ["manifest.json"])).get("manifest.json");
876
- return e ? (console.log(e.toString("utf8")), 0) : (I.error("no manifest.json found in the bundle"), 1);
877
- }
878
- let c = (await T(s(), ["README.md"])).get("README.md");
879
- if (c) return console.log(c.toString("utf8")), 0;
880
- let l = (await T(s(), ["manifest.json"])).get("manifest.json");
881
- return l ? (console.log(l.toString("utf8")), 0) : (I.error("bundle has no README.md or manifest.json"), 1);
882
- }, st = async (e) => {
883
- let { REPLACE_IN_PROGRESS_TABLE: t } = await import("@voltro/database"), { interruptedReplaceAtBoot: n } = await import("./interruptedReplace-DNJ7MKph.js"), { store: r } = await G(), i = await n(r);
884
- if (i === void 0) return I.info("no interrupted replace is recorded — nothing to clear"), 0;
885
- if (!e.includes("--yes")) return I.error(`${i}\n\n Re-run with --yes to clear it.`), 1;
886
- let a = await r.query({
887
- table: t,
888
- predicate: void 0,
889
- order: [],
890
- take: void 0,
891
- skip: void 0,
892
- projection: void 0
893
- });
894
- for (let e of a) await r.delete(t, String(e.id));
895
- return I.info(`cleared ${a.length} interrupted-replace marker(s) — the next boot will start`), 0;
896
- }, ct = async (e) => {
897
- let { STAGING_PREFIX: t, dropStagingSql: n, execStatements: r } = await import("@voltro/data-transfer"), { store: i } = await G(), a = H();
898
- if (a !== "postgres" && a !== "mysql" && a !== "mariadb" && a !== "sqlite" && a !== "mssql") return I.error(`this store has no staging tables to clear (dialect: ${a})`), 1;
899
- let { introspectSchema: o } = await import("@voltro/database/sql"), s = (await i.run((await import("@effect/sql")).SqlClient.SqlClient.pipe((await import("effect")).Effect.flatMap(o)))).tables.map((e) => e.name).filter((e) => e.startsWith(t));
900
- return s.length === 0 ? (I.info("no staging tables are present — nothing to clear"), 0) : e.includes("--yes") ? (await r(i, s.map((e) => n(e.slice(t.length), a))), I.info(`dropped ${s.length} staging table(s)`), 0) : (I.error(`${s.length} staging table(s) from an earlier \`--mode replace\`:\n` + s.map((e) => ` ${e}`).join("\n") + "\n\n Each holds a copy of what a run was loading. Nothing else removes them.\n Make sure no import is running right now — this cannot tell a leftover from one in flight.\n Re-run with --yes to drop them."), 1);
901
- }, lt = async (e) => {
902
- let { describeImportRun: t, IMPORT_RUNS_TABLE: n } = await import("@voltro/database"), r = Number(B(e, "--limit") ?? "20"), i = Number.isFinite(r) ? Math.max(1, Math.min(200, Math.trunc(r))) : 20;
903
- if (B(e, "--target") === "api") {
904
- let t = B(e, "--api-url");
905
- if (!t) return I.error("--target api requires --api-url <url> (the running instance)"), 1;
906
- let n = B(e, "--token") ?? process.env.VOLTRO_DATA_TRANSFER_SECRET;
907
- if (!n) return I.error("--target api requires --token <secret> (or VOLTRO_DATA_TRANSFER_SECRET)"), 1;
908
- let r = await fetch(`${t.replace(/\/+$/, "")}/_voltro/admin/imports?limit=${i}`, { headers: { authorization: `Bearer ${n}` } }), a = await r.text();
909
- if (r.status !== 200) return I.error(`api imports: ${r.status} ${a}`), 1;
910
- let o = JSON.parse(a);
911
- if (e.includes("--json")) return console.log(a), 0;
912
- let s = o.runs ?? [];
913
- if (s.length === 0) return I.info("no imports recorded on this instance"), 0;
914
- (o.running ?? 0) > 0 && I.info(`${o.running} import(s) IN FLIGHT — re-run this to watch the counters move`);
915
- for (let e of s) I.info(` ${e.line ?? ""}`);
916
- return 0;
917
- }
918
- let { store: a } = await G(), o;
919
- try {
920
- o = await a.query({
921
- table: n,
922
- order: [{
923
- column: "startedAt",
924
- direction: "desc"
925
- }],
926
- predicate: void 0,
927
- projection: void 0,
928
- skip: 0,
929
- take: i
930
- });
931
- } catch {
932
- return I.error(`this target has no \`${n}\` table, so no import has been recorded here.\n Run \`voltro db apply\`; imports themselves are unaffected by its absence.`), 1;
933
- }
934
- if (o.length === 0) return I.info("no imports recorded against this target"), 0;
935
- for (let e of o) {
936
- let n = e;
937
- I.info(` ${t({
938
- ...e,
939
- startedAt: new Date(n.startedAt),
940
- finishedAt: n.finishedAt === null ? null : new Date(n.finishedAt)
941
- })}`);
942
- }
943
- return 0;
944
- }, ut = async (e) => {
945
- let t = V(e), n = V(e.filter((e) => e !== t));
946
- if (!t || !n) return I.error("usage: voltro data unpack <file.vbundle> <dir> [--passphrase <p>]"), 1;
947
- let { resolve: r } = await import("node:path"), i = Y(r(process.cwd(), t)), a = J(e);
948
- return a && (i = w(i, a)), await A(i, r(process.cwd(), n)), I.info("unpack complete", {
949
- file: t,
950
- dir: n
951
- }), 0;
952
- }, $ = {
953
- export: {
954
- common: [
955
- "--target",
956
- "--tables",
957
- "--exclude",
958
- "--profile",
959
- "--tenant",
960
- "--assets",
961
- "--compression",
962
- "--consistency",
963
- "--json"
964
- ],
965
- directOnly: [
966
- "--passphrase",
967
- "--dry-run",
968
- "--encrypt"
969
- ],
970
- apiOnly: [
971
- "--api-url",
972
- "--token",
973
- "--bundle-key",
974
- "--timeout"
975
- ]
976
- },
977
- "clear-staging": { common: ["--yes"] },
978
- imports: {
979
- common: [
980
- "--target",
981
- "--limit",
982
- "--json"
983
- ],
984
- apiOnly: ["--api-url", "--token"]
985
- },
986
- "clear-replace-marker": { common: ["--yes"] },
987
- import: {
988
- common: [
989
- "--target",
990
- "--tables",
991
- "--mode",
992
- "--on-conflict",
993
- "--atomic",
994
- "--no-atomic",
995
- "--assets",
996
- "--force",
997
- "--dry-run",
998
- "--json"
999
- ],
1000
- directOnly: [
1001
- "--no-verify",
1002
- "--allow-live",
1003
- "--passphrase",
1004
- "--rollback-dir",
1005
- "--no-rollback"
1006
- ],
1007
- apiOnly: [
1008
- "--api-url",
1009
- "--token",
1010
- "--bundle-key",
1011
- "--timeout",
1012
- "--chunk-size",
1013
- "--rollback-key"
1014
- ]
1015
- },
1016
- unpack: { common: ["--passphrase", "--json"] },
1017
- inspect: { common: ["--json", "--passphrase"] },
1018
- backup: { common: ["--json", "--assets"] },
1019
- restore: { common: [
1020
- "--json",
1021
- "--allow-live",
1022
- "--force",
1023
- "--drill",
1024
- "--drill-url",
1025
- "--api-url"
1026
- ] }
1027
- }, dt = (e) => e.split("=")[0], ft = (e, t) => {
1028
- let n = $[e];
1029
- if (!n) return;
1030
- let r = B(t, "--target") === "api" ? "api" : "direct", i = /* @__PURE__ */ new Set([...n.common, ...r === "api" ? n.apiOnly ?? [] : n.directOnly ?? []]), a = new Set(r === "api" ? n.directOnly ?? [] : n.apiOnly ?? []);
1031
- for (let n of t) {
1032
- if (!n.startsWith("--")) continue;
1033
- let t = dt(n);
1034
- if (i.has(t)) continue;
1035
- if (a.has(t)) return `voltro data ${e}: ${t} is not read with --target ${r} (it is a --target ${r === "api" ? "direct" : "api"} flag). Remove it, or change --target.`;
1036
- let o = Object.entries($).filter(([n, r]) => n !== e && [
1037
- ...r.common,
1038
- ...r.directOnly ?? [],
1039
- ...r.apiOnly ?? []
1040
- ].includes(t)).map(([e]) => e);
1041
- return o.length > 0 ? `voltro data ${e}: ${t} is not a \`${e}\` flag (it belongs to \`voltro data ${o.join("` / `")}\`). Remove it.` : `voltro data ${e}: unknown flag ${t}. Run \`voltro data --help\` for the flags this command reads.`;
1042
- }
1043
- }, pt = async (e) => {
1044
- let [t, ...n] = e;
1045
- if (t !== void 0 && $[t] !== void 0) {
1046
- let e = ft(t, n);
1047
- if (e) return I.error(e), 2;
1048
- }
1049
- return t === "export" ? qe(n) : t === "import" ? tt(n) : t === "unpack" ? ut(n) : t === "inspect" ? ot(n) : t === "backup" ? rt(n) : t === "restore" ? at(n) : t === "clear-replace-marker" ? st(n) : t === "clear-staging" ? ct(n) : t === "imports" ? lt(n) : (I.error("usage: voltro data <export|import|imports|unpack|inspect|backup|restore|clear-replace-marker|clear-staging> … (logical: export/import; native: backup/restore; `imports` reads the history, incl. a run in flight)"), t ? 2 : 1);
1050
- };
1051
- //#endregion
1052
- export { pt as runDataCommand };