@gusto/baerly-storage 0.1.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 (115) hide show
  1. package/README.md +97 -0
  2. package/dist/API.md +850 -0
  3. package/dist/app-config-Cb5dO2s9.d.ts +480 -0
  4. package/dist/app-config.d.ts +2 -0
  5. package/dist/app-config.js +8 -0
  6. package/dist/app-config.js.map +1 -0
  7. package/dist/auth.d.ts +237 -0
  8. package/dist/auth.js +1335 -0
  9. package/dist/auth.js.map +1 -0
  10. package/dist/baerly.js +761 -0
  11. package/dist/baerly.js.map +1 -0
  12. package/dist/bucket-uri-BrDEYvzy.js +4922 -0
  13. package/dist/bucket-uri-BrDEYvzy.js.map +1 -0
  14. package/dist/chunk-EAsCxrDo.js +14 -0
  15. package/dist/client-BLf3Ae5s.d.ts +233 -0
  16. package/dist/client-react.d.ts +131 -0
  17. package/dist/client-react.js +559 -0
  18. package/dist/client-react.js.map +1 -0
  19. package/dist/client.d.ts +4 -0
  20. package/dist/client.js +160 -0
  21. package/dist/client.js.map +1 -0
  22. package/dist/cloudflare-CINJPKCW.js +911 -0
  23. package/dist/cloudflare-CINJPKCW.js.map +1 -0
  24. package/dist/cloudflare.d.ts +211 -0
  25. package/dist/cloudflare.js +445 -0
  26. package/dist/cloudflare.js.map +1 -0
  27. package/dist/config-Bsg8wgwo.js +198 -0
  28. package/dist/config-Bsg8wgwo.js.map +1 -0
  29. package/dist/context-Oj7ffwD-.js +187 -0
  30. package/dist/context-Oj7ffwD-.js.map +1 -0
  31. package/dist/cost-B1WiZxlf.js +203 -0
  32. package/dist/cost-B1WiZxlf.js.map +1 -0
  33. package/dist/current-json-BkatBzF7.js +252 -0
  34. package/dist/current-json-BkatBzF7.js.map +1 -0
  35. package/dist/db-D62JguBc.d.ts +336 -0
  36. package/dist/deploy-BB-wqbhf.js +83 -0
  37. package/dist/deploy-BB-wqbhf.js.map +1 -0
  38. package/dist/dev-banner-CWHIk8tH.d.ts +26 -0
  39. package/dist/dev-vite.d.ts +146 -0
  40. package/dist/dev-vite.js +223 -0
  41. package/dist/dev-vite.js.map +1 -0
  42. package/dist/dev.d.ts +3 -0
  43. package/dist/dev.js +2 -0
  44. package/dist/doctor-B8h9GCN9.js +331 -0
  45. package/dist/doctor-B8h9GCN9.js.map +1 -0
  46. package/dist/dump-BHo_sIMZ.js +116 -0
  47. package/dist/dump-BHo_sIMZ.js.map +1 -0
  48. package/dist/errors-DOdL95kK.js +58 -0
  49. package/dist/errors-DOdL95kK.js.map +1 -0
  50. package/dist/export-Dz2PZKSR.js +423 -0
  51. package/dist/export-Dz2PZKSR.js.map +1 -0
  52. package/dist/fsck-DEz9lyCy.js +293 -0
  53. package/dist/fsck-DEz9lyCy.js.map +1 -0
  54. package/dist/http-CjUO1Bec.js +1756 -0
  55. package/dist/http-CjUO1Bec.js.map +1 -0
  56. package/dist/http.d.ts +1619 -0
  57. package/dist/http.js +2 -0
  58. package/dist/index-BGC-ENnj.d.ts +1065 -0
  59. package/dist/index-BYv0hb8M.d.ts +1457 -0
  60. package/dist/index-BquQkhJi.d.ts +112 -0
  61. package/dist/index-COsQ-Mlz.d.ts +146 -0
  62. package/dist/index.d.ts +6 -0
  63. package/dist/index.js +6 -0
  64. package/dist/indexes-BXn7a06a.js +297 -0
  65. package/dist/indexes-BXn7a06a.js.map +1 -0
  66. package/dist/indexes-DwOXkn1Y.d.ts +22 -0
  67. package/dist/inspect-x02aFWnh.js +149 -0
  68. package/dist/inspect-x02aFWnh.js.map +1 -0
  69. package/dist/log-walk-DIru96UT.js +260 -0
  70. package/dist/log-walk-DIru96UT.js.map +1 -0
  71. package/dist/maintenance-Bn6ul9aV.js +758 -0
  72. package/dist/maintenance-Bn6ul9aV.js.map +1 -0
  73. package/dist/maintenance.d.ts +323 -0
  74. package/dist/maintenance.js +2 -0
  75. package/dist/node.d.ts +422 -0
  76. package/dist/node.js +2 -0
  77. package/dist/normalize-XWY25_sG.js +133 -0
  78. package/dist/normalize-XWY25_sG.js.map +1 -0
  79. package/dist/observability-2IDYRuZK.js +2333 -0
  80. package/dist/observability-2IDYRuZK.js.map +1 -0
  81. package/dist/observability.d.ts +3 -0
  82. package/dist/observability.js +3 -0
  83. package/dist/plan-Cs17VqjU.js +224 -0
  84. package/dist/plan-Cs17VqjU.js.map +1 -0
  85. package/dist/query-DcSbFLJt.js +1880 -0
  86. package/dist/query-DcSbFLJt.js.map +1 -0
  87. package/dist/rebuild-index-C5gTXryd.js +119 -0
  88. package/dist/rebuild-index-C5gTXryd.js.map +1 -0
  89. package/dist/rebuild-index-DwXM0WfA.js +104 -0
  90. package/dist/rebuild-index-DwXM0WfA.js.map +1 -0
  91. package/dist/request-BEF_OvMh.js +72 -0
  92. package/dist/request-BEF_OvMh.js.map +1 -0
  93. package/dist/restore-CbKVMMpm.js +847 -0
  94. package/dist/restore-CbKVMMpm.js.map +1 -0
  95. package/dist/shared-secret-BJdSwpgw.js +71 -0
  96. package/dist/shared-secret-BJdSwpgw.js.map +1 -0
  97. package/dist/snapshot-D7C4_FSl.js +71 -0
  98. package/dist/snapshot-D7C4_FSl.js.map +1 -0
  99. package/dist/snapshot-z_N9hpTe.js +917 -0
  100. package/dist/snapshot-z_N9hpTe.js.map +1 -0
  101. package/dist/src-Chafbw8r.js +522 -0
  102. package/dist/src-Chafbw8r.js.map +1 -0
  103. package/dist/src-DyET_VPP.js +6199 -0
  104. package/dist/src-DyET_VPP.js.map +1 -0
  105. package/dist/src-n0Te1r98.js +352 -0
  106. package/dist/src-n0Te1r98.js.map +1 -0
  107. package/dist/subcommand-BWs6K7zb.js +110 -0
  108. package/dist/subcommand-BWs6K7zb.js.map +1 -0
  109. package/dist/usage-RVUQMLop.js +339 -0
  110. package/dist/usage-RVUQMLop.js.map +1 -0
  111. package/dist/validate-DhH1lO8I.js +377 -0
  112. package/dist/validate-DhH1lO8I.js.map +1 -0
  113. package/dist/wire-izfGZDvr.js +7 -0
  114. package/dist/wire-izfGZDvr.js.map +1 -0
  115. package/package.json +189 -0
