@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,392 +0,0 @@
1
- import { t as __commonJSMin } from "./rolldown-runtime-EAsCxrDo.js";
2
- import { n as createCurrentJson } from "./current-json-C6nhPOm1.js";
3
- import { t as BaerlyError } from "./errors-Dfa3p78c.js";
4
- import { t as assertValidStorageKey } from "./key-Di6yyxFu.js";
5
- import { createHash } from "node:crypto";
6
- import { link, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
7
- import { tmpdir } from "node:os";
8
- import { dirname, join, posix, relative, resolve, sep } from "node:path";
9
- //#region node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.browser.js
10
- var require_picocolors_browser = /* @__PURE__ */ __commonJSMin(((exports, module) => {
11
- var x = String;
12
- var create = function() {
13
- return {
14
- isColorSupported: false,
15
- reset: x,
16
- bold: x,
17
- dim: x,
18
- italic: x,
19
- underline: x,
20
- inverse: x,
21
- hidden: x,
22
- strikethrough: x,
23
- black: x,
24
- red: x,
25
- green: x,
26
- yellow: x,
27
- blue: x,
28
- magenta: x,
29
- cyan: x,
30
- white: x,
31
- gray: x,
32
- bgBlack: x,
33
- bgRed: x,
34
- bgGreen: x,
35
- bgYellow: x,
36
- bgBlue: x,
37
- bgMagenta: x,
38
- bgCyan: x,
39
- bgWhite: x,
40
- blackBright: x,
41
- redBright: x,
42
- greenBright: x,
43
- yellowBright: x,
44
- blueBright: x,
45
- magentaBright: x,
46
- cyanBright: x,
47
- whiteBright: x,
48
- bgBlackBright: x,
49
- bgRedBright: x,
50
- bgGreenBright: x,
51
- bgYellowBright: x,
52
- bgBlueBright: x,
53
- bgMagentaBright: x,
54
- bgCyanBright: x,
55
- bgWhiteBright: x
56
- };
57
- };
58
- module.exports = create();
59
- module.exports.createColors = create;
60
- }));
61
- //#endregion
62
- //#region packages/dev/src/dev-banner.ts
63
- var import_picocolors_browser = require_picocolors_browser();
64
- function printDevBanner(opts) {
65
- const isPlain = opts.plain !== void 0 ? opts.plain : process.env["CI"] !== void 0 || !process.stderr.isTTY;
66
- const write = opts.write ?? ((chunk) => process.stderr.write(chunk));
67
- const pc = (0, import_picocolors_browser.createColors)(!isPlain);
68
- const hints = opts.hints ?? [];
69
- const lines = [];
70
- if (isPlain) {
71
- lines.push(`baerly · ${opts.name}`);
72
- if (opts.primaryUrl) lines.push(`${opts.primaryUrl.label}: ${opts.primaryUrl.url}`);
73
- if (opts.apiUrl) {
74
- const note = opts.apiUrl.note ? ` (${opts.apiUrl.note})` : "";
75
- lines.push(`${opts.apiUrl.label}: ${opts.apiUrl.url}${note}`);
76
- }
77
- for (const hint of hints) lines.push(`${hint.key}: ${hint.value}`);
78
- write(lines.join("\n") + "\n");
79
- } else {
80
- lines.push(pc.bold(pc.cyan(`▎ baerly · ${opts.name}`)));
81
- lines.push("");
82
- if (opts.primaryUrl) {
83
- const marker = ` ${pc.green("← open this")}`;
84
- lines.push(` ${pc.dim(opts.primaryUrl.label)} → ${opts.primaryUrl.url}${marker}`);
85
- }
86
- if (opts.apiUrl) {
87
- const note = opts.apiUrl.note ? ` ${pc.dim(`(${opts.apiUrl.note})`)}` : "";
88
- lines.push(` ${pc.dim(opts.apiUrl.label)} → ${opts.apiUrl.url}${note}`);
89
- }
90
- if ((opts.primaryUrl || opts.apiUrl) && hints.length > 0) lines.push("");
91
- if (hints.length > 0) {
92
- const maxKeyLen = Math.max(...hints.map((h) => h.key.length));
93
- for (const hint of hints) lines.push(` ${pc.dim(hint.key.padEnd(maxKeyLen))} ${hint.value}`);
94
- }
95
- lines.push("");
96
- write(lines.join("\n"));
97
- }
98
- }
99
- //#endregion
100
- //#region packages/dev/src/dev-landing.ts
101
- /**
102
- * Render the dev landing page HTML. Dependency-free; system fonts
103
- * only; no JS. All substitutions are HTML-escaped to keep the page
104
- * inert even when `app` / `uiUrl` come from env vars.
105
- */
106
- const renderDevLanding = (opts) => {
107
- const label = escapeHtml(opts.app);
108
- const app = escapeHtml(opts.app);
109
- const uiUrl = escapeHtml(opts.uiUrl);
110
- return `<!doctype html>
111
- <html lang="en">
112
- <head>
113
- <meta charset="utf-8">
114
- <title>${label} — baerly api</title>
115
- <style>
116
- body { font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; max-width: 40rem; margin: 3rem auto; padding: 0 1.5rem; color: #222; line-height: 1.5; }
117
- h1 { font-size: 1.25rem; margin: 0 0 0.25rem; }
118
- p.tag { color: #666; margin: 0 0 1.5rem; font-size: 0.9rem; }
119
- a { color: #06c; }
120
- ul { padding-left: 1.25rem; }
121
- li { margin: 0.25rem 0; }
122
- code { background: #f3f3f3; padding: 0.1em 0.35em; border-radius: 3px; font-size: 0.9em; }
123
- </style>
124
- </head>
125
- <body>
126
- <h1>${label}</h1>
127
- <p class="tag">baerly api server · app <code>${app}</code></p>
128
- <p>This is the API server. The UI lives at <a href="${uiUrl}">${uiUrl}</a>.</p>
129
- <ul>
130
- <li>Open the UI: <a href="${uiUrl}">${uiUrl}</a></li>
131
- <li>Health probe: <a href="/v1/healthz">/v1/healthz</a></li>
132
- <li>CRUD routes under <code>/v1/c/*</code> require an auth header and aren't clickable from here.</li>
133
- </ul>
134
- </body>
135
- </html>
136
- `;
137
- };
138
- const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => {
139
- switch (c) {
140
- case "&": return "&amp;";
141
- case "<": return "&lt;";
142
- case ">": return "&gt;";
143
- case "\"": return "&quot;";
144
- default: return "&#39;";
145
- }
146
- });
147
- //#endregion
148
- //#region packages/dev/src/ensure-table.ts
149
- /**
150
- * Optional pre-warm: idempotently create the `current.json` manifest
151
- * for a single `(app, tenant, table)` triple. The kernel auto-creates
152
- * this manifest on the first commit anyway (see `Db.create` and
153
- * `Writer.commit`), so calling `ensureTable` is **not required** for
154
- * correctness — it's a one-Class-A-PUT optimization for callers that
155
- * want the manifest in place before the first request lands (seed
156
- * scripts, deploy-time provisioning, CI fixtures that snapshot the
157
- * bucket between phases, etc.).
158
- *
159
- * Wraps {@link createCurrentJson} with the canonical key shape
160
- * (`app/<app>/tenant/<tenant>/manifests/<table>/current.json`) and
161
- * swallows `BaerlyError{code:"Conflict"}` so re-runs are safe. An
162
- * existing manifest is preserved verbatim — this function never
163
- * overwrites a populated manifest. The seed shape matches the
164
- * kernel's auto-create exactly, so a pre-warm and an
165
- * auto-provisioned bucket are byte-identical.
166
- *
167
- * @example
168
- * ```ts
169
- * import { LocalFsStorage, ensureTable } from "@gusto/baerly-storage/dev";
170
- *
171
- * const storage = new LocalFsStorage({ root: "./.baerly-data" });
172
- * // Pre-warm so the first request doesn't pay the bootstrap PUT.
173
- * await ensureTable(storage, { app: "helpdesk", tenant: "demo", table: "tickets" });
174
- * // …then `baerlyNode({ config, storage, verifier })`.
175
- * ```
176
- */
177
- const ensureTable = async (storage, args) => {
178
- const key = `app/${args.app}/tenant/${args.tenant}/manifests/${args.table}/current.json`;
179
- try {
180
- await createCurrentJson(storage, key, {
181
- schema_version: 3,
182
- snapshot: null,
183
- tail_hint: 0,
184
- log_seq_start: 0,
185
- writer_fence: {
186
- epoch: 0,
187
- owner: "",
188
- claimed_at: ""
189
- },
190
- snapshot_bytes: 0,
191
- snapshot_rows: 0
192
- });
193
- } catch (error) {
194
- if (error instanceof BaerlyError && error.code === "Conflict") return;
195
- throw error;
196
- }
197
- };
198
- //#endregion
199
- //#region packages/dev/src/local-fs.ts
200
- /**
201
- * Reserved prefix for the in-directory create-if-absent temp (see `put`).
202
- * `walk`/`list` skip it; it is internal/transient and never a real key.
203
- */
204
- const TEMP_PREFIX = ".baerly-tmp-";
205
- const utf8Encoder = new TextEncoder();
206
- /**
207
- * Compare two keys by their UTF-8 byte sequences — the order S3 and R2
208
- * use for `list`. JS's default string sort compares UTF-16 code units,
209
- * which diverges from UTF-8 byte order for supplementary-plane
210
- * characters; using this keeps `list` ordering faithful to the real
211
- * adapters. (All kernel keys are ASCII base-32, where both orders
212
- * coincide.)
213
- */
214
- const compareKeysUtf8 = (a, b) => {
215
- const ba = utf8Encoder.encode(a);
216
- const bb = utf8Encoder.encode(b);
217
- const n = Math.min(ba.length, bb.length);
218
- for (let i = 0; i < n; i++) if (ba[i] !== bb[i]) return ba[i] - bb[i];
219
- return ba.length - bb.length;
220
- };
221
- /**
222
- * `Storage` backed by a directory tree. Keys may contain `/` and map
223
- * to nested directories on disk so `ls`/`cat` work as expected.
224
- *
225
- * ETags are content-addressed: `"<sha-256-hex>"` (the surrounding
226
- * double-quotes match S3's wire format for non-multipart objects).
227
- * Identical bodies share an ETag across runs — the property that
228
- * makes this adapter useful for fixture-based tests.
229
- *
230
- * Writes are atomic via `writeFile(temp) + rename(final)`; readers
231
- * never see a partially-written file.
232
- *
233
- * `ifNoneMatch:"*"` uses a same-dir temp + `link(2)` (atomic exclusive
234
- * create; `EEXIST` ⇒ key exists) so concurrent creates have exactly one
235
- * winner. Same-dir avoids `EXDEV`; temp+`link` over `open(…,"wx")` keeps
236
- * a partially-written new key invisible to a concurrent reader. `ifMatch`
237
- * keeps the `rename` path (in-process TOCTOU only; cross-process
238
- * contention uses the S3 / Minio `If-Match` path).
239
- *
240
- * Node-only — imports `node:fs`, `node:path`, `node:crypto`. Lives in
241
- * `@baerly/dev` because the protocol kernel is pure-modules / no I/O
242
- * and must remain Worker-bundleable.
243
- */
244
- var LocalFsStorage = class {
245
- #root;
246
- constructor(opts) {
247
- this.#root = resolve(opts.root);
248
- }
249
- async get(key, opts) {
250
- opts?.signal?.throwIfAborted();
251
- const path = this.#pathFor(key);
252
- let body;
253
- try {
254
- body = await readFile(path);
255
- } catch (error) {
256
- if (isErrnoException(error) && error.code === "ENOENT") return null;
257
- throw new BaerlyError("InvalidResponse", `LocalFsStorage.get(${key}): ${error.message}`, error);
258
- }
259
- const etag = etagOf(body);
260
- if (opts?.ifNoneMatch !== void 0 && opts.ifNoneMatch === etag) return null;
261
- return {
262
- body: toUint8Array(body),
263
- etag
264
- };
265
- }
266
- async put(key, body, opts) {
267
- opts?.signal?.throwIfAborted();
268
- const path = this.#pathFor(key);
269
- const newEtag = etagOf(body);
270
- await mkdir(dirname(path), { recursive: true });
271
- if (opts?.ifNoneMatch === "*") {
272
- const tmp = join(dirname(path), `${TEMP_PREFIX}${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`);
273
- try {
274
- await writeFile(tmp, body);
275
- await link(tmp, path);
276
- } catch (error) {
277
- if (isErrnoException(error) && error.code === "EEXIST") throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifNoneMatch="*" but key exists)`);
278
- throw new BaerlyError("InvalidResponse", `LocalFsStorage.put(${key}): ${error.message}`, error);
279
- } finally {
280
- await rm(tmp, { force: true }).catch(() => {});
281
- }
282
- return {
283
- etag: newEtag,
284
- serverDate: /* @__PURE__ */ new Date()
285
- };
286
- }
287
- if (opts?.ifMatch !== void 0) {
288
- const existing = await readExisting(path);
289
- if (existing === null) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
290
- const currentEtag = etagOf(existing);
291
- if (currentEtag !== opts.ifMatch) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${currentEtag})`);
292
- }
293
- const tmp = join(tmpdir(), `baerly-localfs-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`);
294
- await writeFile(tmp, body);
295
- try {
296
- await rename(tmp, path);
297
- } catch (error) {
298
- await rm(tmp, { force: true }).catch(() => {});
299
- throw new BaerlyError("InvalidResponse", `LocalFsStorage.put(${key}): ${error.message}`, error);
300
- }
301
- return {
302
- etag: newEtag,
303
- serverDate: /* @__PURE__ */ new Date()
304
- };
305
- }
306
- async delete(key, opts) {
307
- opts?.signal?.throwIfAborted();
308
- const path = this.#pathFor(key);
309
- try {
310
- await rm(path);
311
- } catch (error) {
312
- if (isErrnoException(error) && error.code === "ENOENT") return;
313
- throw new BaerlyError("InvalidResponse", `LocalFsStorage.delete(${key}): ${error.message}`, error);
314
- }
315
- }
316
- async *list(prefix, opts) {
317
- opts?.signal?.throwIfAborted();
318
- const startAfter = opts?.startAfter ?? "";
319
- const maxKeys = opts?.maxKeys ?? Infinity;
320
- const keys = [];
321
- await walk(this.#root, keys);
322
- keys.sort(compareKeysUtf8);
323
- let yielded = 0;
324
- for (const key of keys) {
325
- if (!key.startsWith(prefix)) continue;
326
- if (compareKeysUtf8(key, startAfter) <= 0) continue;
327
- if (yielded >= maxKeys) return;
328
- opts?.signal?.throwIfAborted();
329
- yield {
330
- key,
331
- etag: etagOf(await readFile(this.#pathFor(key)))
332
- };
333
- yielded += 1;
334
- }
335
- }
336
- /**
337
- * Map an S3-style key to a filesystem path under `#root`, rejecting
338
- * anything that could escape the root (path traversal, absolute
339
- * paths, empty segments, backslashes). All rejections throw
340
- * `BaerlyError("InvalidConfig", …)`.
341
- */
342
- #pathFor(key) {
343
- assertValidStorageKey(key);
344
- if (key.startsWith("/")) throw new BaerlyError("InvalidConfig", `LocalFsStorage: leading "/" in key: ${key}`);
345
- if (key.includes("\\")) throw new BaerlyError("InvalidConfig", `LocalFsStorage: backslash in key: ${key}`);
346
- const segments = key.split("/");
347
- if (segments.some((s) => s === "" || s === "." || s === "..")) throw new BaerlyError("InvalidConfig", `LocalFsStorage: illegal segment in key: ${key}`);
348
- const path = join(this.#root, ...segments);
349
- if (path !== this.#root && !path.startsWith(this.#root + sep)) throw new BaerlyError("InvalidConfig", `LocalFsStorage: resolved path escapes root: ${key}`);
350
- return path;
351
- }
352
- };
353
- const etagOf = (body) => {
354
- return `"${createHash("sha256").update(body).digest("hex")}"`;
355
- };
356
- const toUint8Array = (buf) => new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
357
- const isErrnoException = (e) => typeof e === "object" && e !== null && "code" in e;
358
- const readExisting = async (path) => {
359
- try {
360
- return await readFile(path);
361
- } catch (error) {
362
- if (isErrnoException(error) && error.code === "ENOENT") return null;
363
- throw error;
364
- }
365
- };
366
- /**
367
- * Recursive directory walk. Yields filesystem-relative paths in
368
- * forward-slash form so callers can use them as S3-style keys
369
- * regardless of the host's path separator.
370
- */
371
- const walk = async (root, out) => {
372
- const stack = [root];
373
- while (stack.length > 0) {
374
- const dir = stack.pop();
375
- let entries;
376
- try {
377
- entries = await readdir(dir, { withFileTypes: true });
378
- } catch (error) {
379
- if (isErrnoException(error) && error.code === "ENOENT") continue;
380
- throw error;
381
- }
382
- for (const entry of entries) {
383
- const full = join(dir, entry.name);
384
- if (entry.isDirectory()) stack.push(full);
385
- else if (entry.isFile() && !entry.name.startsWith(TEMP_PREFIX)) out.push(relative(root, full).split(sep).join(posix.sep));
386
- }
387
- }
388
- };
389
- //#endregion
390
- export { require_picocolors_browser as a, printDevBanner as i, ensureTable as n, renderDevLanding as r, LocalFsStorage as t };
391
-
392
- //# sourceMappingURL=src-DYZ4H1aF.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-DYZ4H1aF.js","names":["#root","#pathFor"],"sources":["../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.browser.js","../packages/dev/src/dev-banner.ts","../packages/dev/src/dev-landing.ts","../packages/dev/src/ensure-table.ts","../packages/dev/src/local-fs.ts"],"sourcesContent":["var x=String;\nvar create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}};\nmodule.exports=create();\nmodule.exports.createColors = create;\n","import { createColors } from \"picocolors\";\n\nexport interface DevBannerHint {\n readonly key: string;\n readonly value: string;\n}\n\nexport interface DevBannerOpts {\n readonly name: string;\n readonly primaryUrl?: { readonly label: string; readonly url: string };\n readonly apiUrl?: { readonly label: string; readonly url: string; readonly note?: string };\n readonly hints?: ReadonlyArray<DevBannerHint>;\n /** Force plain-text output (no color, no `←`). Defaults to !isTTY || CI. */\n readonly plain?: boolean;\n /** Sink. Defaults to process.stderr. */\n readonly write?: (chunk: string) => void;\n}\n\nexport function printDevBanner(opts: DevBannerOpts): void {\n const isPlain =\n opts.plain !== undefined\n ? opts.plain\n : process.env[\"CI\"] !== undefined || !process.stderr.isTTY;\n const write = opts.write ?? ((chunk) => process.stderr.write(chunk));\n const pc = createColors(!isPlain);\n const hints = opts.hints ?? [];\n\n const lines: string[] = [];\n\n if (isPlain) {\n lines.push(`baerly · ${opts.name}`);\n\n if (opts.primaryUrl) {\n lines.push(`${opts.primaryUrl.label}: ${opts.primaryUrl.url}`);\n }\n if (opts.apiUrl) {\n const note = opts.apiUrl.note ? ` (${opts.apiUrl.note})` : \"\";\n lines.push(`${opts.apiUrl.label}: ${opts.apiUrl.url}${note}`);\n }\n for (const hint of hints) {\n lines.push(`${hint.key}: ${hint.value}`);\n }\n write(lines.join(\"\\n\") + \"\\n\");\n } else {\n lines.push(pc.bold(pc.cyan(`▎ baerly · ${opts.name}`)));\n lines.push(\"\");\n\n if (opts.primaryUrl) {\n const marker = ` ${pc.green(\"← open this\")}`;\n lines.push(` ${pc.dim(opts.primaryUrl.label)} → ${opts.primaryUrl.url}${marker}`);\n }\n if (opts.apiUrl) {\n const note = opts.apiUrl.note ? ` ${pc.dim(`(${opts.apiUrl.note})`)}` : \"\";\n lines.push(` ${pc.dim(opts.apiUrl.label)} → ${opts.apiUrl.url}${note}`);\n }\n if ((opts.primaryUrl || opts.apiUrl) && hints.length > 0) {\n lines.push(\"\");\n }\n if (hints.length > 0) {\n const maxKeyLen = Math.max(...hints.map((h) => h.key.length));\n for (const hint of hints) {\n lines.push(` ${pc.dim(hint.key.padEnd(maxKeyLen))} ${hint.value}`);\n }\n }\n lines.push(\"\");\n write(lines.join(\"\\n\"));\n }\n}\n","/**\n * Dev landing page for the API root (`GET /`).\n *\n * The HTTP surface is API-only: every path outside `/v1/*`\n * returns the {@link HttpErrorEnvelope} 404 shape. That's correct for\n * production but confusing in local dev — a user who clicks the\n * `http://localhost:3000` link in their terminal sees a JSON 404 and\n * assumes the server is broken.\n *\n * Adapters that wire the {@link DevLandingOptions} opt-in surface a\n * small HTML page on `GET /` instead: app label, a clickable link to\n * the UI, a `/v1/healthz` probe link, and a note that `/v1/c/*` is\n * auth-gated. `GET /favicon.ico` answers 204 so browsers don't pin a\n * second JSON 404 next to the landing page.\n *\n * Production deployments leave the option unset; the 404 falls\n * through to the existing envelope.\n */\n\n/** Options for {@link renderDevLanding}. */\nexport interface DevLandingOptions {\n /** Bucket-prefix / app name (typically passed through from the adapter's `app` option). */\n readonly app: string;\n /** URL of the human-facing UI (e.g., `\"http://localhost:5173\"`). */\n readonly uiUrl: string;\n}\n\n/**\n * Render the dev landing page HTML. Dependency-free; system fonts\n * only; no JS. All substitutions are HTML-escaped to keep the page\n * inert even when `app` / `uiUrl` come from env vars.\n */\nexport const renderDevLanding = (opts: DevLandingOptions): string => {\n const label = escapeHtml(opts.app);\n const app = escapeHtml(opts.app);\n const uiUrl = escapeHtml(opts.uiUrl);\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>${label} — baerly api</title>\n<style>\n body { font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; max-width: 40rem; margin: 3rem auto; padding: 0 1.5rem; color: #222; line-height: 1.5; }\n h1 { font-size: 1.25rem; margin: 0 0 0.25rem; }\n p.tag { color: #666; margin: 0 0 1.5rem; font-size: 0.9rem; }\n a { color: #06c; }\n ul { padding-left: 1.25rem; }\n li { margin: 0.25rem 0; }\n code { background: #f3f3f3; padding: 0.1em 0.35em; border-radius: 3px; font-size: 0.9em; }\n</style>\n</head>\n<body>\n<h1>${label}</h1>\n<p class=\"tag\">baerly api server · app <code>${app}</code></p>\n<p>This is the API server. The UI lives at <a href=\"${uiUrl}\">${uiUrl}</a>.</p>\n<ul>\n <li>Open the UI: <a href=\"${uiUrl}\">${uiUrl}</a></li>\n <li>Health probe: <a href=\"/v1/healthz\">/v1/healthz</a></li>\n <li>CRUD routes under <code>/v1/c/*</code> require an auth header and aren't clickable from here.</li>\n</ul>\n</body>\n</html>\n`;\n};\n\nconst escapeHtml = (s: string): string =>\n s.replace(/[&<>\"']/g, (c) => {\n switch (c) {\n case \"&\": {\n return \"&amp;\";\n }\n case \"<\": {\n return \"&lt;\";\n }\n case \">\": {\n return \"&gt;\";\n }\n case '\"': {\n return \"&quot;\";\n }\n default: {\n return \"&#39;\";\n }\n }\n });\n","import {\n BaerlyError,\n CURRENT_JSON_SCHEMA_VERSION,\n createCurrentJson,\n type Storage,\n} from \"@baerly/protocol\";\n\n/**\n * Optional pre-warm: idempotently create the `current.json` manifest\n * for a single `(app, tenant, table)` triple. The kernel auto-creates\n * this manifest on the first commit anyway (see `Db.create` and\n * `Writer.commit`), so calling `ensureTable` is **not required** for\n * correctness — it's a one-Class-A-PUT optimization for callers that\n * want the manifest in place before the first request lands (seed\n * scripts, deploy-time provisioning, CI fixtures that snapshot the\n * bucket between phases, etc.).\n *\n * Wraps {@link createCurrentJson} with the canonical key shape\n * (`app/<app>/tenant/<tenant>/manifests/<table>/current.json`) and\n * swallows `BaerlyError{code:\"Conflict\"}` so re-runs are safe. An\n * existing manifest is preserved verbatim — this function never\n * overwrites a populated manifest. The seed shape matches the\n * kernel's auto-create exactly, so a pre-warm and an\n * auto-provisioned bucket are byte-identical.\n *\n * @example\n * ```ts\n * import { LocalFsStorage, ensureTable } from \"@gusto/baerly-storage/dev\";\n *\n * const storage = new LocalFsStorage({ root: \"./.baerly-data\" });\n * // Pre-warm so the first request doesn't pay the bootstrap PUT.\n * await ensureTable(storage, { app: \"helpdesk\", tenant: \"demo\", table: \"tickets\" });\n * // …then `baerlyNode({ config, storage, verifier })`.\n * ```\n */\nexport const ensureTable = async (\n storage: Storage,\n args: { app: string; tenant: string; table: string },\n): Promise<void> => {\n const key = `app/${args.app}/tenant/${args.tenant}/manifests/${args.table}/current.json`;\n try {\n await createCurrentJson(storage, key, {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n tail_hint: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" },\n snapshot_bytes: 0,\n snapshot_rows: 0,\n });\n } catch (error) {\n if (error instanceof BaerlyError && error.code === \"Conflict\") {\n return;\n }\n throw error;\n }\n};\n","import { createHash } from \"node:crypto\";\nimport { link, mkdir, readdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, posix, relative, resolve, sep } from \"node:path\";\nimport {\n BaerlyError,\n assertValidStorageKey,\n type Storage,\n type StorageGetOptions,\n type StorageGetResult,\n type StorageListEntry,\n type StoragePutOptions,\n type StoragePutResult,\n} from \"@baerly/protocol\";\n\n/**\n * Reserved prefix for the in-directory create-if-absent temp (see `put`).\n * `walk`/`list` skip it; it is internal/transient and never a real key.\n */\nconst TEMP_PREFIX = \".baerly-tmp-\";\n\nexport interface LocalFsStorageOptions {\n /** Root directory; treated as \"the bucket\". */\n root: string;\n}\n\nconst utf8Encoder = new TextEncoder();\n\n/**\n * Compare two keys by their UTF-8 byte sequences — the order S3 and R2\n * use for `list`. JS's default string sort compares UTF-16 code units,\n * which diverges from UTF-8 byte order for supplementary-plane\n * characters; using this keeps `list` ordering faithful to the real\n * adapters. (All kernel keys are ASCII base-32, where both orders\n * coincide.)\n */\nconst compareKeysUtf8 = (a: string, b: string): number => {\n const ba = utf8Encoder.encode(a);\n const bb = utf8Encoder.encode(b);\n const n = Math.min(ba.length, bb.length);\n for (let i = 0; i < n; i++) {\n if (ba[i] !== bb[i]) {\n return ba[i]! - bb[i]!;\n }\n }\n return ba.length - bb.length;\n};\n\n/**\n * `Storage` backed by a directory tree. Keys may contain `/` and map\n * to nested directories on disk so `ls`/`cat` work as expected.\n *\n * ETags are content-addressed: `\"<sha-256-hex>\"` (the surrounding\n * double-quotes match S3's wire format for non-multipart objects).\n * Identical bodies share an ETag across runs — the property that\n * makes this adapter useful for fixture-based tests.\n *\n * Writes are atomic via `writeFile(temp) + rename(final)`; readers\n * never see a partially-written file.\n *\n * `ifNoneMatch:\"*\"` uses a same-dir temp + `link(2)` (atomic exclusive\n * create; `EEXIST` ⇒ key exists) so concurrent creates have exactly one\n * winner. Same-dir avoids `EXDEV`; temp+`link` over `open(…,\"wx\")` keeps\n * a partially-written new key invisible to a concurrent reader. `ifMatch`\n * keeps the `rename` path (in-process TOCTOU only; cross-process\n * contention uses the S3 / Minio `If-Match` path).\n *\n * Node-only — imports `node:fs`, `node:path`, `node:crypto`. Lives in\n * `@baerly/dev` because the protocol kernel is pure-modules / no I/O\n * and must remain Worker-bundleable.\n */\nexport class LocalFsStorage implements Storage {\n readonly #root: string;\n\n constructor(opts: LocalFsStorageOptions) {\n this.#root = resolve(opts.root);\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n let body: Buffer;\n try {\n body = await readFile(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return null;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.get(${key}): ${(error as Error).message}`,\n error,\n );\n }\n const etag = etagOf(body);\n if (opts?.ifNoneMatch !== undefined && opts.ifNoneMatch === etag) {\n // 304 Not Modified — caller's cached copy is current.\n return null;\n }\n return { body: toUint8Array(body), etag };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n const newEtag = etagOf(body);\n\n await mkdir(dirname(path), { recursive: true });\n\n if (opts?.ifNoneMatch === \"*\") {\n // Atomic exclusive create via link(2) — see class JSDoc.\n const tmp = join(\n dirname(path),\n `${TEMP_PREFIX}${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n );\n try {\n await writeFile(tmp, body);\n await link(tmp, path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"EEXIST\") {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifNoneMatch=\"*\" but key exists)`,\n );\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.put(${key}): ${(error as Error).message}`,\n error,\n );\n } finally {\n // Best-effort cleanup — a failed write may leave a partial temp,\n // and a cleanup failure must not mask a Conflict thrown above.\n await rm(tmp, { force: true }).catch(() => {});\n }\n return { etag: newEtag, serverDate: new Date() };\n }\n\n if (opts?.ifMatch !== undefined) {\n // TOCTOU within a process — fine. Cross-process callers should\n // not rely on these guards (see class JSDoc).\n const existing = await readExisting(path);\n if (existing === null) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n const currentEtag = etagOf(existing);\n if (currentEtag !== opts.ifMatch) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${currentEtag})`,\n );\n }\n }\n\n // Unconditional PUT (or ifMatch already verified above).\n // Write to a unique temp path then rename for atomicity. Temp lives\n // in `os.tmpdir()` so a half-written file never appears under the\n // bucket root where `list` might see it. PID + timestamp + random\n // tail makes the name unique across concurrent writers in the same\n // process.\n const tmp = join(\n tmpdir(),\n `baerly-localfs-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n );\n await writeFile(tmp, body);\n try {\n await rename(tmp, path);\n } catch (error) {\n // Best-effort cleanup of the temp file; swallow any error there\n // so the original failure surfaces unchanged.\n await rm(tmp, { force: true }).catch(() => {});\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.put(${key}): ${(error as Error).message}`,\n error,\n );\n }\n return { etag: newEtag, serverDate: new Date() };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n try {\n await rm(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return;\n } // idempotent\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.delete(${key}): ${(error as Error).message}`,\n error,\n );\n }\n }\n\n async *list(\n prefix: string,\n opts?: {\n startAfter?: string;\n maxKeys?: number;\n signal?: AbortSignal;\n },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n const startAfter = opts?.startAfter ?? \"\";\n const maxKeys = opts?.maxKeys ?? Infinity;\n const keys: string[] = [];\n await walk(this.#root, keys);\n keys.sort(compareKeysUtf8);\n let yielded = 0;\n for (const key of keys) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n if (compareKeysUtf8(key, startAfter) <= 0) {\n continue;\n }\n if (yielded >= maxKeys) {\n return;\n }\n opts?.signal?.throwIfAborted();\n const buf = await readFile(this.#pathFor(key));\n yield { key, etag: etagOf(buf) };\n yielded += 1;\n }\n }\n\n /**\n * Map an S3-style key to a filesystem path under `#root`, rejecting\n * anything that could escape the root (path traversal, absolute\n * paths, empty segments, backslashes). All rejections throw\n * `BaerlyError(\"InvalidConfig\", …)`.\n */\n #pathFor(key: string): string {\n // Shared Storage key grammar (non-empty, no `.`/`..` segments); the\n // FS-specific guards below add traversal/backslash/empty-segment checks.\n assertValidStorageKey(key);\n if (key.startsWith(\"/\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: leading \"/\" in key: ${key}`);\n }\n if (key.includes(\"\\\\\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: backslash in key: ${key}`);\n }\n const segments = key.split(\"/\");\n if (segments.some((s) => s === \"\" || s === \".\" || s === \"..\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: illegal segment in key: ${key}`);\n }\n const path = join(this.#root, ...segments);\n if (path !== this.#root && !path.startsWith(this.#root + sep)) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: resolved path escapes root: ${key}`);\n }\n return path;\n }\n}\n\nconst etagOf = (body: Uint8Array): string => {\n const h = createHash(\"sha256\").update(body).digest(\"hex\");\n return `\"${h}\"`;\n};\n\nconst toUint8Array = (buf: Buffer): Uint8Array =>\n new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n\nconst isErrnoException = (e: unknown): e is NodeJS.ErrnoException =>\n typeof e === \"object\" && e !== null && \"code\" in e;\n\nconst readExisting = async (path: string): Promise<Buffer | null> => {\n try {\n return await readFile(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n};\n\n/**\n * Recursive directory walk. Yields filesystem-relative paths in\n * forward-slash form so callers can use them as S3-style keys\n * regardless of the host's path separator.\n */\nconst walk = async (root: string, out: string[]): Promise<void> => {\n const stack: string[] = [root];\n while (stack.length > 0) {\n const dir = stack.pop()!;\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n continue;\n }\n throw error;\n }\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n stack.push(full);\n } else if (entry.isFile() && !entry.name.startsWith(TEMP_PREFIX)) {\n // Skip the transient create-if-absent temps (see TEMP_PREFIX) so a\n // concurrent list during a create never surfaces a half-linked key.\n out.push(relative(root, full).split(sep).join(posix.sep));\n }\n }\n }\n};\n"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;;CAAA,IAAI,IAAE;CACN,IAAI,SAAO,WAAW;EAAC,OAAO;GAAC,kBAAiB;GAAM,OAAM;GAAE,MAAK;GAAE,KAAI;GAAE,QAAO;GAAE,WAAU;GAAE,SAAQ;GAAE,QAAO;GAAE,eAAc;GAAE,OAAM;GAAE,KAAI;GAAE,OAAM;GAAE,QAAO;GAAE,MAAK;GAAE,SAAQ;GAAE,MAAK;GAAE,OAAM;GAAE,MAAK;GAAE,SAAQ;GAAE,OAAM;GAAE,SAAQ;GAAE,UAAS;GAAE,QAAO;GAAE,WAAU;GAAE,QAAO;GAAE,SAAQ;GAAE,aAAY;GAAE,WAAU;GAAE,aAAY;GAAE,cAAa;GAAE,YAAW;GAAE,eAAc;GAAE,YAAW;GAAE,aAAY;GAAE,eAAc;GAAE,aAAY;GAAE,eAAc;GAAE,gBAAe;GAAE,cAAa;GAAE,iBAAgB;GAAE,cAAa;GAAE,eAAc;EAAC;CAAC;CACtgB,OAAO,UAAQ,OAAO;CACtB,OAAO,QAAQ,eAAe;;;;;ACe9B,SAAgB,eAAe,MAA2B;CACxD,MAAM,UACJ,KAAK,UAAU,KAAA,IACX,KAAK,QACL,QAAQ,IAAI,UAAU,KAAA,KAAa,CAAC,QAAQ,OAAO;CACzD,MAAM,QAAQ,KAAK,WAAW,UAAU,QAAQ,OAAO,MAAM,KAAK;CAClE,MAAM,MAAA,GAAA,0BAAA,aAAA,CAAkB,CAAC,OAAO;CAChC,MAAM,QAAQ,KAAK,SAAS,CAAC;CAE7B,MAAM,QAAkB,CAAC;CAEzB,IAAI,SAAS;EACX,MAAM,KAAK,YAAY,KAAK,MAAM;EAElC,IAAI,KAAK,YACP,MAAM,KAAK,GAAG,KAAK,WAAW,MAAM,IAAI,KAAK,WAAW,K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