@gusto/baerly-storage 0.6.0 → 0.7.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 (218) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -512
  3. package/dist/CHANGELOG.md +1137 -378
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-ypCm3zjt.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-wrVYf4bb.js → cloudflare-CKHYXccw.js} +61 -82
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-Di_Q01qx.js → deploy-Obj4nE-Z.js} +10 -14
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +9 -14
  53. package/dist/dev-vite.js +11 -10
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/{gcs-admin-Bx6xSNJj.d.ts → gcs-admin-Dso1HWQj.d.ts} +18 -14
  68. package/dist/gcs.d.ts +19 -7
  69. package/dist/gcs.js +1 -2
  70. package/dist/{goog4-signer-Z7KnJ1su.js → goog4-signer-CeLIABoE.js} +102 -92
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-7zT29K3P.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-DP3ClvcA.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +119 -92
  103. package/dist/node.js +3 -3
  104. package/dist/{observability-Ch-VQJyE.js → observability-C-ISCCLE.js} +1247 -326
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-C4qgiXSg.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec--LykAdl1.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-DD5gDc7t.d.ts → s3-http-DBC_wiCL.d.ts} +14 -8
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/{sha256-CqcKTjw9.js → sha256-4FfGQNPw.js} +9 -9
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/{aws4fetch.esm-CXE5ZbAa.js → sigv4-sign-5IUflUD_.js} +143 -96
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BMFfDUI2.js → src-Actga-bO.js} +949 -363
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-BV68pqwJ.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-BMZR8o6U.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +90 -69
  152. package/dist/aws4fetch.esm-CXE5ZbAa.js.map +0 -1
  153. package/dist/bytes-BXdamO3L.js +0 -11
  154. package/dist/bytes-BXdamO3L.js.map +0 -1
  155. package/dist/cloudflare-wrVYf4bb.js.map +0 -1
  156. package/dist/config-B6nTy8e2.js +0 -3095
  157. package/dist/config-B6nTy8e2.js.map +0 -1
  158. package/dist/constants-CfeMWQWk.js +0 -222
  159. package/dist/constants-CfeMWQWk.js.map +0 -1
  160. package/dist/context-DRZ3tZ5l.js.map +0 -1
  161. package/dist/cost-_SE_SVgZ.js +0 -203
  162. package/dist/cost-_SE_SVgZ.js.map +0 -1
  163. package/dist/current-json-C6nhPOm1.js.map +0 -1
  164. package/dist/db-DjjthkTi.d.ts +0 -254
  165. package/dist/deploy-Di_Q01qx.js.map +0 -1
  166. package/dist/doctor-RWVRpvat.js +0 -102
  167. package/dist/doctor-RWVRpvat.js.map +0 -1
  168. package/dist/dump-m2vEYDNY.js +0 -94
  169. package/dist/dump-m2vEYDNY.js.map +0 -1
  170. package/dist/errors-Dfa3p78c.js +0 -78
  171. package/dist/errors-Dfa3p78c.js.map +0 -1
  172. package/dist/export-DenKwEQu.js +0 -401
  173. package/dist/export-DenKwEQu.js.map +0 -1
  174. package/dist/fsck-2Vq-7-e2.js +0 -279
  175. package/dist/fsck-2Vq-7-e2.js.map +0 -1
  176. package/dist/goog4-signer-Z7KnJ1su.js.map +0 -1
  177. package/dist/http-7zT29K3P.js.map +0 -1
  178. package/dist/http-transport-BTgVCY5r.js +0 -1250
  179. package/dist/http-transport-BTgVCY5r.js.map +0 -1
  180. package/dist/index-BHz92Acj.d.ts +0 -162
  181. package/dist/index-CEZKQsKt.d.ts +0 -1113
  182. package/dist/index-uE-w2dgj.d.ts +0 -115
  183. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  184. package/dist/inspect-BpYbH1DM.js +0 -133
  185. package/dist/inspect-BpYbH1DM.js.map +0 -1
  186. package/dist/log-tail-QWU4wlu-.js +0 -514
  187. package/dist/log-tail-QWU4wlu-.js.map +0 -1
  188. package/dist/maintenance-BGHGt2Yg.d.ts +0 -537
  189. package/dist/maintenance-DULFcpd1.js +0 -2144
  190. package/dist/maintenance-DULFcpd1.js.map +0 -1
  191. package/dist/maintenance-fEi-UZ2o.js +0 -1412
  192. package/dist/maintenance-fEi-UZ2o.js.map +0 -1
  193. package/dist/normalize-rjnZLwS4.js +0 -133
  194. package/dist/normalize-rjnZLwS4.js.map +0 -1
  195. package/dist/observability-Ch-VQJyE.js.map +0 -1
  196. package/dist/plan-C4qgiXSg.js.map +0 -1
  197. package/dist/query-C43r-6ib.js +0 -1773
  198. package/dist/query-C43r-6ib.js.map +0 -1
  199. package/dist/rebuild-index-BH1dc1p6.js +0 -81
  200. package/dist/rebuild-index-BH1dc1p6.js.map +0 -1
  201. package/dist/request-u0M51mhJ.js +0 -72
  202. package/dist/request-u0M51mhJ.js.map +0 -1
  203. package/dist/restore-D0VYWzfP.js +0 -778
  204. package/dist/restore-D0VYWzfP.js.map +0 -1
  205. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  206. package/dist/runtime-spec--LykAdl1.js.map +0 -1
  207. package/dist/sha256-CqcKTjw9.js.map +0 -1
  208. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  209. package/dist/src-BMFfDUI2.js.map +0 -1
  210. package/dist/src-DYZ4H1aF.js +0 -392
  211. package/dist/src-DYZ4H1aF.js.map +0 -1
  212. package/dist/src-DvbTEya2.js +0 -536
  213. package/dist/src-DvbTEya2.js.map +0 -1
  214. package/dist/subcommand-BV68pqwJ.js.map +0 -1
  215. package/dist/time-DUqvFMHq.js.map +0 -1
  216. package/dist/usage-BMZR8o6U.js.map +0 -1
  217. package/dist/validate-DtljsCh1.js.map +0 -1
  218. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -1,78 +0,0 @@