@@ -0,0 +1,423 @@
1
+ import { t as parseBucketUri } from "./bucket-uri-BrDEYvzy.js";
2
+ import { n as matchesWire, t as validateWire } from "./validate-DhH1lO8I.js";
3
+ import { o as BaerlyError, r as emitSuccess } from "./baerly.js";
4
+ import { n as loadMaterialisedView, r as quoteValue, t as inferPlanForCollection } from "./plan-Cs17VqjU.js";
5
+ import { t as defineBaerlySubcommand } from "./subcommand-BWs6K7zb.js";
6
+ import { writeFile } from "node:fs/promises";
7
+ //#region src/export/ddl.ts
8
+ /**
9
+ * Emit a `CREATE TABLE` statement for the plan, one line per column,
10
+ * terminated with a semicolon + newline so the output is directly
11
+ * pipeable into `psql` / `sqlite3` / `wrangler d1 execute`.
12
+ *
13
+ * `_id` is the primary key (always first in `plan.columns`).
14
+ *
15
+ * D1 today is sqlite-flavoured: same DDL as `target=sqlite` with a
16
+ * single difference — D1 disallows table names starting with
17
+ * `sqlite_`. We refuse them up front.
18
+ */
19
+ const emitCreateTable = (plan) => {
20
+ if (plan.columns.length === 0) throw new BaerlyError("SchemaError", `emitCreateTable: collection ${JSON.stringify(plan.table)} has no observed columns — empty snapshot?`);
21
+ if (plan.target === "d1" && plan.table.toLowerCase().startsWith("sqlite_")) throw new BaerlyError("SchemaError", `emitCreateTable: D1 reserves the sqlite_ table-name prefix (got ${JSON.stringify(plan.table)})`);
22
+ const lines = [];
23
+ lines.push(`CREATE TABLE ${plan.tableIdentifier} (`);
24
+ const colLines = [];
25
+ for (const col of plan.columns) {
26
+ const nullClause = col.nullable ? "" : " NOT NULL";
27
+ const pkClause = col.source === "_id" ? " PRIMARY KEY" : "";
28
+ colLines.push(` ${col.identifier} ${col.sqlType}${nullClause}${pkClause}`);
29
+ }
30
+ lines.push(colLines.join(",\n"));
31
+ lines.push(");");
32
+ return lines.join("\n") + "\n";
33
+ };
34
+ //#endregion
35
+ //#region src/export/rows.ts
36
+ /**
37
+ * Emit one `INSERT INTO …` statement per row. The emitted SQL is
38
+ * directly pipeable into `psql` / `sqlite3` / `wrangler d1
39
+ * execute`. Per-row statements (not one big VALUES tuple) so a
40
+ * mid-stream failure has bounded blast radius.
41
+ *
42
+ * For columns whose plan has `jsonEncoded: true`, the row's value
43
+ * is JSON-stringified first and then string-quoted. Postgres
44
+ * accepts a literal text JSON in a `jsonb` column. SQLite / D1 see
45
+ * the JSON as plain TEXT.
46
+ *
47
+ * Rows are streamed via the async-iterable protocol so the export
48
+ * never materialises the full SQL output in memory. The caller
49
+ * concatenates the yielded chunks (or pipes them straight to disk
50
+ * / stdout).
51
+ */
52
+ async function* emitInsertStatements(plan, rows) {
53
+ const columnList = plan.columns.map((c) => c.identifier).join(", ");
54
+ for (const [id, body] of rows) {
55
+ const values = [];
56
+ for (const col of plan.columns) {
57
+ const raw = col.source === "_id" ? id : body[col.source];
58
+ if (raw === void 0) {
59
+ values.push("NULL");
60
+ continue;
61
+ }
62
+ if (col.jsonEncoded) {
63
+ const json = JSON.stringify(raw);
64
+ values.push(quoteValue(json, plan.target));
65
+ } else values.push(quoteValue(raw, plan.target));
66
+ }
67
+ yield `INSERT INTO ${plan.tableIdentifier} (${columnList}) VALUES (${values.join(", ")});\n`;
68
+ }
69
+ }
70
+ //#endregion
71
+ //#region src/export/where.ts
72
+ /**
73
+ * Wire-predicate → SQL `WHERE` clause translation.
74
+ *
75
+ * Pure function. The translator consumes a validated
76
+ * {@link PredicateWire} — the same shape the read path uses — and
77
+ * an {@link ExportPlan} (from `./plan.ts`), and emits a SQL fragment
78
+ * matched against the plan's columns.
79
+ *
80
+ * Three classes of clause:
81
+ *
82
+ * 1. Flat column, top-level field → direct comparator
83
+ * (`"status" = 'open'`, `"priority" > 5`).
84
+ * 2. JSON-encoded column → JSON-path operators (Postgres `->`/`->>`
85
+ * chains; SQLite/D1 `json_extract(…, '$.…')`).
86
+ * 3. Unmatchable clause (dotted path against a flat column, or a
87
+ * field naming an unknown column) → `1 = 0` plus a hint the CLI
88
+ * surfaces as a `-- TODO(baerly export):` comment above the
89
+ * emitted statement.
90
+ *
91
+ * Dynamic predicates are invisible at runtime — we see the
92
+ * materialised wire, not the source expression. Callers that know
93
+ * they constructed the wire dynamically can pass
94
+ * `options.dynamicHint` to surface an operator-supplied note.
95
+ */
96
+ /**
97
+ * Translate a validated {@link PredicateWire} into a SQL WHERE-clause
98
+ * fragment matched against the plan's columns. The first argument
99
+ * must already have been validated by {@link validateWire} — the
100
+ * function re-validates defensively but the caller's invariant
101
+ * matters for error-message provenance.
102
+ *
103
+ * Pure function. No I/O. Same wire + plan + target → same SQL string.
104
+ *
105
+ * @throws BaerlyError code="InvalidConfig" — wire fails
106
+ * {@link validateWire}; same shape `Query<T>.where` already
107
+ * surfaces.
108
+ */
109
+ const translatePredicateWireToSql = (wire, plan, options) => {
110
+ validateWire(wire);
111
+ const hints = [];
112
+ if (options?.dynamicHint !== void 0 && options.dynamicHint.length > 0) hints.push(`caller-flagged dynamic predicate: ${options.dynamicHint}. Review the emitted SQL for completeness.`);
113
+ const clauses = [];
114
+ for (const clause of wire.clauses) clauses.push(...clauseForWire(clause, plan, hints));
115
+ return {
116
+ sql: clauses.length === 0 ? "" : clauses.join(" AND "),
117
+ hints
118
+ };
119
+ };
120
+ const clauseForWire = (clause, plan, hints) => {
121
+ const segments = clause.field.includes(".") ? clause.field.split(".") : [clause.field];
122
+ const head = segments[0];
123
+ if (head === void 0 || head.length === 0) throw new BaerlyError("InvalidConfig", "translatePredicateWireToSql: empty field path encountered (defensive)");
124
+ const col = plan.columns.find((c) => c.source === head);
125
+ if (col === void 0) {
126
+ hints.push(`predicate field ${JSON.stringify(clause.field)} references a key never observed in the snapshot; this clause cannot match.`);
127
+ return ["1 = 0"];
128
+ }
129
+ if (!col.jsonEncoded && segments.length === 1) return [flatColumnClause(col.identifier, clause, plan.target)];
130
+ if (!col.jsonEncoded && segments.length > 1) {
131
+ hints.push(`predicate path ${JSON.stringify(clause.field)} addresses a flat column; this clause cannot match. Hand-edit if intended.`);
132
+ return ["1 = 0"];
133
+ }
134
+ if (col.jsonEncoded && segments.length === 1) return [jsonColumnRootClause(col, clause, plan.target)];
135
+ return [jsonPathClause(col, segments.slice(1), clause, plan.target)];
136
+ };
137
+ const flatColumnClause = (identifier, clause, target) => {
138
+ switch (clause.op) {
139
+ case "eq": return `${identifier} = ${quoteLeaf(clause.value, target)}`;
140
+ case "gt": return `${identifier} > ${quoteLeaf(clause.value, target)}`;
141
+ case "gte": return `${identifier} >= ${quoteLeaf(clause.value, target)}`;
142
+ case "lt": return `${identifier} < ${quoteLeaf(clause.value, target)}`;
143
+ case "lte": return `${identifier} <= ${quoteLeaf(clause.value, target)}`;
144
+ case "in": return `${identifier} IN (${clause.value.map((v) => quoteLeaf(v, target)).join(", ")})`;
145
+ }
146
+ };
147
+ const jsonColumnRootClause = (col, clause, target) => {
148
+ if (clause.op === "eq") {
149
+ const literal = JSON.stringify(clause.value);
150
+ if (target === "postgres") return `${col.identifier}::text = ${quoteValue(literal, target)}`;
151
+ return `${col.identifier} = ${quoteValue(literal, target)}`;
152
+ }
153
+ if (clause.op === "in") {
154
+ const literals = clause.value.map((v) => quoteValue(JSON.stringify(v), target));
155
+ if (target === "postgres") return `${col.identifier}::text IN (${literals.join(", ")})`;
156
+ return `${col.identifier} IN (${literals.join(", ")})`;
157
+ }
158
+ const comparator = rangeComparator(clause.op);
159
+ const literal = JSON.stringify(clause.value);
160
+ if (target === "postgres") return `${col.identifier}::text ${comparator} ${quoteValue(literal, target)}`;
161
+ return `${col.identifier} ${comparator} ${quoteValue(literal, target)}`;
162
+ };
163
+ const jsonPathClause = (col, tail, clause, target) => {
164
+ const accessor = jsonPathAccessor(col.identifier, tail, target);
165
+ switch (clause.op) {
166
+ case "eq": return `${accessor} = ${quoteLeaf(clause.value, target)}`;
167
+ case "gt": return `${accessor} > ${quoteLeaf(clause.value, target)}`;
168
+ case "gte": return `${accessor} >= ${quoteLeaf(clause.value, target)}`;
169
+ case "lt": return `${accessor} < ${quoteLeaf(clause.value, target)}`;
170
+ case "lte": return `${accessor} <= ${quoteLeaf(clause.value, target)}`;
171
+ case "in": return `${accessor} IN (${clause.value.map((v) => quoteLeaf(v, target)).join(", ")})`;
172
+ }
173
+ };
174
+ const rangeComparator = (op) => {
175
+ if (op === "gt") return ">";
176
+ if (op === "gte") return ">=";
177
+ if (op === "lt") return "<";
178
+ return "<=";
179
+ };
180
+ const jsonPathAccessor = (identifier, tail, target) => {
181
+ if (target === "postgres") {
182
+ let expr = identifier;
183
+ for (let i = 0; i < tail.length; i++) {
184
+ const seg = tail[i];
185
+ const isLast = i === tail.length - 1;
186
+ const key = `'${seg.replace(/'/g, "''")}'`;
187
+ expr = `${expr}${isLast ? "->>" : "->"}${key}`;
188
+ }
189
+ return expr;
190
+ }
191
+ return `json_extract(${identifier}, ${`'$.${tail.map((s) => s.replace(/'/g, "''")).join(".")}'`})`;
192
+ };
193
+ /**
194
+ * Quote a leaf primitive for use as the right-hand side of a
195
+ * comparison. Booleans branch on target. Nested objects must never
196
+ * reach here — wire `eq` clauses on nested objects can only come
197
+ * from the callback form `q.eq("nested", { ... })`, which the
198
+ * export translator does not support today.
199
+ */
200
+ const quoteLeaf = (value, target) => {
201
+ if (typeof value === "object") throw new BaerlyError("InvalidConfig", "translatePredicateWireToSql: nested object reached leaf quoter — callback-form q.eq(field, object) is not supported for SQL export. Hand-edit the emitted SQL.");
202
+ return quoteValue(value, target);
203
+ };
204
+ //#endregion
205
+ //#region src/export/plan-sidecar.ts
206
+ const SIDECAR_SCHEMA_VERSION = 1;
207
+ /**
208
+ * Encode an {@link ExportPlan} as the canonical sidecar JSON string.
209
+ *
210
+ * Wire format is pretty-printed (`indent=2`) with a trailing newline
211
+ * so `cat sidecar.plan.json` is human-readable and `diff` works on
212
+ * two sidecars without spurious line-end noise. The on-wire bytes
213
+ * embed the `schemaVersion` discriminator so future shape changes
214
+ * are detectable; `identifier` and `tableIdentifier` are NOT carried
215
+ * (they're re-derived via {@link quoteIdentifier} on deserialise).
216
+ */
217
+ const serializeExportPlan = (plan) => {
218
+ return JSON.stringify({
219
+ schemaVersion: SIDECAR_SCHEMA_VERSION,
220
+ table: plan.table,
221
+ target: plan.target,
222
+ columns: plan.columns.map((c) => ({
223
+ source: c.source,
224
+ sqlType: c.sqlType,
225
+ nullable: c.nullable,
226
+ jsonEncoded: c.jsonEncoded
227
+ }))
228
+ }, null, 2) + "\n";
229
+ };
230
+ //#endregion
231
+ //#region src/export.ts
232
+ /**
233
+ * `baerly export` — snapshot dump of one collection to SQL.
234
+ *
235
+ * Drives the export modules end-to-end: load the materialised view,
236
+ * infer an `ExportPlan` over the row shape, emit `CREATE TABLE` +
237
+ * `INSERT` statements. When `--where=<json>` is supplied the
238
+ * predicate is translated via `translatePredicateToSql` and applied
239
+ * in-memory through `matches(...)` so the emitted INSERTs already
240
+ * match the filter; the translated WHERE clause is also surfaced as a
241
+ * comment above the inserts so operators can inspect / hand-edit it.
242
+ *
243
+ * The sidecar file (`<output>.plan.json`) carries the `ExportPlan` so
244
+ * a follow-up round-trip ingest can verify the column schema. The
245
+ * sidecar is JSON via `JSON.stringify` — the plan shape is the public
246
+ * contract.
247
+ *
248
+ * Args:
249
+ * --bucket Required. Bucket URI.
250
+ * --app Required (or via baerly.config.ts).
251
+ * --tenant Required (or via baerly.config.ts).
252
+ * --collection Required. Collection name.
253
+ * --target Required. postgres | sqlite | d1.
254
+ * --where Optional. JSON-encoded `Predicate<T>`.
255
+ * --where-comment Optional. Caller hint surfaced as a
256
+ * `-- TODO(baerly export):` comment.
257
+ * --output Optional. Path to write SQL into; default
258
+ * stdout. The sidecar plan is written to
259
+ * `<output>.plan.json` unless `--no-sidecar`.
260
+ * --no-sidecar Skip emitting the sidecar plan file.
261
+ * --json JSON envelope on stdout (or stderr on error).
262
+ *
263
+ * Exit codes:
264
+ * 0 — dump completed.
265
+ * 1 — InvalidConfig (bad args / bucket URI / --where JSON / unknown --target).
266
+ * 2 — Storage / Network error.
267
+ * 3 — Protocol invariant (Internal / InvalidResponse / Conflict).
268
+ */
269
+ const EXPORT_ARGS = {
270
+ bucket: {
271
+ type: "string",
272
+ required: true,
273
+ description: "Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)",
274
+ valueHint: "bucket-uri"
275
+ },
276
+ app: {
277
+ type: "string",
278
+ required: false,
279
+ description: "Application name segment (defaults to baerly.config.ts).",
280
+ valueHint: "app"
281
+ },
282
+ tenant: {
283
+ type: "string",
284
+ required: false,
285
+ description: "Tenant name segment (defaults to baerly.config.ts).",
286
+ valueHint: "tenant"
287
+ },
288
+ collection: {
289
+ type: "string",
290
+ required: true,
291
+ description: "Collection name.",
292
+ valueHint: "name"
293
+ },
294
+ target: {
295
+ type: "enum",
296
+ options: [
297
+ "postgres",
298
+ "sqlite",
299
+ "d1"
300
+ ],
301
+ required: true,
302
+ description: "SQL target: postgres | sqlite | d1."
303
+ },
304
+ where: {
305
+ type: "string",
306
+ required: false,
307
+ description: "JSON-encoded PredicateWire ({ clauses: [...] }) filtering the rows to export.",
308
+ valueHint: "json"
309
+ },
310
+ "where-comment": {
311
+ type: "string",
312
+ required: false,
313
+ description: "Caller hint surfaced as a -- TODO(baerly export): comment.",
314
+ valueHint: "text"
315
+ },
316
+ output: {
317
+ type: "string",
318
+ required: false,
319
+ description: "Path to write SQL into; default stdout.",
320
+ valueHint: "path"
321
+ },
322
+ sidecar: {
323
+ type: "boolean",
324
+ default: true,
325
+ description: "Emit a <output>.plan.json sidecar (default true; pass --no-sidecar to skip)."
326
+ },
327
+ json: {
328
+ type: "boolean",
329
+ description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
330
+ }
331
+ };
332
+ const parseWherePredicate = (raw) => {
333
+ let parsed;
334
+ try {
335
+ parsed = JSON.parse(raw);
336
+ } catch (error) {
337
+ throw new BaerlyError("InvalidConfig", `baerly export: --where is not valid JSON: ${error.message}`);
338
+ }
339
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new BaerlyError("InvalidConfig", `baerly export: --where must decode to a JSON object (got ${describeNonObject(parsed)})`);
340
+ validateWire(parsed);
341
+ return parsed;
342
+ };
343
+ const filterRows = (rows, wire) => {
344
+ const filtered = /* @__PURE__ */ new Map();
345
+ for (const [id, body] of rows) {
346
+ if (wire === null) {
347
+ filtered.set(id, body);
348
+ continue;
349
+ }
350
+ if (matchesWire(wire, body)) filtered.set(id, body);
351
+ }
352
+ return filtered;
353
+ };
354
+ const buildSql = async (plan, rows, whereClause, whereHints) => {
355
+ let out = emitCreateTable(plan);
356
+ for (const hint of whereHints) out += `-- TODO(baerly export): ${hint}\n`;
357
+ if (whereClause.length > 0) out += `-- WHERE clause for review: ${whereClause}\n`;
358
+ for await (const chunk of emitInsertStatements(plan, rows)) out += chunk;
359
+ return out;
360
+ };
361
+ const bundle = defineBaerlySubcommand({
362
+ name: "export",
363
+ meta: { description: "Snapshot dump of one collection to SQL." },
364
+ args: EXPORT_ARGS,
365
+ handler: async (args, ctx) => {
366
+ const target = args.target;
367
+ const { app, tenant } = await ctx.resolveAppTenant({
368
+ app: args.app,
369
+ tenant: args.tenant
370
+ });
371
+ const bucket = await parseBucketUri(args.bucket);
372
+ const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;
373
+ const view = await loadMaterialisedView({
374
+ storage: bucket.storage,
375
+ currentJsonKey,
376
+ collection: args.collection
377
+ });
378
+ if (view === null) throw new BaerlyError("InvalidConfig", `baerly export: collection ${JSON.stringify(args.collection)} is not provisioned (no current.json at ${currentJsonKey})`);
379
+ const plan = inferPlanForCollection({
380
+ rows: view,
381
+ target,
382
+ table: args.collection
383
+ });
384
+ let wire = null;
385
+ let whereClause = "";
386
+ let whereHints = [];
387
+ if (typeof args.where === "string" && args.where.length > 0) {
388
+ wire = parseWherePredicate(args.where);
389
+ const translation = translatePredicateWireToSql(wire, plan, typeof args["where-comment"] === "string" && args["where-comment"].length > 0 ? { dynamicHint: args["where-comment"] } : void 0);
390
+ whereClause = translation.sql;
391
+ whereHints = translation.hints;
392
+ } else if (typeof args["where-comment"] === "string" && args["where-comment"].length > 0) whereHints = [`caller-flagged dynamic predicate: ${args["where-comment"]}. No predicate supplied; emitted INSERTs cover the full collection.`];
393
+ const filtered = filterRows(view, wire);
394
+ const sql = await buildSql(plan, filtered, whereClause, whereHints);
395
+ const outputPath = args.output;
396
+ if (typeof outputPath === "string" && outputPath.length > 0) {
397
+ await writeFile(outputPath, sql, "utf8");
398
+ if (args.sidecar !== false) await writeFile(`${outputPath}.plan.json`, serializeExportPlan(plan), "utf8");
399
+ } else process.stdout.write(sql);
400
+ emitSuccess({
401
+ command: "export",
402
+ status: "ok",
403
+ collection: args.collection,
404
+ target,
405
+ rows: filtered.size,
406
+ hints: whereHints,
407
+ ...typeof outputPath === "string" && outputPath.length > 0 && { output: outputPath }
408
+ });
409
+ return 0;
410
+ }
411
+ });
412
+ /** citty `defineCommand` block for `baerly export`. */
413
+ const exportCmd = bundle.cmd;
414
+ bundle.run;
415
+ const describeNonObject = (v) => {
416
+ if (v === null) return "null";
417
+ if (Array.isArray(v)) return "array";
418
+ return typeof v;
419
+ };
420
+ //#endregion
421
+ export { exportCmd };
422
+
423
+ //# sourceMappingURL=export-Dz2PZKSR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"export-Dz2PZKSR.js","names":[],"sources":["../packages/cli/src/export/ddl.ts","../packages/cli/src/export/rows.ts","../packages/cli/src/export/where.ts","../packages/cli/src/export/plan-sidecar.ts","../packages/cli/src/export.ts"],"sourcesContent":["import { BaerlyError } from \"@baerly/protocol\";\nimport type { ExportPlan } from \"./types.ts\";\n\n/**\n * Emit a `CREATE TABLE` statement for the plan, one line per column,\n * terminated with a semicolon + newline so the output is directly\n * pipeable into `psql` / `sqlite3` / `wrangler d1 execute`.\n *\n * `_id` is the primary key (always first in `plan.columns`).\n *\n * D1 today is sqlite-flavoured: same DDL as `target=sqlite` with a\n * single difference — D1 disallows table names starting with\n * `sqlite_`. We refuse them up front.\n */\nexport const emitCreateTable = (plan: ExportPlan): string => {\n if (plan.columns.length === 0) {\n throw new BaerlyError(\n \"SchemaError\",\n `emitCreateTable: collection ${JSON.stringify(plan.table)} has no observed columns — empty snapshot?`,\n );\n }\n if (plan.target === \"d1\" && plan.table.toLowerCase().startsWith(\"sqlite_\")) {\n throw new BaerlyError(\n \"SchemaError\",\n `emitCreateTable: D1 reserves the sqlite_ table-name prefix (got ${JSON.stringify(plan.table)})`,\n );\n }\n const lines: string[] = [];\n lines.push(`CREATE TABLE ${plan.tableIdentifier} (`);\n const colLines: string[] = [];\n for (const col of plan.columns) {\n const nullClause = col.nullable ? \"\" : \" NOT NULL\";\n const pkClause = col.source === \"_id\" ? \" PRIMARY KEY\" : \"\";\n colLines.push(` ${col.identifier} ${col.sqlType}${nullClause}${pkClause}`);\n }\n lines.push(colLines.join(\",\\n\"));\n lines.push(\");\");\n return lines.join(\"\\n\") + \"\\n\";\n};\n","import type { DocumentValue } from \"@baerly/protocol\";\nimport type { ExportPlan, ExportRow } from \"./types.ts\";\nimport { quoteValue } from \"./sql-escape.ts\";\n\n/**\n * Emit one `INSERT INTO …` statement per row. The emitted SQL is\n * directly pipeable into `psql` / `sqlite3` / `wrangler d1\n * execute`. Per-row statements (not one big VALUES tuple) so a\n * mid-stream failure has bounded blast radius.\n *\n * For columns whose plan has `jsonEncoded: true`, the row's value\n * is JSON-stringified first and then string-quoted. Postgres\n * accepts a literal text JSON in a `jsonb` column. SQLite / D1 see\n * the JSON as plain TEXT.\n *\n * Rows are streamed via the async-iterable protocol so the export\n * never materialises the full SQL output in memory. The caller\n * concatenates the yielded chunks (or pipes them straight to disk\n * / stdout).\n */\nexport async function* emitInsertStatements(\n plan: ExportPlan,\n rows: ReadonlyMap<string, ExportRow>,\n): AsyncIterable<string> {\n const columnList = plan.columns.map((c) => c.identifier).join(\", \");\n // Iterate in `Map` insertion order — stable, and the snapshot\n // body itself sorts by `_id` (compactor.ts: `docs is sorted by\n // _id for deterministic byte output`).\n for (const [id, body] of rows) {\n const values: string[] = [];\n for (const col of plan.columns) {\n const raw: DocumentValue | undefined =\n col.source === \"_id\"\n ? (id as DocumentValue)\n : (body as Record<string, DocumentValue>)[col.source];\n if (raw === undefined) {\n values.push(\"NULL\");\n continue;\n }\n if (col.jsonEncoded) {\n const json = JSON.stringify(raw);\n values.push(quoteValue(json, plan.target));\n } else {\n values.push(quoteValue(raw, plan.target));\n }\n }\n yield `INSERT INTO ${plan.tableIdentifier} (${columnList}) VALUES (${values.join(\", \")});\\n`;\n }\n}\n","/**\n * Wire-predicate → SQL `WHERE` clause translation.\n *\n * Pure function. The translator consumes a validated\n * {@link PredicateWire} — the same shape the read path uses — and\n * an {@link ExportPlan} (from `./plan.ts`), and emits a SQL fragment\n * matched against the plan's columns.\n *\n * Three classes of clause:\n *\n * 1. Flat column, top-level field → direct comparator\n * (`\"status\" = 'open'`, `\"priority\" > 5`).\n * 2. JSON-encoded column → JSON-path operators (Postgres `->`/`->>`\n * chains; SQLite/D1 `json_extract(…, '$.…')`).\n * 3. Unmatchable clause (dotted path against a flat column, or a\n * field naming an unknown column) → `1 = 0` plus a hint the CLI\n * surfaces as a `-- TODO(baerly export):` comment above the\n * emitted statement.\n *\n * Dynamic predicates are invisible at runtime — we see the\n * materialised wire, not the source expression. Callers that know\n * they constructed the wire dynamically can pass\n * `options.dynamicHint` to surface an operator-supplied note.\n */\n\nimport {\n BaerlyError,\n type DocumentValue,\n type PredicateClause,\n type PredicateWire,\n validateWire,\n} from \"@baerly/protocol\";\nimport { quoteValue } from \"./sql-escape.ts\";\nimport type { ColumnPlan, ExportPlan, SqlTarget } from \"./types.ts\";\n\nexport interface WhereTranslation {\n /** SQL fragment without the leading `WHERE`. Empty when no predicate. */\n readonly sql: string;\n /**\n * Hand-edit hints for the operator. One entry per non-matchable\n * clause (§3.6) or per dynamically-constructed sub-clause flagged\n * by the caller. The CLI surfaces these as `-- TODO(baerly export): …`\n * comments above the emitted statement.\n */\n readonly hints: readonly string[];\n}\n\n/**\n * Translate a validated {@link PredicateWire} into a SQL WHERE-clause\n * fragment matched against the plan's columns. The first argument\n * must already have been validated by {@link validateWire} — the\n * function re-validates defensively but the caller's invariant\n * matters for error-message provenance.\n *\n * Pure function. No I/O. Same wire + plan + target → same SQL string.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — wire fails\n * {@link validateWire}; same shape `Query<T>.where` already\n * surfaces.\n */\nexport const translatePredicateWireToSql = (\n wire: PredicateWire,\n plan: ExportPlan,\n options?: { readonly dynamicHint?: string },\n): WhereTranslation => {\n validateWire(wire);\n const hints: string[] = [];\n if (options?.dynamicHint !== undefined && options.dynamicHint.length > 0) {\n hints.push(\n `caller-flagged dynamic predicate: ${options.dynamicHint}. Review the emitted SQL for completeness.`,\n );\n }\n const clauses: string[] = [];\n for (const clause of wire.clauses) {\n clauses.push(...clauseForWire(clause, plan, hints));\n }\n return {\n sql: clauses.length === 0 ? \"\" : clauses.join(\" AND \"),\n hints,\n };\n};\n\nconst clauseForWire = (clause: PredicateClause, plan: ExportPlan, hints: string[]): string[] => {\n const segments = clause.field.includes(\".\") ? clause.field.split(\".\") : [clause.field];\n const head = segments[0];\n if (head === undefined || head.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"translatePredicateWireToSql: empty field path encountered (defensive)\",\n );\n }\n const col = plan.columns.find((c) => c.source === head);\n if (col === undefined) {\n hints.push(\n `predicate field ${JSON.stringify(clause.field)} references a key never observed in the snapshot; this clause cannot match.`,\n );\n return [\"1 = 0\"];\n }\n // §3.2 — flat column, top-level field → direct comparator.\n if (!col.jsonEncoded && segments.length === 1) {\n return [flatColumnClause(col.identifier, clause, plan.target)];\n }\n // §3.6 — flat column, dotted path → unmatchable.\n if (!col.jsonEncoded && segments.length > 1) {\n hints.push(\n `predicate path ${JSON.stringify(clause.field)} addresses a flat column; this clause cannot match. Hand-edit if intended.`,\n );\n return [\"1 = 0\"];\n }\n // §3.3 — JSON column, top-level field.\n if (col.jsonEncoded && segments.length === 1) {\n return [jsonColumnRootClause(col, clause, plan.target)];\n }\n // §3.4 / §3.5 — JSON column, dotted path.\n return [jsonPathClause(col, segments.slice(1), clause, plan.target)];\n};\n\nconst flatColumnClause = (\n identifier: string,\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n switch (clause.op) {\n case \"eq\": {\n return `${identifier} = ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gt\": {\n return `${identifier} > ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gte\": {\n return `${identifier} >= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lt\": {\n return `${identifier} < ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lte\": {\n return `${identifier} <= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"in\": {\n return `${identifier} IN (${(clause.value as ReadonlyArray<DocumentValue>)\n .map((v) => quoteLeaf(v, target))\n .join(\", \")})`;\n }\n }\n};\n\nconst jsonColumnRootClause = (\n col: ColumnPlan,\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n // The root JSON column stores the value as JSON-encoded text;\n // we compare against the JSON encoding of the predicate value.\n // Range and `in` ops on a JSON-encoded root column compare the\n // JSON text lexicographically, which is rarely what the caller\n // wanted — for those, the operator is expected to promote the\n // field into a flat column or hand-edit the emitted SQL.\n if (clause.op === \"eq\") {\n const literal = JSON.stringify(clause.value);\n if (target === \"postgres\") {\n return `${col.identifier}::text = ${quoteValue(literal, target)}`;\n }\n return `${col.identifier} = ${quoteValue(literal, target)}`;\n }\n if (clause.op === \"in\") {\n const literals = (clause.value as ReadonlyArray<DocumentValue>).map((v) =>\n quoteValue(JSON.stringify(v), target),\n );\n if (target === \"postgres\") {\n return `${col.identifier}::text IN (${literals.join(\", \")})`;\n }\n return `${col.identifier} IN (${literals.join(\", \")})`;\n }\n // Range against JSON-encoded root: fall back to a lex compare on\n // the JSON serialisation. Surface a comment via the SQL itself;\n // the operator can hand-edit.\n const comparator = rangeComparator(clause.op);\n const literal = JSON.stringify(clause.value);\n if (target === \"postgres\") {\n return `${col.identifier}::text ${comparator} ${quoteValue(literal, target)}`;\n }\n return `${col.identifier} ${comparator} ${quoteValue(literal, target)}`;\n};\n\nconst jsonPathClause = (\n col: ColumnPlan,\n tail: readonly string[],\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n const accessor = jsonPathAccessor(col.identifier, tail, target);\n switch (clause.op) {\n case \"eq\": {\n return `${accessor} = ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gt\": {\n return `${accessor} > ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gte\": {\n return `${accessor} >= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lt\": {\n return `${accessor} < ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lte\": {\n return `${accessor} <= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"in\": {\n return `${accessor} IN (${(clause.value as ReadonlyArray<DocumentValue>)\n .map((v) => quoteLeaf(v, target))\n .join(\", \")})`;\n }\n }\n};\n\nconst rangeComparator = (op: PredicateClause[\"op\"]): string => {\n if (op === \"gt\") {\n return \">\";\n }\n if (op === \"gte\") {\n return \">=\";\n }\n if (op === \"lt\") {\n return \"<\";\n }\n return \"<=\";\n};\n\nconst jsonPathAccessor = (\n identifier: string,\n tail: readonly string[],\n target: SqlTarget,\n): string => {\n if (target === \"postgres\") {\n let expr = identifier;\n for (let i = 0; i < tail.length; i++) {\n const seg = tail[i]!;\n const isLast = i === tail.length - 1;\n const key = `'${seg.replace(/'/g, \"''\")}'`;\n expr = `${expr}${isLast ? \"->>\" : \"->\"}${key}`;\n }\n return expr;\n }\n const jsonPath = `'$.${tail.map((s) => s.replace(/'/g, \"''\")).join(\".\")}'`;\n return `json_extract(${identifier}, ${jsonPath})`;\n};\n\n/**\n * Quote a leaf primitive for use as the right-hand side of a\n * comparison. Booleans branch on target. Nested objects must never\n * reach here — wire `eq` clauses on nested objects can only come\n * from the callback form `q.eq(\"nested\", { ... })`, which the\n * export translator does not support today.\n */\nconst quoteLeaf = (value: DocumentValue, target: SqlTarget): string => {\n if (typeof value === \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"translatePredicateWireToSql: nested object reached leaf quoter — callback-form q.eq(field, object) is not supported for SQL export. Hand-edit the emitted SQL.\",\n );\n }\n return quoteValue(value, target);\n};\n","/**\n * Sidecar plan serialisation for `baerly export`.\n *\n * `baerly export --output=foo.sql` writes the inferred {@link ExportPlan}\n * alongside the SQL dump as `foo.sql.plan.json`. The round-trip test\n * (`tests/integration/export-round-trip.test.ts`) consumes the sidecar\n * to coerce SQLite-returned values back to their original JS type\n * (e.g. SQLite stores booleans as 0/1; we restore `true`/`false`).\n *\n * Wire shape (`schemaVersion = 1`):\n *\n * ```json\n * {\n * \"schemaVersion\": 1,\n * \"table\": \"tickets\",\n * \"target\": \"sqlite\",\n * \"columns\": [\n * { \"source\": \"_id\", \"sqlType\": \"TEXT\", \"nullable\": false, \"jsonEncoded\": false },\n * ...\n * ]\n * }\n * ```\n *\n * `identifier` is NOT carried on the wire — we re-derive it via\n * {@link quoteIdentifier} on deserialise. An attacker writing the\n * sidecar should not get SQL-emit control over identifiers.\n *\n * `rowCount` is also not preserved across the sidecar boundary; the\n * deserialised plan reports `0`. This is intentional — consumers that\n * care about row count read the SQL stream itself.\n */\n\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { quoteIdentifier } from \"./sql-escape.ts\";\nimport type { ColumnPlan, ExportPlan, SqlTarget, SqlType } from \"./types.ts\";\n\nconst SIDECAR_SCHEMA_VERSION = 1 as const;\n\nconst VALID_TARGETS: ReadonlySet<string> = new Set([\"postgres\", \"sqlite\", \"d1\"]);\n\nconst VALID_SQL_TYPES: ReadonlySet<string> = new Set([\n \"text\",\n \"boolean\",\n \"integer\",\n \"double precision\",\n \"jsonb\",\n \"TEXT\",\n \"INTEGER\",\n \"REAL\",\n]);\n\n/**\n * Encode an {@link ExportPlan} as the canonical sidecar JSON string.\n *\n * Wire format is pretty-printed (`indent=2`) with a trailing newline\n * so `cat sidecar.plan.json` is human-readable and `diff` works on\n * two sidecars without spurious line-end noise. The on-wire bytes\n * embed the `schemaVersion` discriminator so future shape changes\n * are detectable; `identifier` and `tableIdentifier` are NOT carried\n * (they're re-derived via {@link quoteIdentifier} on deserialise).\n */\nexport const serializeExportPlan = (plan: ExportPlan): string => {\n return (\n JSON.stringify(\n {\n schemaVersion: SIDECAR_SCHEMA_VERSION,\n table: plan.table,\n target: plan.target,\n columns: plan.columns.map((c) => ({\n source: c.source,\n sqlType: c.sqlType,\n nullable: c.nullable,\n jsonEncoded: c.jsonEncoded,\n })),\n },\n null,\n 2,\n ) + \"\\n\"\n );\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * Parse the sidecar JSON string back into an {@link ExportPlan}.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when the sidecar JSON is\n * malformed, the schema version is unsupported, or any required\n * field is missing / has an unexpected type. Identifiers are\n * re-quoted via {@link quoteIdentifier} rather than copied off the\n * wire — the sidecar cannot smuggle SQL-injection via a\n * pre-quoted identifier.\n */\nexport const deserializeExportPlan = (text: string): ExportPlan => {\n let raw: unknown;\n try {\n raw = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: parse failed: ${(error as Error).message}`,\n );\n }\n if (!isObject(raw)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"deserializeExportPlan: top-level value is not an object\",\n );\n }\n if (raw[\"schemaVersion\"] !== SIDECAR_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: unsupported schemaVersion ${String(raw[\"schemaVersion\"])} (expected ${String(SIDECAR_SCHEMA_VERSION)})`,\n );\n }\n if (typeof raw[\"table\"] !== \"string\" || raw[\"table\"].length === 0) {\n throw new BaerlyError(\"InvalidConfig\", \"deserializeExportPlan: missing or empty table\");\n }\n if (typeof raw[\"target\"] !== \"string\" || !VALID_TARGETS.has(raw[\"target\"])) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: unknown target ${JSON.stringify(raw[\"target\"])}`,\n );\n }\n if (!Array.isArray(raw[\"columns\"])) {\n throw new BaerlyError(\"InvalidConfig\", \"deserializeExportPlan: columns is not an array\");\n }\n const table = raw[\"table\"];\n const target = raw[\"target\"] as SqlTarget;\n const columns: ColumnPlan[] = [];\n for (const [i, col] of raw[\"columns\"].entries()) {\n if (!isObject(col)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}] is not an object`,\n );\n }\n if (typeof col[\"source\"] !== \"string\" || col[\"source\"].length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].source is missing or empty`,\n );\n }\n if (typeof col[\"sqlType\"] !== \"string\" || !VALID_SQL_TYPES.has(col[\"sqlType\"])) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].sqlType ${JSON.stringify(col[\"sqlType\"])} is not a recognised SqlType`,\n );\n }\n if (typeof col[\"nullable\"] !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].nullable is not a boolean`,\n );\n }\n if (typeof col[\"jsonEncoded\"] !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].jsonEncoded is not a boolean`,\n );\n }\n columns.push({\n source: col[\"source\"],\n identifier: quoteIdentifier(col[\"source\"], target),\n sqlType: col[\"sqlType\"] as SqlType,\n nullable: col[\"nullable\"],\n jsonEncoded: col[\"jsonEncoded\"],\n });\n }\n return {\n table,\n target,\n tableIdentifier: quoteIdentifier(table, target),\n columns,\n // Not preserved across the sidecar boundary — see file JSDoc.\n rowCount: 0,\n };\n};\n","/* eslint-disable no-underscore-dangle -- `_id` is the locked\n primary-key field on document shapes; the exporter threads it\n through the materialised view and the emitted INSERT rows. */\n\n/**\n * `baerly export` — snapshot dump of one collection to SQL.\n *\n * Drives the export modules end-to-end: load the materialised view,\n * infer an `ExportPlan` over the row shape, emit `CREATE TABLE` +\n * `INSERT` statements. When `--where=<json>` is supplied the\n * predicate is translated via `translatePredicateToSql` and applied\n * in-memory through `matches(...)` so the emitted INSERTs already\n * match the filter; the translated WHERE clause is also surfaced as a\n * comment above the inserts so operators can inspect / hand-edit it.\n *\n * The sidecar file (`<output>.plan.json`) carries the `ExportPlan` so\n * a follow-up round-trip ingest can verify the column schema. The\n * sidecar is JSON via `JSON.stringify` — the plan shape is the public\n * contract.\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --target Required. postgres | sqlite | d1.\n * --where Optional. JSON-encoded `Predicate<T>`.\n * --where-comment Optional. Caller hint surfaced as a\n * `-- TODO(baerly export):` comment.\n * --output Optional. Path to write SQL into; default\n * stdout. The sidecar plan is written to\n * `<output>.plan.json` unless `--no-sidecar`.\n * --no-sidecar Skip emitting the sidecar plan file.\n * --json JSON envelope on stdout (or stderr on error).\n *\n * Exit codes:\n * 0 — dump completed.\n * 1 — InvalidConfig (bad args / bucket URI / --where JSON / unknown --target).\n * 2 — Storage / Network error.\n * 3 — Protocol invariant (Internal / InvalidResponse / Conflict).\n */\n\nimport { writeFile } from \"node:fs/promises\";\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, matchesWire, type PredicateWire, validateWire } from \"@baerly/protocol\";\nimport {\n type ExportPlan,\n type ExportRow,\n type SqlTarget,\n emitCreateTable,\n emitInsertStatements,\n inferPlanForCollection,\n loadMaterialisedView,\n serializeExportPlan,\n translatePredicateWireToSql,\n} from \"./export/index.ts\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { emitSuccess } from \"./output.ts\";\nimport { defineBaerlySubcommand } from \"./subcommand.ts\";\n\nconst EXPORT_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Collection name.\",\n valueHint: \"name\",\n },\n target: {\n type: \"enum\",\n options: [\"postgres\", \"sqlite\", \"d1\"],\n required: true,\n description: \"SQL target: postgres | sqlite | d1.\",\n },\n where: {\n type: \"string\",\n required: false,\n description: \"JSON-encoded PredicateWire ({ clauses: [...] }) filtering the rows to export.\",\n valueHint: \"json\",\n },\n \"where-comment\": {\n type: \"string\",\n required: false,\n description: \"Caller hint surfaced as a -- TODO(baerly export): comment.\",\n valueHint: \"text\",\n },\n output: {\n type: \"string\",\n required: false,\n description: \"Path to write SQL into; default stdout.\",\n valueHint: \"path\",\n },\n sidecar: {\n type: \"boolean\",\n default: true,\n description: \"Emit a <output>.plan.json sidecar (default true; pass --no-sidecar to skip).\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\nconst parseWherePredicate = (raw: string): PredicateWire => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly export: --where is not valid JSON: ${(error as Error).message}`,\n );\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly export: --where must decode to a JSON object (got ${describeNonObject(parsed)})`,\n );\n }\n // Re-validate defensively; the translator will reject too, but\n // surfacing the error here gives a single uniform error path.\n validateWire(parsed as PredicateWire);\n return parsed as PredicateWire;\n};\n\nconst filterRows = (\n rows: ReadonlyMap<string, ExportRow>,\n wire: PredicateWire | null,\n): Map<string, ExportRow> => {\n const filtered = new Map<string, ExportRow>();\n for (const [id, body] of rows) {\n if (wire === null) {\n filtered.set(id, body);\n continue;\n }\n if (matchesWire(wire, body)) {\n filtered.set(id, body);\n }\n }\n return filtered;\n};\n\nconst buildSql = async (\n plan: ExportPlan,\n rows: ReadonlyMap<string, ExportRow>,\n whereClause: string,\n whereHints: readonly string[],\n): Promise<string> => {\n let out = emitCreateTable(plan);\n for (const hint of whereHints) {\n out += `-- TODO(baerly export): ${hint}\\n`;\n }\n if (whereClause.length > 0) {\n out += `-- WHERE clause for review: ${whereClause}\\n`;\n }\n for await (const chunk of emitInsertStatements(plan, rows)) {\n out += chunk;\n }\n return out;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"export\",\n meta: {\n description: \"Snapshot dump of one collection to SQL.\",\n },\n args: EXPORT_ARGS,\n handler: async (args, ctx) => {\n const target: SqlTarget = args.target;\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n const bucket = await parseBucketUri(args.bucket);\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n const view = await loadMaterialisedView({\n storage: bucket.storage,\n currentJsonKey,\n collection: args.collection,\n });\n if (view === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly export: collection ${JSON.stringify(args.collection)} is not provisioned (no current.json at ${currentJsonKey})`,\n );\n }\n const plan = inferPlanForCollection({\n rows: view,\n target,\n table: args.collection,\n });\n\n let wire: PredicateWire | null = null;\n let whereClause = \"\";\n let whereHints: readonly string[] = [];\n if (typeof args.where === \"string\" && args.where.length > 0) {\n wire = parseWherePredicate(args.where);\n const translation = translatePredicateWireToSql(\n wire,\n plan,\n typeof args[\"where-comment\"] === \"string\" && args[\"where-comment\"].length > 0\n ? { dynamicHint: args[\"where-comment\"] }\n : undefined,\n );\n whereClause = translation.sql;\n whereHints = translation.hints;\n } else if (typeof args[\"where-comment\"] === \"string\" && args[\"where-comment\"].length > 0) {\n // Bare --where-comment with no predicate still surfaces the operator's\n // note so reviewers see the intent.\n whereHints = [\n `caller-flagged dynamic predicate: ${args[\"where-comment\"]}. No predicate supplied; emitted INSERTs cover the full collection.`,\n ];\n }\n\n const filtered = filterRows(view, wire);\n const sql = await buildSql(plan, filtered, whereClause, whereHints);\n\n const outputPath = args.output;\n if (typeof outputPath === \"string\" && outputPath.length > 0) {\n await writeFile(outputPath, sql, \"utf8\");\n if (args.sidecar !== false) {\n await writeFile(`${outputPath}.plan.json`, serializeExportPlan(plan), \"utf8\");\n }\n } else {\n process.stdout.write(sql);\n }\n\n emitSuccess({\n command: \"export\",\n status: \"ok\",\n collection: args.collection,\n target,\n rows: filtered.size,\n hints: whereHints,\n ...(typeof outputPath === \"string\" && outputPath.length > 0 && { output: outputPath }),\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly export`. */\nexport const exportCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runExport = bundle.run;\n\n// Build a human-readable label for the \"expected JSON object\" error.\n// `null`, arrays, and the bare `undefined` need to be disambiguated\n// from `typeof`'s default \"object\".\nconst describeNonObject = (v: unknown): string => {\n if (v === null) {\n return \"null\";\n }\n if (Array.isArray(v)) {\n return \"array\";\n }\n return typeof v;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAcA,MAAa,mBAAmB,SAA6B;CAC3D,IAAI,KAAK,QAAQ,WAAW,GAC1B,MAAM,IAAI,YACR,eACA,+BAA+B,KAAK,UAAU,KAAK,KAAK,EAAE,2CAC5D;CAEF,IAAI,KAAK,WAAW,QAAQ,KAAK,MAAM,YAAY,EAAE,WAAW,SAAS,GACvE,MAAM,IAAI,YACR,eACA,mEAAmE,KAAK,UAAU,KAAK,KAAK,EAAE,EAChG;CAEF,MAAM,QAAk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