1
- //#region packages/protocol/src/errors.ts
2
- /**
3
- * Codes whose default failure class is resolved by retrying with a fresh read.
4
- * Throw sites may override this when the same code is context-sensitive
5
- * (notably caller-supplied `_id` collisions, which also use `Conflict`).
6
- */
7
- const RETRIABLE_CODES = /* @__PURE__ */ new Set(["NetworkError", "Conflict"]);
8
- /** True iff this error code's default failure class is retriable. */
9
- const isRetriableCode = (code) => RETRIABLE_CODES.has(code);
10
- /**
11
- * The single error class thrown by baerly-storage. Discriminate by `code`, not
12
- * `instanceof`: the code string survives `JSON.stringify` round-trips
13
- * across Worker / iframe / postMessage realm boundaries, where each
14
- * realm has its own `BaerlyError` constructor identity. IDB-restored
15
- * writes can replay across realms, so `instanceof` would spuriously
16
- * fail on a structurally-identical error from another realm.
17
- *
18
- * @example
19
- * ```ts
20
- * try {
21
- * await db.collection("tickets").insert({ title: "hi" });
22
- * } catch (err) {
23
- * if (err instanceof BaerlyError && err.code === "Conflict") {
24
- * // Check err.retriable; CAS can retry, duplicate _id cannot.
25
- * }
26
- * throw err;
27
- * }
28
- * ```
29
- */
30
- var BaerlyError = class extends Error {
31
- code;
32
- cause;
33
- /**
34
- * Structured field-path issues, set only when `code === "SchemaError"`.
35
- * Each entry's `path` is a dotted-key list (e.g. `["assignee", "team"]`
36
- * or `["items", 3, "qty"]`) that targets the offending field on the
37
- * input document. `message` is the validator-emitted human string.
38
- *
39
- * The HTTP layer's `mapError` renders these into the 400 body via
40
- * the existing `HttpErrorEnvelope`; older callers that don't know
41
- * about `issues` see a plain message-only error and stay correct.
42
- */
43
- issues;
44
- /**
45
- * Raw HTTP status, set only by the client-side wire decoder when
46
- * inflating an `HttpErrorEnvelope` into this class. Server-side
47
- * throws never set it (the HTTP layer's `mapError` derives the
48
- * outbound status from `code`). Useful for diagnostics — e.g. to
49
- * distinguish 404-as-"no such row" from 404-as-"route not found".
50
- * Discriminate by `code` for behavior; reach for `status` only when
51
- * you genuinely need the wire value.
52
- */
53
- status;
54
- /** Canonical corrective action; crosses the wire via `HttpErrorEnvelope.error.resolution`. */
55
- resolution;
56
- retriableOverride;
57
- /**
58
- * Whether this error instance is retriable. Defaults from `code`, but
59
- * context-sensitive throw sites can override it.
60
- */
61
- get retriable() {
62
- return this.retriableOverride ?? isRetriableCode(this.code);
63
- }
64
- constructor(code, message, cause, issues, status, resolution, retriableOverride) {
65
- super(message);
66
- this.name = "BaerlyError";
67
- this.code = code;
68
- this.cause = cause;
69
- this.retriableOverride = retriableOverride;
70
- if (issues !== void 0) this.issues = issues;
71
- if (status !== void 0) this.status = status;
72
- if (resolution !== void 0) this.resolution = resolution;
73
- }
74
- };
75
- //#endregion
76
- export { isRetriableCode as n, BaerlyError as t };
77
-
78
- //# sourceMappingURL=errors-Dfa3p78c.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"errors-Dfa3p78c.js","names":[],"sources":["../packages/protocol/src/errors.ts"],"sourcesContent":["/**\n * Discriminator for {@link BaerlyError}. Strings (not subclasses) so they\n * survive cross-realm boundaries (e.g. a Web Worker) and so callers can\n * pattern-match with grep-friendly equality.\n */\nexport type BaerlyErrorCode =\n /** Caller-provided config or input is invalid (bad bucket, unsupported credential type, malformed URL, bucket not version-enabled when versioning was requested). */\n | \"InvalidConfig\"\n /** Generic S3/HTTP transport failure (5xx, unexpected status, retries exhausted). */\n | \"NetworkError\"\n /** S3 returned 403. Either credentials are wrong or the bucket policy denies the operation. */\n | \"AccessDenied\"\n /** Server returned data that didn't parse (malformed XML, non-JSON body where JSON expected). */\n | \"InvalidResponse\"\n /** Internal invariant violation — should not be reachable. File a bug. */\n | \"Internal\"\n /**\n * Document body failed schema validation. Emitted by the table-API\n * write verbs (`Collection.insert`, `Query.update`, `Collection.replace`) when\n * the body is not valid JSON or contains an array where\n * `DocumentValue` is required; also emitted when a collection has a\n * declared `SchemaValidator` (via `Db.create({ collections })`) and\n * the bound schema rejects the doc. In the schema-rejection case the\n * error carries an `issues` array describing each failure. HTTP layer\n * maps this to 400.\n */\n | \"SchemaError\"\n /**\n * Write conflicted with current state: CAS retry budget exhausted,\n * duplicate caller-supplied `_id`, or an already-existing guarded\n * storage key. Check `BaerlyError.retriable` to decide whether the\n * same logical operation should be retried.\n */\n | \"Conflict\"\n /**\n * `Verifier` returned no identity. HTTP server maps to 401.\n * Code is reserved here so the union locks.\n */\n | \"Unauthorized\"\n /**\n * The addressed resource does not exist. HTTP server maps to 404.\n * Emitted by the row-by-id read / update / delete handlers in\n * `packages/server/src/http/router.ts` when the predicate\n * `{ _id }` matches zero rows. Not a protocol invariant —\n * callers may retry after creating the resource or treat as a\n * miss depending on intent. The CLI maps this to the generic\n * exit-2 \"storage error\" bucket, not the exit-3 \"protocol\n * invariant\" bucket.\n */\n | \"NotFound\"\n /**\n * Request body exceeded the server's size cap. HTTP server maps\n * to 413. Cap is `MAX_BODY_BYTES` (1 MiB today; exported from\n * `packages/server/src/http/router.ts`). The Node adapter\n * enforces during the `node:http` stream pump so the process\n * never materializes a multi-MiB body; Workers also rely on\n * platform-side caps (16 MB free / 100 MB paid).\n */\n | \"PayloadTooLarge\"\n /**\n * A predicate is structurally well-formed but contradicts itself —\n * no document can match. Emitted by `validateWire` and\n * `mergePredicateWires`. Triggers:\n * - `{ clauses: [{op:\"in\", field:\"priority\", value:[]}] }` (empty `in` set)\n * - an `eq` clause with a value outside the residual interval\n * established by range clauses on the same field\n * - merging `{op:\"gt\", value:10}` with `{op:\"lt\", value:5}` on the\n * same field (empty interval)\n * - merging two `in` clauses on the same field with empty intersection\n *\n * Conflicting equality across clauses (`eq:\"open\"` + `eq:\"closed\"` on\n * the same field) surfaces as `InvalidConfig` rather than this code —\n * the merger treats it as a caller-side configuration bug, not an\n * algebraic contradiction.\n *\n * The HTTP layer treats this as a 400 (caller error). The distinct\n * code lets downstream code short-circuit empty-by-construction\n * without re-running the validator or parsing messages.\n */\n | \"UnsatisfiablePredicate\"\n /**\n * A `useQuery` callback awaited a recorder terminal\n * (`.get`/`.first`/`.all`/`.count`). The recorder runs once per\n * render to capture the chain shape; it cannot survive an `await`\n * because the proxy doesn't proxy across microtask boundaries. The\n * recorder's terminal returns a thenable whose `.then` throws this\n * error synchronously, converting what would otherwise be a silent\n * spinner-hang into a render-time error the hook surfaces as\n * `status: \"error\"`. Companion `baerly/no-await-in-use-query` lint\n * flags the pattern at edit time. For compound reads, use\n * `Promise.all` (parallel) or compose two `useQuery` calls with\n * `useQuery.skip` (dependent).\n */\n | \"UseQueryAwaitedRecorder\"\n /**\n * A write method (`.insert`/`.update`/`.replace`/`.delete`) was\n * called on the recorder inside a `useQuery` callback. Writes\n * inside reads are a programming error; the recorder rejects them\n * synchronously from the discovery pass, before any I/O fires. Use\n * `useMutation()` instead.\n */\n | \"UnexpectedWriteInQuery\"\n /**\n * A `useMutation()` callback rejected with a non-`BaerlyError`\n * throwable. The hook wraps the original throw under this code so\n * the `error` slot is always a `BaerlyError`; the original value\n * is preserved on `.cause`.\n */\n | \"MutationFailed\";\n\n/**\n * Runtime enumeration of every {@link BaerlyErrorCode}. The spec\n * generator and the drift gate iterate this to assert the IR lists\n * each code; the type guard in `spec/ir-schema.test.ts` fails tsgo if\n * this tuple and the union diverge. Keep order stable for deterministic\n * artifact diffs. This is the canonical code list — do not re-list\n * codes elsewhere (see RETRIABLE_CODES, the sibling retriable subset).\n */\nexport const ERROR_CODES = [\n \"InvalidConfig\",\n \"NetworkError\",\n \"AccessDenied\",\n \"InvalidResponse\",\n \"Internal\",\n \"SchemaError\",\n \"Conflict\",\n \"Unauthorized\",\n \"NotFound\",\n \"PayloadTooLarge\",\n \"UnsatisfiablePredicate\",\n \"UseQueryAwaitedRecorder\",\n \"UnexpectedWriteInQuery\",\n \"MutationFailed\",\n] as const satisfies readonly BaerlyErrorCode[];\n\n// Exhaustiveness guard: every union member must appear in ERROR_CODES.\n// If a code is added to BaerlyErrorCode without a tuple entry, this\n// errors at tsgo time (the union is not assignable to the tuple's union).\ntype _ErrorCodesExhaustive = [BaerlyErrorCode] extends [(typeof ERROR_CODES)[number]]\n ? true\n : [\"missing code in ERROR_CODES\", Exclude<BaerlyErrorCode, (typeof ERROR_CODES)[number]>];\n// eslint-disable-next-line no-underscore-dangle\nconst _errorCodesExhaustive: _ErrorCodesExhaustive = true;\nvoid _errorCodesExhaustive;\n\n/**\n * Codes whose default failure class is resolved by retrying with a fresh read.\n * Throw sites may override this when the same code is context-sensitive\n * (notably caller-supplied `_id` collisions, which also use `Conflict`).\n */\nexport const RETRIABLE_CODES: ReadonlySet<BaerlyErrorCode> = new Set<BaerlyErrorCode>([\n \"NetworkError\",\n \"Conflict\",\n]);\n\n/** True iff this error code's default failure class is retriable. */\nexport const isRetriableCode = (code: BaerlyErrorCode): boolean => RETRIABLE_CODES.has(code);\n\n/**\n * Codes raised only inside the client-side React runtime\n * (`useQuery` / `useMutation`); they never travel the HTTP wire, so the\n * machine-contract IR reports `httpStatus: null` for them — distinct\n * from a real `500` (a server-side transport/internal failure the HTTP\n * layer maps to a status). Sibling of {@link RETRIABLE_CODES}; add a\n * code here when a new client-only failure mode joins the union.\n */\nexport const CLIENT_RUNTIME_CODES: ReadonlySet<BaerlyErrorCode> = new Set<BaerlyErrorCode>([\n \"UseQueryAwaitedRecorder\",\n \"UnexpectedWriteInQuery\",\n \"MutationFailed\",\n]);\n\n/**\n * The single error class thrown by baerly-storage. Discriminate by `code`, not\n * `instanceof`: the code string survives `JSON.stringify` round-trips\n * across Worker / iframe / postMessage realm boundaries, where each\n * realm has its own `BaerlyError` constructor identity. IDB-restored\n * writes can replay across realms, so `instanceof` would spuriously\n * fail on a structurally-identical error from another realm.\n *\n * @example\n * ```ts\n * try {\n * await db.collection(\"tickets\").insert({ title: \"hi\" });\n * } catch (err) {\n * if (err instanceof BaerlyError && err.code === \"Conflict\") {\n * // Check err.retriable; CAS can retry, duplicate _id cannot.\n * }\n * throw err;\n * }\n * ```\n */\nexport class BaerlyError extends Error {\n readonly code: BaerlyErrorCode;\n override readonly cause?: unknown;\n /**\n * Structured field-path issues, set only when `code === \"SchemaError\"`.\n * Each entry's `path` is a dotted-key list (e.g. `[\"assignee\", \"team\"]`\n * or `[\"items\", 3, \"qty\"]`) that targets the offending field on the\n * input document. `message` is the validator-emitted human string.\n *\n * The HTTP layer's `mapError` renders these into the 400 body via\n * the existing `HttpErrorEnvelope`; older callers that don't know\n * about `issues` see a plain message-only error and stay correct.\n */\n readonly issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>;\n /**\n * Raw HTTP status, set only by the client-side wire decoder when\n * inflating an `HttpErrorEnvelope` into this class. Server-side\n * throws never set it (the HTTP layer's `mapError` derives the\n * outbound status from `code`). Useful for diagnostics — e.g. to\n * distinguish 404-as-\"no such row\" from 404-as-\"route not found\".\n * Discriminate by `code` for behavior; reach for `status` only when\n * you genuinely need the wire value.\n */\n readonly status?: number;\n /** Canonical corrective action; crosses the wire via `HttpErrorEnvelope.error.resolution`. */\n readonly resolution?: string;\n private readonly retriableOverride: boolean | undefined;\n\n /**\n * Whether this error instance is retriable. Defaults from `code`, but\n * context-sensitive throw sites can override it.\n */\n get retriable(): boolean {\n return this.retriableOverride ?? isRetriableCode(this.code);\n }\n\n constructor(\n code: BaerlyErrorCode,\n message: string,\n cause?: unknown,\n issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>,\n status?: number,\n resolution?: string,\n retriableOverride?: boolean,\n ) {\n super(message);\n this.name = \"BaerlyError\";\n this.code = code;\n this.cause = cause;\n this.retriableOverride = retriableOverride;\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (issues !== undefined) {\n this.issues = issues;\n }\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (status !== undefined) {\n this.status = status;\n }\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (resolution !== undefined) {\n this.resolution = resolution;\n }\n }\n}\n"],"mappings":";;;;;;AAsJA,MAAa,kCAAgD,IAAI,IAAqB,CACpF,gBACA,UACF,CAAC;;AAGD,MAAa,mBAAmB,SAAmC,gBAAgB,IAAI,IAAI;;;;;;;;;;;;;;;;;;;;;AAoC3F,IAAa,cAAb,cAAiC,MAAM;CACrC;CACA;;;;;;;;;;;CAWA;;;;;;;;;;CAaA;;CAEA;CACA;;;;;CAMA,IAAI,YAAqB;EACvB,OAAO,KAAK,qBAAqB,gBAAgB,KAAK,IAAI;CAC5D;CAEA,YACE,MACA,SACA,OACA,QAIA,QACA,YACA,mBACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,QAAQ;EACb,KAAK,oBAAoB;EAEzB,IAAI,WAAW,KAAA,GACb,KAAK,SAAS;EAGhB,IAAI,WAAW,KAAA,GACb,KAAK,SAAS;EAGhB,IAAI,eAAe,KAAA,GACjB,KAAK,aAAa;CAEtB;AACF"}
@@ -1,401 +0,0 @@
1
- import { r as parseBucketUri } from "./config-B6nTy8e2.js";
2
- import { n as matchesWire, t as validateWire } from "./validate-DtljsCh1.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-C4qgiXSg.js";
5
- import { a as TENANT_ARG, i as JSON_ARG, n as BUCKET_ARG, o as assertCollectionArg, r as COLLECTION_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-BV68pqwJ.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: BUCKET_ARG,
271
- app: APP_ARG,
272
- tenant: TENANT_ARG,
273
- collection: COLLECTION_ARG,
274
- target: {
275
- type: "enum",
276
- options: [
277
- "postgres",
278
- "sqlite",
279
- "d1"
280
- ],
281
- required: true,
282
- description: "SQL target: postgres | sqlite | d1."
283
- },
284
- where: {
285
- type: "string",
286
- required: false,
287
- description: "JSON-encoded PredicateWire ({ clauses: [...] }) filtering the rows to export.",
288
- valueHint: "json"
289
- },
290
- "where-comment": {
291
- type: "string",
292
- required: false,
293
- description: "Caller hint surfaced as a -- TODO(baerly export): comment.",
294
- valueHint: "text"
295
- },
296
- output: {
297
- type: "string",
298
- required: false,
299
- description: "Path to write SQL into; default stdout.",
300
- valueHint: "path"
301
- },
302
- sidecar: {
303
- type: "boolean",
304
- default: true,
305
- description: "Emit a <output>.plan.json sidecar (default true; pass --no-sidecar to skip)."
306
- },
307
- json: JSON_ARG
308
- };
309
- const parseWherePredicate = (raw) => {
310
- let parsed;
311
- try {
312
- parsed = JSON.parse(raw);
313
- } catch (error) {
314
- throw new BaerlyError("InvalidConfig", `baerly export: --where is not valid JSON: ${error.message}`);
315
- }
316
- 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)})`);
317
- validateWire(parsed);
318
- return parsed;
319
- };
320
- const filterRows = (rows, wire) => {
321
- const filtered = /* @__PURE__ */ new Map();
322
- for (const [id, body] of rows) {
323
- if (wire === null) {
324
- filtered.set(id, body);
325
- continue;
326
- }
327
- if (matchesWire(wire, body)) filtered.set(id, body);
328
- }
329
- return filtered;
330
- };
331
- const buildSql = async (plan, rows, whereClause, whereHints) => {
332
- let out = emitCreateTable(plan);
333
- for (const hint of whereHints) out += `-- TODO(baerly export): ${hint}\n`;
334
- if (whereClause.length > 0) out += `-- WHERE clause for review: ${whereClause}\n`;
335
- for await (const chunk of emitInsertStatements(plan, rows)) out += chunk;
336
- return out;
337
- };
338
- const bundle = defineBaerlySubcommand({
339
- name: "export",
340
- meta: { description: "Snapshot dump of one collection to SQL." },
341
- args: EXPORT_ARGS,
342
- handler: async (args, ctx) => {
343
- const target = args.target;
344
- const { app, tenant } = await ctx.resolveAppTenant({
345
- app: args.app,
346
- tenant: args.tenant
347
- });
348
- assertCollectionArg(args.collection, "baerly export");
349
- const bucket = await parseBucketUri(args.bucket);
350
- const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;
351
- const view = await loadMaterialisedView({
352
- storage: bucket.storage,
353
- currentJsonKey,
354
- collection: args.collection
355
- });
356
- if (view === null) throw new BaerlyError("InvalidConfig", `baerly export: collection ${JSON.stringify(args.collection)} is not provisioned (no current.json at ${currentJsonKey})`);
357
- const plan = inferPlanForCollection({
358
- rows: view,
359
- target,
360
- table: args.collection
361
- });
362
- let wire = null;
363
- let whereClause = "";
364
- let whereHints = [];
365
- if (typeof args.where === "string" && args.where.length > 0) {
366
- wire = parseWherePredicate(args.where);
367
- const translation = translatePredicateWireToSql(wire, plan, typeof args["where-comment"] === "string" && args["where-comment"].length > 0 ? { dynamicHint: args["where-comment"] } : void 0);
368
- whereClause = translation.sql;
369
- whereHints = translation.hints;
370
- } 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.`];
371
- const filtered = filterRows(view, wire);
372
- const sql = await buildSql(plan, filtered, whereClause, whereHints);
373
- const outputPath = args.output;
374
- if (typeof outputPath === "string" && outputPath.length > 0) {
375
- await writeFile(outputPath, sql, "utf8");
376
- if (args.sidecar !== false) await writeFile(`${outputPath}.plan.json`, serializeExportPlan(plan), "utf8");
377
- } else process.stdout.write(sql);
378
- emitSuccess({
379
- command: "export",
380
- status: "ok",
381
- collection: args.collection,
382
- target,
383
- rows: filtered.size,
384
- hints: whereHints,
385
- ...typeof outputPath === "string" && outputPath.length > 0 && { output: outputPath }
386
- });
387
- return 0;
388
- }
389
- });
390
- /** citty `defineCommand` block for `baerly export`. */
391
- const exportCmd = bundle.cmd;
392
- bundle.run;
393
- const describeNonObject = (v) => {
394
- if (v === null) return "null";
395
- if (Array.isArray(v)) return "array";
396
- return typeof v;
397
- };
398
- //#endregion
399
- export { exportCmd };
400
-
401
- //# sourceMappingURL=export-DenKwEQu.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"export-DenKwEQu.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 {\n APP_ARG,\n assertCollectionArg,\n BUCKET_ARG,\n COLLECTION_ARG,\n defineBaerlySubcommand,\n JSON_ARG,\n TENANT_ARG,\n} from \"./subcommand.ts\";\n\nconst EXPORT_ARGS = {\n bucket: BUCKET_ARG,\n app: APP_ARG,\n tenant: TENANT_ARG,\n collection: COLLECTION_ARG,\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: JSON_ARG,\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 assertCollectionArg(args.collection, \"baerly export\");\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,CAAC,CAAC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