@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.
- package/README.md +47 -124
- package/dist/API.md +161 -512
- package/dist/CHANGELOG.md +1137 -378
- package/dist/RECIPES.md +398 -80
- package/dist/THIRD-PARTY-LICENSES.txt +5 -26
- package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
- package/dist/app-config.d.ts +31 -1
- package/dist/app-config.js +1 -2
- package/dist/app-config.js.map +1 -1
- package/dist/auth.d.ts +33 -28
- package/dist/auth.js +549 -985
- package/dist/auth.js.map +1 -1
- package/dist/baerly.js +130 -138
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +97 -22
- package/dist/capacity-warning-header-BlVopyiI.js +16 -0
- package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
- package/dist/{client-ypCm3zjt.d.ts → client-CHQTXpef.d.ts} +121 -36
- package/dist/client-react.d.ts +67 -20
- package/dist/client-react.js +240 -54
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +5 -4
- package/dist/client.js +51 -16
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-wrVYf4bb.js → cloudflare-CKHYXccw.js} +61 -82
- package/dist/cloudflare-CKHYXccw.js.map +1 -0
- package/dist/cloudflare.d.ts +106 -71
- package/dist/cloudflare.js +334 -271
- package/dist/cloudflare.js.map +1 -1
- package/dist/code-resolution-CL_7L0wS.js +22 -0
- package/dist/code-resolution-CL_7L0wS.js.map +1 -0
- package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
- package/dist/config-DEzInG6M.js +4035 -0
- package/dist/config-DEzInG6M.js.map +1 -0
- package/dist/constants-D3GSH3tc.js +469 -0
- package/dist/constants-D3GSH3tc.js.map +1 -0
- package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
- package/dist/context-rlpSnHFA.js.map +1 -0
- package/dist/cost-B52llVDx.js +330 -0
- package/dist/cost-B52llVDx.js.map +1 -0
- package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
- package/dist/current-json-CC6lE4Aj.js.map +1 -0
- package/dist/db-plFUNTSF.d.ts +130 -0
- package/dist/db-read-seams-BSs0m1z1.js +3261 -0
- package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
- package/dist/{deploy-Di_Q01qx.js → deploy-Obj4nE-Z.js} +10 -14
- package/dist/deploy-Obj4nE-Z.js.map +1 -0
- package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
- package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
- package/dist/dev-landing-CD-si4dW.js +50 -0
- package/dist/dev-landing-CD-si4dW.js.map +1 -0
- package/dist/dev-vite.d.ts +9 -14
- package/dist/dev-vite.js +11 -10
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +3 -2
- package/dist/dev.js +2 -1
- package/dist/doctor-BA0i-YAN.js +270 -0
- package/dist/doctor-BA0i-YAN.js.map +1 -0
- package/dist/dump-D1vX8ozg.js +133 -0
- package/dist/dump-D1vX8ozg.js.map +1 -0
- package/dist/errors-7Rk1HGCE.js +160 -0
- package/dist/errors-7Rk1HGCE.js.map +1 -0
- package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
- package/dist/export-BVL2EvYE.js.map +1 -0
- package/dist/fsck-BWkPgov4.js +145 -0
- package/dist/fsck-BWkPgov4.js.map +1 -0
- package/dist/{gcs-admin-Bx6xSNJj.d.ts → gcs-admin-Dso1HWQj.d.ts} +18 -14
- package/dist/gcs.d.ts +19 -7
- package/dist/gcs.js +1 -2
- package/dist/{goog4-signer-Z7KnJ1su.js → goog4-signer-CeLIABoE.js} +102 -92
- package/dist/goog4-signer-CeLIABoE.js.map +1 -0
- package/dist/{http-7zT29K3P.js → http-Z5rZyYMX.js} +898 -271
- package/dist/http-Z5rZyYMX.js.map +1 -0
- package/dist/http-transport-DNUM8kU-.js +1299 -0
- package/dist/http-transport-DNUM8kU-.js.map +1 -0
- package/dist/http.d.ts +366 -294
- package/dist/http.js +2 -2
- package/dist/index-JJrIu1pO.d.ts +135 -0
- package/dist/index-LEgHN0qJ.d.ts +50 -0
- package/dist/{index-DP3ClvcA.d.ts → index-RiEYj8t0.d.ts} +291 -78
- package/dist/index.d.ts +27 -6
- package/dist/index.js +3 -5
- package/dist/inspect-BTsVYZKd.js +196 -0
- package/dist/inspect-BTsVYZKd.js.map +1 -0
- package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
- package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
- package/dist/ledger-Dj_bGgo0.js +192 -0
- package/dist/ledger-Dj_bGgo0.js.map +1 -0
- package/dist/legacy-names-DgZBtgOh.js +47 -0
- package/dist/legacy-names-DgZBtgOh.js.map +1 -0
- package/dist/log-C9W15Dfo.d.ts +94 -0
- package/dist/log-tail-DWJbneBF.js +142 -0
- package/dist/log-tail-DWJbneBF.js.map +1 -0
- package/dist/log-walk-C-vA-WGJ.js +111 -0
- package/dist/log-walk-C-vA-WGJ.js.map +1 -0
- package/dist/maintenance-Dd-Yakqj.js +1709 -0
- package/dist/maintenance-Dd-Yakqj.js.map +1 -0
- package/dist/maintenance-DevB6z4e.js +2237 -0
- package/dist/maintenance-DevB6z4e.js.map +1 -0
- package/dist/maintenance.d.ts +100 -3
- package/dist/maintenance.js +1 -3
- package/dist/node.d.ts +119 -92
- package/dist/node.js +3 -3
- package/dist/{observability-Ch-VQJyE.js → observability-C-ISCCLE.js} +1247 -326
- package/dist/observability-C-ISCCLE.js.map +1 -0
- package/dist/observability.d.ts +27 -3
- package/dist/observability.js +3 -3
- package/dist/path-segment-DBXG26PW.js +363 -0
- package/dist/path-segment-DBXG26PW.js.map +1 -0
- package/dist/{plan-C4qgiXSg.js → plan-BvQbaNMe.js} +19 -11
- package/dist/plan-BvQbaNMe.js.map +1 -0
- package/dist/request-CRWiTrza.js +272 -0
- package/dist/request-CRWiTrza.js.map +1 -0
- package/dist/restore-U6Im8V1V.js +1467 -0
- package/dist/restore-U6Im8V1V.js.map +1 -0
- package/dist/retry-OBtLB2GC.js +126 -0
- package/dist/retry-OBtLB2GC.js.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
- package/dist/{runtime-spec--LykAdl1.js → runtime-spec-B5mg3pHF.js} +189 -28
- package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
- package/dist/{s3-http-DD5gDc7t.d.ts → s3-http-DBC_wiCL.d.ts} +14 -8
- package/dist/s3.d.ts +20 -7
- package/dist/s3.js +4 -5
- package/dist/s3.js.map +1 -1
- package/dist/{sha256-CqcKTjw9.js → sha256-4FfGQNPw.js} +9 -9
- package/dist/sha256-4FfGQNPw.js.map +1 -0
- package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
- package/dist/shared-secret-Vkur-8r0.js.map +1 -0
- package/dist/{aws4fetch.esm-CXE5ZbAa.js → sigv4-sign-5IUflUD_.js} +143 -96
- package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
- package/dist/snapshot-CknzkDM0.js +148 -0
- package/dist/snapshot-CknzkDM0.js.map +1 -0
- package/dist/{src-BMFfDUI2.js → src-Actga-bO.js} +949 -363
- package/dist/src-Actga-bO.js.map +1 -0
- package/dist/src-D0MQfvOp.js +812 -0
- package/dist/src-D0MQfvOp.js.map +1 -0
- package/dist/src-Dr9uo3dc.js +501 -0
- package/dist/src-Dr9uo3dc.js.map +1 -0
- package/dist/{subcommand-BV68pqwJ.js → subcommand-BLoF66dG.js} +89 -16
- package/dist/subcommand-BLoF66dG.js.map +1 -0
- package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
- package/dist/time-DRxTP9iv.js.map +1 -0
- package/dist/types-suVbsEWS.d.ts +116 -0
- package/dist/{usage-BMZR8o6U.js → usage-CPzVhrQr.js} +40 -45
- package/dist/usage-CPzVhrQr.js.map +1 -0
- package/dist/uuid-BuT_c404.js +333 -0
- package/dist/uuid-BuT_c404.js.map +1 -0
- package/dist/verifier-Bmlmndzo.d.ts +95 -0
- package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
- package/dist/wire-DndvKU-K.js.map +1 -0
- package/package.json +90 -69
- package/dist/aws4fetch.esm-CXE5ZbAa.js.map +0 -1
- package/dist/bytes-BXdamO3L.js +0 -11
- package/dist/bytes-BXdamO3L.js.map +0 -1
- package/dist/cloudflare-wrVYf4bb.js.map +0 -1
- package/dist/config-B6nTy8e2.js +0 -3095
- package/dist/config-B6nTy8e2.js.map +0 -1
- package/dist/constants-CfeMWQWk.js +0 -222
- package/dist/constants-CfeMWQWk.js.map +0 -1
- package/dist/context-DRZ3tZ5l.js.map +0 -1
- package/dist/cost-_SE_SVgZ.js +0 -203
- package/dist/cost-_SE_SVgZ.js.map +0 -1
- package/dist/current-json-C6nhPOm1.js.map +0 -1
- package/dist/db-DjjthkTi.d.ts +0 -254
- package/dist/deploy-Di_Q01qx.js.map +0 -1
- package/dist/doctor-RWVRpvat.js +0 -102
- package/dist/doctor-RWVRpvat.js.map +0 -1
- package/dist/dump-m2vEYDNY.js +0 -94
- package/dist/dump-m2vEYDNY.js.map +0 -1
- package/dist/errors-Dfa3p78c.js +0 -78
- package/dist/errors-Dfa3p78c.js.map +0 -1
- package/dist/export-DenKwEQu.js +0 -401
- package/dist/export-DenKwEQu.js.map +0 -1
- package/dist/fsck-2Vq-7-e2.js +0 -279
- package/dist/fsck-2Vq-7-e2.js.map +0 -1
- package/dist/goog4-signer-Z7KnJ1su.js.map +0 -1
- package/dist/http-7zT29K3P.js.map +0 -1
- package/dist/http-transport-BTgVCY5r.js +0 -1250
- package/dist/http-transport-BTgVCY5r.js.map +0 -1
- package/dist/index-BHz92Acj.d.ts +0 -162
- package/dist/index-CEZKQsKt.d.ts +0 -1113
- package/dist/index-uE-w2dgj.d.ts +0 -115
- package/dist/indexes-Dn9hbGQG.d.ts +0 -22
- package/dist/inspect-BpYbH1DM.js +0 -133
- package/dist/inspect-BpYbH1DM.js.map +0 -1
- package/dist/log-tail-QWU4wlu-.js +0 -514
- package/dist/log-tail-QWU4wlu-.js.map +0 -1
- package/dist/maintenance-BGHGt2Yg.d.ts +0 -537
- package/dist/maintenance-DULFcpd1.js +0 -2144
- package/dist/maintenance-DULFcpd1.js.map +0 -1
- package/dist/maintenance-fEi-UZ2o.js +0 -1412
- package/dist/maintenance-fEi-UZ2o.js.map +0 -1
- package/dist/normalize-rjnZLwS4.js +0 -133
- package/dist/normalize-rjnZLwS4.js.map +0 -1
- package/dist/observability-Ch-VQJyE.js.map +0 -1
- package/dist/plan-C4qgiXSg.js.map +0 -1
- package/dist/query-C43r-6ib.js +0 -1773
- package/dist/query-C43r-6ib.js.map +0 -1
- package/dist/rebuild-index-BH1dc1p6.js +0 -81
- package/dist/rebuild-index-BH1dc1p6.js.map +0 -1
- package/dist/request-u0M51mhJ.js +0 -72
- package/dist/request-u0M51mhJ.js.map +0 -1
- package/dist/restore-D0VYWzfP.js +0 -778
- package/dist/restore-D0VYWzfP.js.map +0 -1
- package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
- package/dist/runtime-spec--LykAdl1.js.map +0 -1
- package/dist/sha256-CqcKTjw9.js.map +0 -1
- package/dist/shared-secret-DgEicd3x.js.map +0 -1
- package/dist/src-BMFfDUI2.js.map +0 -1
- package/dist/src-DYZ4H1aF.js +0 -392
- package/dist/src-DYZ4H1aF.js.map +0 -1
- package/dist/src-DvbTEya2.js +0 -536
- package/dist/src-DvbTEya2.js.map +0 -1
- package/dist/subcommand-BV68pqwJ.js.map +0 -1
- package/dist/time-DUqvFMHq.js.map +0 -1
- package/dist/usage-BMZR8o6U.js.map +0 -1
- package/dist/validate-DtljsCh1.js.map +0 -1
- package/dist/wire-izfGZDvr.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-D0MQfvOp.js","names":["utf8Encoder"],"sources":["../packages/dev/src/key-lock.ts","../packages/dev/src/local-fs-key-codec.ts","../packages/dev/src/local-fs.ts","../packages/dev/src/dev-banner.ts","../packages/dev/src/ensure-table.ts"],"sourcesContent":["/**\n * A keyed async mutex: serializes async critical sections that share a\n * lock key, while letting different keys run concurrently.\n *\n * Deliberately NOT re-exported from `./index.ts` — this is an internal\n * implementation detail of `LocalFsStorage`, not part of the published\n * `@gusto/baerly-storage/dev` surface.\n */\n\ninterface KeyLock {\n /** Resolves when the currently-running holder releases. */\n tail: Promise<void>;\n /** Holders currently running or queued; the entry is evicted at zero. */\n waiters: number;\n}\n\n/**\n * Live locks, keyed by caller-supplied string.\n *\n * Module-level rather than per-owner on purpose. `LocalFsStorage` is\n * constructed freely — `localFsStorage()` mints a fresh instance on every\n * call over the same default root, and the randomized cascade builds N\n * instances over one directory specifically to make them contend — so a\n * lock map hanging off the instance would serialize nothing in exactly the\n * cases that need it. Callers key on the resolved root plus the storage\n * key, which is the real identity of the thing being mutated.\n */\nconst locks = new Map<string, KeyLock>();\n\n/**\n * Run `fn` with exclusive access to `lockKey`, in FIFO order among\n * contenders. Concurrent calls on *different* keys are unaffected.\n *\n * A rejecting `fn` releases the lock like any other completion and the\n * rejection propagates to its own caller only — one failed critical\n * section must not wedge the key or poison the next holder.\n *\n * Scope: one loaded copy of this module, since `locks` is module-level.\n * That is one process in every normal setup. It says nothing about other\n * processes, which need a lock file, a lease, or server-side CAS.\n *\n * `fn` must not itself call `withKeyLock` on the same key — the inner\n * call would wait on the outer call's release and self-deadlock. Nothing\n * in this package does; only one lock is ever held at a time, so there is\n * no lock-ordering cycle either.\n */\nexport const withKeyLock = async <T>(lockKey: string, fn: () => Promise<T>): Promise<T> => {\n const lock = locks.getOrInsertComputed(lockKey, () => ({ tail: Promise.resolve(), waiters: 0 }));\n lock.waiters += 1;\n\n // Take a ticket: wait on the previous holder's release, and publish our\n // own release as what the next arrival waits on. Both happen before any\n // `await`, so tickets are handed out in call order with no interleaving.\n const predecessor = lock.tail;\n let release!: () => void;\n lock.tail = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n await predecessor;\n try {\n return await fn();\n } finally {\n release();\n lock.waiters -= 1;\n // Evict once the last contender drains, so the map is bounded by\n // in-flight writers rather than growing with the keyspace — a\n // long-lived dev server would otherwise retain an entry per key ever\n // written. `waiters` is incremented synchronously at registration and\n // decremented only here, so zero really does mean nobody is left. The\n // identity check is belt-and-braces: there is no `await` between the\n // release above and this line, so it cannot currently be false.\n if (lock.waiters === 0 && locks.get(lockKey) === lock) {\n locks.delete(lockKey);\n }\n }\n};\n\n/** Test-only: number of live lock entries. Pins the eviction path. */\nexport const keyLockCount = (): number => locks.size;\n","import { BaerlyError } from \"@baerly/protocol\";\n\n/**\n * On-disk encoding of `Storage` keys for `LocalFsStorage`.\n *\n * Keys are byte-exact everywhere else (S3, R2, `MemoryStorage`), but a\n * filesystem may fold case and Unicode normalization (default macOS APFS\n * does both), which would merge `A`/`a` or NFC/NFD `é` onto one file. So\n * each `/`-segment is escaped into an alphabet that every case fold and\n * every normalization form leaves unchanged:\n *\n * - `a-z`, `0-9`, `-`, `_` stay literal, and so does `.` except where it\n * would start an on-disk name.\n * - Every other UTF-8 byte becomes `%` plus two lowercase hex digits:\n * `A` → `%41`, `é` (NFC) → `%c3%a9`, `é` (NFD) → `e%cc%81`.\n *\n * Decoding the encoding returns the original key, so distinct keys get\n * distinct names, and folding those names changes nothing. Kernel-written\n * segments (`log/<seq>`, `current.json`, base-32 index values, UUIDv7\n * ids) are already in the literal set, so they look the same on disk.\n * The exception is the snapshot level segment `L9`, stored as `%4c9`.\n *\n * No on-disk name ever starts with `.`, which leaves every dot-prefixed\n * name (staging temps, the format marker, a stray `.DS_Store`) private to\n * the adapter.\n *\n * **`NAME_MAX`.** Escaping can triple a segment, and filenames cap at 255\n * bytes on APFS and ext4. An encoded segment longer than that is split\n * into directory components of at most {@link MAX_PART_BYTES} bytes, each\n * but the last ending in {@link CONTINUATION}. `~` is always escaped by\n * the encoding, so a trailing `~` can only mean \"continued\". Splits fall\n * only between tokens (a literal byte or a `%xx` triplet).\n *\n * **Alternatives that fail.** Refusing a folding filesystem at startup\n * breaks zero-config dev on default macOS. A sidecar key map or hashed\n * filenames breaks the atomic single-file `link(2)` create and readable\n * names. Lowercase-only ids would bend the public `_id` grammar to suit\n * one adapter.\n */\n\n/** Filename limit on APFS and ext4. */\nexport const NAME_MAX_BYTES = 255;\n\n/** Marks a directory component as the head of a split segment. */\nexport const CONTINUATION = \"~\";\n\n/** Longest component that still fits {@link CONTINUATION} under `NAME_MAX`. */\nconst MAX_PART_BYTES = NAME_MAX_BYTES - CONTINUATION.length;\n\nconst utf8Encoder = new TextEncoder();\n// `ignoreBOM: true` keeps a leading U+FEFF: by default `TextDecoder` strips\n// it as a byte-order mark, which would decode `\\uFEFFA` to `A`.\nconst utf8Decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true });\n\n/** Bytes that stay literal: `-` `.` `0-9` `_` `a-z`. `.` is special-cased. */\nconst isLiteralByte = (b: number): boolean =>\n (b >= 0x61 && b <= 0x7a) || // a-z\n (b >= 0x30 && b <= 0x39) || // 0-9\n b === 0x2d || // -\n b === 0x5f || // _\n b === 0x2e; // .\n\nconst DOT = 0x2e;\n\nconst escapeByte = (b: number): string => `%${b.toString(16).padStart(2, \"0\")}`;\n\n/** Tokens of one encoded segment: a literal char or a `%xx` triplet. */\nconst tokenize = (segment: string): string[] => {\n const tokens: string[] = [];\n for (const b of utf8Encoder.encode(segment)) {\n tokens.push(isLiteralByte(b) ? String.fromCharCode(b) : escapeByte(b));\n }\n return tokens;\n};\n\n/**\n * Pack tokens into on-disk components. A component never starts with a\n * literal `.`: such a token is written as `%2e` instead.\n */\nconst pack = (tokens: string[], limit: number): string[] => {\n const parts: string[] = [];\n let current = \"\";\n for (let token of tokens) {\n if (current.length + token.length > limit) {\n parts.push(current);\n current = \"\";\n }\n if (current === \"\" && token === \".\") {\n token = escapeByte(DOT);\n }\n current += token;\n }\n parts.push(current);\n return parts;\n};\n\n/** Encode one non-empty `/`-segment into its on-disk component(s). */\nexport const encodeSegment = (segment: string): string[] => {\n const tokens = tokenize(segment);\n const single = pack(tokens, Number.POSITIVE_INFINITY);\n if (single[0]!.length <= NAME_MAX_BYTES) {\n return single;\n }\n const parts = pack(tokens, MAX_PART_BYTES);\n return parts.map((p, i) => (i < parts.length - 1 ? p + CONTINUATION : p));\n};\n\n/**\n * Encode a key into on-disk path components. The caller has already\n * validated the key's `/`-structure (no empty, `.`, or `..` segment).\n * Rejects a key that is not well-formed UTF-16: `TextEncoder` maps every\n * lone surrogate to U+FFFD, which would make the encoding non-injective.\n */\nexport const encodeKey = (key: string): string[] => {\n if (!key.isWellFormed()) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `LocalFsStorage: key is not well-formed UTF-16 (lone surrogate): ${JSON.stringify(key)}`,\n );\n }\n return key.split(\"/\").flatMap(encodeSegment);\n};\n\nconst HEX = /^[0-9a-f]{2}$/;\n\n/** Decode one component's bytes (continuation marker already stripped). */\nconst decodeBytes = (component: string, out: number[]): boolean => {\n for (let i = 0; i < component.length; i++) {\n const c = component.charCodeAt(i);\n if (c === 0x25) {\n const hex = component.slice(i + 1, i + 3);\n if (!HEX.test(hex)) {\n return false;\n }\n out.push(Number.parseInt(hex, 16));\n i += 2;\n } else if (isLiteralByte(c)) {\n out.push(c);\n } else {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Decode on-disk path components (relative to the root) back to a key.\n * Returns `null` for anything that is not the canonical encoding of some\n * key — a foreign file, a non-canonical escape, a dangling continuation —\n * so the caller can decide how loudly to fail.\n */\nexport const decodeComponents = (components: readonly string[]): string | null => {\n const segments: string[] = [];\n let bytes: number[] = [];\n for (const component of components) {\n const continued = component.endsWith(CONTINUATION);\n const body = continued ? component.slice(0, -CONTINUATION.length) : component;\n if (body === \"\" || !decodeBytes(body, bytes)) {\n return null;\n }\n if (!continued) {\n let segment: string;\n try {\n segment = utf8Decoder.decode(new Uint8Array(bytes));\n } catch {\n return null;\n }\n if (segment === \".\" || segment === \"..\") {\n return null; // not a valid key segment\n }\n segments.push(segment);\n bytes = [];\n }\n }\n if (bytes.length > 0 || segments.length === 0) {\n return null; // ends mid-segment\n }\n const key = segments.join(\"/\");\n // Canonical-form check: exactly one spelling per key, so `list` can\n // never report a key under two names (`%61` vs `a`, `%2E` vs `%2e`,\n // a split in the wrong place).\n let canonical: string[];\n try {\n canonical = encodeKey(key);\n } catch {\n return null;\n }\n if (canonical.length !== components.length || canonical.some((c, i) => c !== components[i])) {\n return null;\n }\n return key;\n};\n","import { createHash } from \"node:crypto\";\nimport {\n link,\n mkdir,\n readdir,\n readFile,\n realpath,\n rename,\n rm,\n stat,\n writeFile,\n} from \"node:fs/promises\";\nimport { dirname, join, 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\";\nimport { withKeyLock } from \"./key-lock.ts\";\nimport { decodeComponents, encodeKey } from \"./local-fs-key-codec.ts\";\n\n/**\n * Prefix for the in-directory staging temps (see `put`). Dot-prefixed, so\n * it can never collide with an encoded key (see `local-fs-key-codec.ts`)\n * and `walk` skips it with every other adapter-private name.\n */\nconst TEMP_PREFIX = \".baerly-tmp-\";\n\n/**\n * Root marker recording the on-disk key encoding. Dot-prefixed, so it is\n * never a key. A directory without it is scanned once for names written\n * by the pre-encoding layout (see `#ensureFormat`).\n */\nconst FORMAT_MARKER = \".baerly-localfs.json\";\n\n/** Version of the key encoding in `local-fs-key-codec.ts`. */\nconst KEY_ENCODING = 1;\n\n/** Legacy paths named in the refusal message before it truncates. */\nconst LEGACY_PATHS_SHOWN = 10;\n\n/**\n * Staging path for a two-phase (write → publish) `put`. Always a sibling\n * of the destination: `rename(2)`/`link(2)` refuse to cross filesystems\n * (`EXDEV`), and the bucket root is routinely on a different volume from\n * `os.tmpdir()`. The leading `.` of `TEMP_PREFIX` is what makes staging\n * in-bucket safe — `walk` skips dot-prefixed names at every depth, and no\n * encoded key starts with one, so a crash before the publish leaves a file\n * invisible to `list` rather than a bogus key.\n *\n * The trade-off that invisibility buys: a temp stranded by a hard crash\n * now sits inside the bucket, and because every enumerator goes through\n * `list`, nothing — not `runGc`, not `admin fsck` — will ever reclaim it.\n * Staging in `os.tmpdir()` at least let the OS reap it. Repeated crashes\n * therefore grow the data directory, and clearing that is a manual\n * `find . -name '.baerly-tmp-*' -delete`. Non-crash failures are cleaned\n * up by `put`'s `finally`.\n */\nconst tempPathFor = (finalPath: string): string =>\n join(\n dirname(finalPath),\n `${TEMP_PREFIX}${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n );\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 * Keys are byte-exact, as on S3 and R2: keys that differ only by case or\n * Unicode normalization are distinct objects even on a filesystem that\n * folds both (default macOS APFS). Each segment is escaped into a\n * fold-invariant alphabet on disk — `A` is stored as `%41`, NFC `é` as\n * `%c3%a9` — while kernel-written segments (lowercase ids, base-32 index\n * values, `current.json`) are stored verbatim. See\n * `local-fs-key-codec.ts`.\n *\n * The root carries a `.baerly-localfs.json` marker naming that encoding.\n * A directory written by an older release, before keys were escaped, is\n * adopted as-is when every name in it already reads the same under the\n * encoding; otherwise every operation refuses with `InvalidConfig`.\n * Such a directory is dev data: move it aside or delete it. Collections\n * worth keeping can be dumped with the older release (`baerly admin\n * dump`, rows only) and restored into a fresh directory (`baerly admin\n * restore`). Data a folding filesystem has already merged is not\n * recoverable.\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. The temp is always a sibling of\n * its destination — `rename(2)`/`link(2)` fail with `EXDEV` across\n * filesystems, and the bucket root is routinely on a different volume\n * from `os.tmpdir()` (see `tempPathFor`).\n *\n * `ifNoneMatch:\"*\"` uses `link(2)` (atomic exclusive create; `EEXIST` ⇒\n * key exists) so concurrent creates have exactly one winner. temp+`link`\n * over `open(…,\"wx\")` keeps a partially-written new key invisible to a\n * concurrent reader.\n *\n * `ifMatch` is a read-compare-write, so it is made atomic by serializing\n * every mutation of a key against every other — see `#lockKey`.\n *\n * Scope of that guarantee, precisely: **one loaded copy of this module**.\n * Within it, concurrent CAS on one key admits exactly one winner and the\n * losers get `WriteConflict`, across any number of `LocalFsStorage` instances\n * whose roots resolve — through symlinks — to the same directory. That is\n * one process in every normal setup, but the lock lives in a module-level\n * map, so a process that somehow loads both this source and the bundled\n * copy has two of them.\n *\n * Across processes it guarantees nothing: two `baerly` CLI runs, or two\n * servers, sharing a directory can both win, because nothing in POSIX\n * makes read-compare-write atomic without a lock file or a lease. That is\n * why this adapter is for single-process dev and self-hosting;\n * horizontally-scaled deploys need S3 / R2, whose server-side conditional\n * write is what the no-lease maintenance fold actually relies on.\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 *\n * ⚠️ **Hard termination and temp files.**\n *\n * Writes stage a sibling `.baerly-tmp-*` file before atomic rename/link.\n * Normal failures clean up the temp in `finally`, but hard termination\n * (`SIGKILL`, OOM, power loss) can strand a temp inside the root directory.\n *\n * These files are hidden from `list`, `gc`, `fsck`, and usage reporting\n * by design—the temp filter applies at every depth.\n *\n * **Manual cleanup procedure:**\n * 1. Stop all writers using the root\n * 2. Run: `find <root> -name '.baerly-tmp-*' -delete`\n *\n * Do not clean while writes are in progress—races with in-flight PUTs\n * can delete a file that a concurrent operation is about to rename.\n */\nexport class LocalFsStorage implements Storage {\n readonly #root: string;\n /** Memoized `realpath` of {@link #root} — see {@link #canonicalRoot}. */\n #realRoot: string | undefined;\n /** Set once the root's key encoding is known to be current. */\n #formatChecked = false;\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 await this.#ensureFormat(false);\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 { cause: error },\n );\n }\n const etag = etagOf(body);\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 await this.#ensureFormat(true);\n // Create the parent before taking the lock, so the `realpath` behind\n // `#lockKey` has a directory to canonicalize.\n await mkdir(dirname(path), { recursive: true });\n // Every mutation of a key is serialized against every other. `ifMatch`\n // is the reason: it reads the current body, compares etags, and only\n // then publishes, with awaited fs ops in between — so unguarded, two\n // callers both read the base etag, both pass the compare, and both\n // publish, yielding N winners for one base version. Guarding the\n // unconditional and create-if-absent paths too is not incidental: an\n // unconditional put landing inside another caller's compare→publish\n // window is the same lost update reached from the other side.\n return withKeyLock(await this.#lockKey(path), () => this.#putSerialized(key, path, body, opts));\n }\n\n async #putSerialized(\n key: string,\n path: string,\n body: Uint8Array,\n opts?: StoragePutOptions,\n ): Promise<StoragePutResult> {\n // Re-check inside the critical section. The pre-lock check happens\n // before an unbounded queue wait, so a signal aborted while this call\n // sat behind other writers to the same key would otherwise be ignored\n // and the write would land anyway.\n opts?.signal?.throwIfAborted();\n const newEtag = etagOf(body);\n\n if (opts?.ifNoneMatch === \"*\") {\n // Atomic exclusive create via link(2) — see class JSDoc.\n const tmp = tempPathFor(path);\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 \"WriteConflict\",\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 { cause: 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 WriteConflict 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 // Read-compare-write. Atomic only because `put` holds this key's\n // lock for the whole of it, publish included — see the class JSDoc\n // for what that does and does not guarantee.\n const existing = await readExisting(path);\n if (existing === null) {\n throw new BaerlyError(\n \"WriteConflict\",\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 \"WriteConflict\",\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). Stage to a\n // sibling temp, then `rename` to publish — the rename is atomic, so a\n // reader sees either the old body or the new one, never a partial\n // write. See `tempPathFor` for why the temp must be a sibling.\n const tmp = tempPathFor(path);\n try {\n await writeFile(tmp, body);\n await rename(tmp, path);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.put(${key}): ${(error as Error).message}`,\n { cause: error },\n );\n } finally {\n // Best-effort cleanup, mirroring the create-if-absent branch. On\n // success the rename already consumed the temp and this is a no-op;\n // on failure it keeps a half-written body from lingering under the\n // bucket root, where only `walk`'s dot-name skip hides it. A\n // cleanup failure must not mask the error thrown above.\n await rm(tmp, { force: true }).catch(() => {});\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 await this.#ensureFormat(false);\n // Same lock as `put`: a delete slipping between an `ifMatch` compare\n // and its publish would resurrect the key from a version the caller\n // was told no longer existed.\n return withKeyLock(await this.#lockKey(path), async () => {\n // Re-check after the queue wait — see `#putSerialized`.\n opts?.signal?.throwIfAborted();\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 { cause: error },\n );\n }\n });\n }\n\n /**\n * Identity of the thing being mutated, for {@link withKeyLock}.\n *\n * Keyed on the *canonical filesystem path*, not on the key and not on\n * `this`. Not on `this` because separate instances over one directory\n * are the common case (`localFsStorage()` mints a fresh one per call),\n * so an instance-scoped lock would serialize nothing where it matters.\n * Not on the root spelling the caller passed, because several spellings\n * of a root can name one directory, and handing an alias its own lock\n * lets the race straight back in:\n *\n * - Symlinks. `resolve()` collapses `.`/`..` but not links, so\n * `/tmp/data` and `/private/tmp/data` — the same directory on every\n * Mac — look like two (measured at 2 winners before it was closed).\n * Hence `realpath`, memoized per instance and only cached once it\n * succeeds, so a root that does not exist yet cannot poison the entry.\n * - Case and Unicode in the root path. A caller can spell a root on a\n * folding filesystem as `/Users/me/Data` or `/users/me/data`, or in\n * NFC or NFD, and reach one directory.\n *\n * The key-derived tail of `path` cannot alias: it is the fold-invariant\n * encoding from `local-fs-key-codec.ts`, so distinct keys are distinct\n * files on every filesystem and the case/NFC fold below changes nothing\n * there. The fold is kept for the root-spelling case only. It\n * over-approximates on a case-sensitive filesystem, where two roots\n * differing only in case are really different directories and share a\n * lock; that costs a little concurrency, never correctness. And it is\n * not exact Unicode case folding (JS has no `toCaseFold()`), so a root\n * spelled with `Σ` and one with `σ` get separate locks — acceptable for\n * a root path, which the operator chooses once.\n */\n async #lockKey(path: string): Promise<string> {\n const root = await this.#canonicalRoot();\n return (root + path.slice(this.#root.length)).normalize(\"NFC\").toLowerCase();\n }\n\n /**\n * {@link #root} with symlinks resolved. Cached only on success: `delete`\n * against a bucket that was never created would otherwise memoize the\n * un-canonicalized spelling and defeat the aliasing guard for every\n * later `put`.\n *\n * Only `ENOENT` falls back. Every other `realpath` failure — `EACCES`,\n * `ELOOP`, `ENAMETOOLONG` — throws, because the fallback is a *different\n * lock key*, and absorbing those would let an instance that cannot\n * canonicalize run unserialized against one that can. That is the\n * exactly-one-winner guarantee this lock exists to provide, failing\n * silently, which is indistinguishable from the defect it fixed. A root\n * that is unreadable is a broken deployment either way; the only choice\n * is whether it says so.\n *\n * Not caching failure bounds that to one call but does not erase it.\n * `put` mkdirs before locking so it always canonicalizes; `delete` does\n * not, so against a not-yet-created symlinked root it locks the\n * unresolved spelling while a concurrent `put` locks the resolved one —\n * two locks, no serialization. That needs only ONE spelling in play, not\n * two: the split is resolved-vs-unresolved form of the same path.\n *\n * Known and kept, not overlooked. The hazard `delete` locks\n * against is slipping inside an `ifMatch` compare→publish, which needs\n * the key to exist, hence the root to exist, hence `realpath` to have\n * succeeded — so both conditions hold only if the root appears between\n * this call and the `rm`, and the next call self-heals. Fixes cost more\n * than that: mkdir-to-get-a-lock-key makes deleting from an absent\n * bucket create it, and walking to the deepest existing ancestor adds\n * real complexity for an unreachable window.\n */\n async #canonicalRoot(): Promise<string> {\n if (this.#realRoot !== undefined) {\n return this.#realRoot;\n }\n try {\n this.#realRoot = await realpath(this.#root);\n return this.#realRoot;\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return this.#root;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage: cannot canonicalize root (${this.#root}): ${(error as Error).message}`,\n { cause: 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 await this.#ensureFormat(false);\n const keys: string[] = [];\n for (const components of (await walk(this.#root)) ?? []) {\n const key = decodeComponents(components);\n if (key !== null) {\n keys.push(key);\n continue;\n }\n // Not the canonical encoding of any key: a file this adapter did not\n // write (`notes~`, `100%zz`). Usually no `get`/`put`/`delete` can\n // address it either, so it is outside the keyspace and skipped rather\n // than failing every `list` over one stray file.\n //\n // Except on a folding filesystem, where a stray such as `c/%4A` or\n // `README.md` IS the file that `get(\"c/J\")` / `get(\"readme.md\")`\n // reads, and a `put` renames over it keeping the stray spelling.\n // Skipping it would hide a key that the other verbs see, so when the\n // case/NFC fold of the name decodes and resolves to this very file,\n // fail loudly instead. `InvalidConfig`, as the legacy-tree refusal is:\n // both mean the data directory holds files the operator must move.\n const alias = await this.#aliasedKey(components);\n if (alias !== null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `LocalFsStorage.list: ${join(this.#root, ...components)} was not written by this ` +\n `adapter but the filesystem resolves key ${JSON.stringify(alias)} to it; move the ` +\n `file out of the data directory`,\n );\n }\n }\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 let buf: Buffer;\n try {\n buf = await readFile(this.#pathFor(key));\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n // Deleted between `walk` and this read. A key vanishing\n // mid-listing is a legal outcome on a real object store, so skip\n // it rather than failing the whole iteration — and skip it\n // rather than locking, since `list` is a snapshot iterator, not\n // a critical section. Reachable in the maintenance fold, where\n // `runGc` deletes while the compactor walks the same prefixes.\n continue;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.list(${key}): ${(error as Error).message}`,\n { cause: error },\n );\n }\n yield { key, etag: etagOf(buf) };\n yielded += 1;\n }\n }\n\n /**\n * The key whose on-disk path the filesystem resolves to the stray file at\n * `components`, or `null` if none does. Only a case- or\n * normalization-folding filesystem produces one: the candidate is\n * {@link foldToEncodedAlphabet} of the name, which is a key only if it\n * decodes, and an alias only if both paths name the same inode.\n */\n async #aliasedKey(components: readonly string[]): Promise<string | null> {\n const folded = components.map(foldToEncodedAlphabet);\n const key = decodeComponents(folded);\n if (key === null) {\n return null;\n }\n try {\n const [a, b] = await Promise.all([\n stat(join(this.#root, ...components)),\n stat(join(this.#root, ...folded)),\n ]);\n return a.dev === b.dev && a.ino === b.ino ? key : null;\n } catch (error) {\n // Either side vanished, or the fold names no file: ENOENT, or ENOTDIR\n // when the folded path runs through a key's file (`Notes/todo` beside\n // the key `notes` on a case-sensitive filesystem), or ENAMETOOLONG\n // should a fold ever lengthen a name. None is an alias.\n if (\n isErrnoException(error) &&\n (error.code === \"ENOENT\" || error.code === \"ENOTDIR\" || error.code === \"ENAMETOOLONG\")\n ) {\n return null;\n }\n throw new BaerlyError(\"InvalidResponse\", `LocalFsStorage.list: ${(error as Error).message}`, {\n cause: error,\n });\n }\n }\n\n /**\n * Make sure the root uses the current key encoding before any operation\n * touches it. With the marker present this is one small read per\n * instance. Without it the root is scanned once:\n *\n * - absent root: nothing to read, so reads return without stamping, and\n * the first `put` (`create`) makes the root and stamps it;\n * - every on-disk name already reads the same under the encoding (true\n * of kernel-written trees with lowercase ids that hold no snapshot;\n * the snapshot segment `L9` is escaped): stamp, nothing moves;\n * - otherwise refuse with `InvalidConfig`. There is no in-place\n * migration — renaming cannot undo merges a folding filesystem has\n * already made — so the remedy is dump with the older release and\n * restore into a fresh directory.\n *\n * Only success is cached, so a refusal repeats on every call.\n */\n async #ensureFormat(create: boolean): Promise<void> {\n if (this.#formatChecked) {\n return;\n }\n // Canonicalize first so a broken root (ELOOP, EACCES) reports as such —\n // see `#canonicalRoot` — rather than as a failed marker read.\n await this.#canonicalRoot();\n const marker = join(this.#root, FORMAT_MARKER);\n if (await readFormatMarker(marker)) {\n this.#formatChecked = true;\n return;\n }\n if (create) {\n await mkdir(this.#root, { recursive: true });\n }\n const legacy = await findLegacyPaths(this.#root);\n if (legacy === null) {\n return; // root absent and nothing to create\n }\n // Re-read before refusing: a concurrent opener may have stamped the\n // marker and written encoded names since this scan began.\n if (legacy.length > 0 && !(await readFormatMarker(marker))) {\n const shown = legacy.slice(0, LEGACY_PATHS_SHOWN).map((p) => ` ${p}`);\n if (legacy.length > LEGACY_PATHS_SHOWN) {\n shown.push(` … and ${legacy.length - LEGACY_PATHS_SHOWN} more`);\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `LocalFsStorage: ${this.#root} holds dev data from an older release, which this ` +\n `release cannot read. Move the directory aside or delete it; the next write ` +\n `starts a fresh one. The usual causes are a folded collection (\\`snapshot/L9/\\`) ` +\n `and an uppercase letter in a collection name or id (a camelCase name such as ` +\n `\\`boardInvitees\\`). To keep a collection's rows, dump it with the older release ` +\n `(\\`baerly admin dump\\`) and restore into the fresh directory ` +\n `(\\`baerly admin restore\\`); a dump holds collection rows only, not other files ` +\n `the app stored here. Paths not valid under the current key encoding (no ` +\n `${FORMAT_MARKER} marker):\\n` +\n `${shown.join(\"\\n\")}\\n` +\n `If a listed path is a stray file that is not data, move it out of the directory ` +\n `instead. Keys that differed only by case or Unicode normalization may already ` +\n `have been merged by the filesystem.`,\n );\n }\n await stampFormatMarker(marker);\n this.#formatChecked = true;\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) or that the encoding cannot\n * represent injectively (lone surrogates). 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, ...encodeKey(key));\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 * `true` when the root's format marker exists and names the current\n * encoding, `false` when it is absent. A marker naming another encoding\n * means a newer release wrote this directory, so it is refused.\n */\nconst readFormatMarker = async (marker: string): Promise<boolean> => {\n const body = await readExisting(marker).catch((error: unknown) => {\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage: cannot read ${marker}: ${(error as Error).message}`,\n { cause: error },\n );\n });\n if (body === null) {\n return false;\n }\n let encoding: unknown;\n try {\n encoding = (JSON.parse(new TextDecoder().decode(body)) as { key_encoding?: unknown })\n .key_encoding;\n } catch (error) {\n throw new BaerlyError(\"InvalidResponse\", `LocalFsStorage: ${marker} is not valid JSON`, {\n cause: error,\n });\n }\n if (encoding !== KEY_ENCODING) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `LocalFsStorage: ${marker} names key_encoding ${JSON.stringify(encoding)}; this release ` +\n `reads only key_encoding ${KEY_ENCODING}`,\n );\n }\n return true;\n};\n\n/**\n * Write the format marker with the same temp + `link(2)` exclusive create\n * as `ifNoneMatch:\"*\"`. Losing that race to a concurrent opener is fine as\n * long as what it wrote is the current encoding.\n */\nconst stampFormatMarker = async (marker: string): Promise<void> => {\n const tmp = tempPathFor(marker);\n try {\n await writeFile(tmp, `${JSON.stringify({ key_encoding: KEY_ENCODING })}\\n`);\n await link(tmp, marker);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"EEXIST\" && (await readFormatMarker(marker))) {\n return;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage: cannot write ${marker}: ${(error as Error).message}`,\n { cause: error },\n );\n } finally {\n await rm(tmp, { force: true }).catch(() => {});\n }\n};\n\n/**\n * Non-ASCII characters that APFS's full case folding maps to ASCII but\n * `toLowerCase` leaves alone (Unicode CaseFolding.txt status `F`, plus the\n * `C` mapping of long `ſ`). Each was checked on an APFS volume: a file\n * named with the left side is reached by the right side.\n */\nconst APFS_ASCII_FOLDS: Readonly<Record<string, string>> = {\n ß: \"ss\", // U+00DF\n ẞ: \"ss\", // U+1E9E\n ſ: \"s\", // U+017F\n ff: \"ff\", // U+FB00\n fi: \"fi\", // U+FB01\n fl: \"fl\", // U+FB02\n ffi: \"ffi\", // U+FB03\n ffl: \"ffl\", // U+FB04\n ſt: \"st\", // U+FB05\n st: \"st\", // U+FB06\n};\nconst APFS_ASCII_FOLDABLE = /[ßẞſff-st]/g;\n\n/**\n * Fold an on-disk name the way a folding filesystem matches it, as far as\n * the result can land in the encoded alphabet (`a-z0-9-_.%`). A name\n * containing anything else after the fold cannot decode, so only folds to\n * ASCII matter: lowercase (which also maps Kelvin `K` to `k`) plus\n * {@link APFS_ASCII_FOLDS}. Normalization adds none: the only canonical\n * decompositions to ASCII are Kelvin `K`, U+037E (`;`) and U+1FEF (`` ` ``),\n * and the last two are escaped by the encoding.\n */\nconst foldToEncodedAlphabet = (name: string): string =>\n name.replace(APFS_ASCII_FOLDABLE, (c) => APFS_ASCII_FOLDS[c]!).toLowerCase();\n\n/**\n * Paths under `root` that the pre-encoding layout wrote and the current\n * encoding would read differently (uppercase, non-ASCII, `%`, `~`, a\n * leading `.` …). Empty when the tree can be adopted as-is; `null` when\n * the root does not exist.\n *\n * Walks dot-prefixed names too: the old layout stored a key segment such\n * as an `_id` or collection named `.foo` verbatim, and the encoding treats\n * that name as adapter-private, so skipping it here would adopt the tree\n * and silently drop or orphan that data.\n */\nconst findLegacyPaths = async (root: string): Promise<string[] | null> => {\n const files = await walk(root, isLegacyScanNoise);\n if (files === null) {\n return null;\n }\n return files\n .filter((components) => decodeComponents(components) !== components.join(\"/\"))\n .map((components) => components.join(\"/\"))\n .toSorted();\n};\n\n/**\n * Entries the legacy scan may skip: staging temps (both layouts wrote them,\n * and the old one rejected keys with that prefix), and the files Finder\n * and git leave behind. Junk names are skipped as FILES only — a directory\n * called `.DS_Store` would be a legacy collection or tenant, i.e. data.\n * Nothing else is assumed not to be data.\n *\n * The format marker is deliberately not here. The scan runs only when the\n * marker was absent; if a concurrent opener stamps it mid-scan, the scan\n * flags it like any other name and `#ensureFormat`'s re-read of the marker\n * is what accepts the directory. A nested file with the marker's name is\n * legacy data (a key segment that old layout stored verbatim).\n */\nconst isLegacyScanNoise = (name: string, isDirectory: boolean): boolean =>\n name.startsWith(TEMP_PREFIX) || (!isDirectory && (name === \".DS_Store\" || name === \".gitkeep\"));\n\n/**\n * In the current layout every dot-prefixed name is not a key: no encoded\n * key component starts with `.`, so those are adapter-private (staging\n * temps, the format marker) or foreign (`.DS_Store`). Skipping temps is\n * what keeps a concurrent `list` from surfacing a half-published key.\n */\nconst isDotName = (name: string, _isDirectory: boolean): boolean => name.startsWith(\".\");\n\n/**\n * Recursive directory walk. Returns each file's path components relative\n * to `root`, or `null` when `root` does not exist. Entries for which\n * `skip` holds are ignored at every depth, directories included.\n */\nconst walk = async (\n root: string,\n skip: (name: string, isDirectory: boolean) => boolean = isDotName,\n): Promise<string[][] | null> => {\n const out: string[][] = [];\n const stack: Array<{ dir: string; components: string[] }> = [{ dir: root, components: [] }];\n while (stack.length > 0) {\n const { dir, components } = 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 if (dir === root) {\n return null;\n }\n continue;\n }\n throw error;\n }\n for (const entry of entries) {\n if (skip(entry.name, entry.isDirectory())) {\n continue;\n }\n const next = [...components, entry.name];\n if (entry.isDirectory()) {\n stack.push({ dir: join(dir, entry.name), components: next });\n } else if (entry.isFile()) {\n out.push(next);\n }\n }\n }\n return out;\n};\n","import { styleText, type InspectColor } from \"node:util\";\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 paint = (format: InspectColor | InspectColor[], text: string): string =>\n isPlain ? text : styleText(format, text, { validateStream: false });\n const pc = {\n boldCyan: (text: string): string => paint([\"bold\", \"cyan\"], text),\n green: (text: string): string => paint(\"green\", text),\n dim: (text: string): string => paint(\"dim\", text),\n };\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.boldCyan(`▎ 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","import {\n BaerlyError,\n isWriteConflict,\n CURRENT_JSON_SCHEMA_VERSION,\n createCurrentJson,\n mintGeneration,\n type Storage,\n} from \"@baerly/protocol\";\nimport { assertNameSegment } from \"@baerly/server/_internal/testing\";\n\n/**\n * Optional pre-warm: idempotently create the `current.json` manifest\n * for a single `(app, tenant, collection)` 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/<collection>/current.json`) and\n * swallows `BaerlyError{code:\"WriteConflict\"}` so re-runs are safe. The\n * three names follow the same rule as `Db.create` / `db.collection`\n * (including Unicode Normalization Form C), refused with\n * `BaerlyError{code:\"InvalidConfig\"}` before any write. An\n * existing manifest is preserved verbatim — this function never\n * overwrites a populated manifest. The seed shape matches the kernel's\n * auto-create, with one deliberate exception: `generation` is a fresh\n * nonce, so a pre-warm and an auto-provision are equivalent rather than\n * byte-identical. Only one of them can win the `If-None-Match` create,\n * and a generation is only ever compared against a cursor minted from\n * it, so the difference is unobservable.\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\", collection: \"tickets\" });\n * // …then `baerlyNode({ config, storage, verifier })`.\n * ```\n */\nexport const ensureTable = async (\n storage: Storage,\n args: { app: string; tenant: string; collection: string },\n): Promise<void> => {\n // Plain-JS callers bypass the type: refuse a missing `collection` as a\n // BaerlyError, and point a caller still on the pre-0.7 `table` key at\n // the rename. `table` is never read as the name.\n if (typeof args.collection !== \"string\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"table\" in args\n ? \"ensureTable: the `table` key is now `collection`; pass { app, tenant, collection }\"\n : \"ensureTable: collection must be a string\",\n );\n }\n // The SDK's name rule (key segment + NFC), before any write.\n assertNameSegment(args.app, \"app\", \"ensureTable\");\n assertNameSegment(args.tenant, \"tenant\", \"ensureTable\");\n assertNameSegment(args.collection, \"collection\", \"ensureTable\");\n const key = `app/${args.app}/tenant/${args.tenant}/manifests/${args.collection}/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 generation: mintGeneration(),\n });\n } catch (error) {\n if (isWriteConflict(error)) {\n return;\n }\n throw error;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2BA,MAAM,wBAAQ,IAAI,IAAqB;;;;;;;;;;;;;;;;;;AAmBvC,MAAa,cAAc,OAAU,SAAiB,OAAqC;CACzF,MAAM,OAAO,MAAM,oBAAoB,gBAAgB;EAAE,MAAM,QAAQ,QAAQ;EAAG,SAAS;CAAE,EAAE;CAC/F,KAAK,WAAW;CAKhB,MAAM,cAAc,KAAK;CACzB,IAAI;CACJ,KAAK,OAAO,IAAI,SAAe,YAAY;EACzC,UAAU;CACZ,CAAC;CAED,MAAM;CACN,IAAI;EACF,OAAO,MAAM,GAAG;CAClB,UAAU;EACR,QAAQ;EACR,KAAK,WAAW;EAQhB,IAAI,KAAK,YAAY,KAAK,MAAM,IAAI,OAAO,MAAM,MAC/C,MAAM,OAAO,OAAO;CAExB;AACF;;AC7BA,MAAM,iBAAiB;AAEvB,MAAMA,gBAAc,IAAI,YAAY;AAGpC,MAAM,cAAc,IAAI,YAAY,SAAS;CAAE,OAAO;CAAM,WAAW;AAAK,CAAC;;AAG7E,MAAM,iBAAiB,MACpB,KAAK,MAAQ,KAAK,OAClB,KAAK,MAAQ,KAAK,MACnB,MAAM,MACN,MAAM,MACN,MAAM;AAER,MAAM,MAAM;AAEZ,MAAM,cAAc,MAAsB,IAAI,EAAE,SAAS,EA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AK,eAAe,UAC7B,MAAM,IAAI,YACR,iBACA,WAAW,OACP,uFACA,0CACN;CAGF,kBAAkB,KAAK,KAAK,OAAO,aAAa;CAChD,kBAAkB,KAAK,QAAQ,UAAU,aAAa;CACtD,kBAAkB,KAAK,YAAY,cAAc,aAAa;CAC9D,MAAM,MAAM,OAAO,KAAK,IAAI,UAAU,KAAK,OAAO,aAAa,KAAK,WAAW;CAC/E,IAAI;EACF,MAAM,kBAAkB,SAAS,KAAK;GACpC,gBAAA;GACA,UAAU;GACV,WAAW;GACX,eAAe;GACf,cAAc;IAAE,OAAO;IAAG,OAAO;IAAI,YAAY;GAAG;GACpD,gBAAgB;GAChB,eAAe;GACf,YAAY,eAAe;EAC7B,CAAC;CACH,SAAS,OAAO;EACd,IAAI,gBAAgB,KAAK,GACvB;EAEF,MAAM;CACR;AACF"}
|
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
import { t as BaerlyError } from "./errors-7Rk1HGCE.js";
|
|
2
|
+
import { d as runReplaceById, m as validateWire, n as collectionReadContext, o as registerDbInternals, p as assertReadDocId, s as makeQuery, t as assertKeySegment, u as runInsert } from "./db-read-seams-BSs0m1z1.js";
|
|
3
|
+
import { a as assertNameNotReserved } from "./path-segment-DBXG26PW.js";
|
|
4
|
+
import { t as assertValidStorageKey } from "./key-C4FPZ9Io.js";
|
|
5
|
+
// packages/protocol/src/env.ts
|
|
6
|
+
const PAAS_MARKERS = [
|
|
7
|
+
"RAILWAY_ENVIRONMENT",
|
|
8
|
+
"RENDER",
|
|
9
|
+
"FLY_APP_NAME",
|
|
10
|
+
"K_SERVICE",
|
|
11
|
+
"DYNO",
|
|
12
|
+
"KUBERNETES_SERVICE_HOST",
|
|
13
|
+
"ECS_CONTAINER_METADATA_URI_V4"
|
|
14
|
+
];
|
|
15
|
+
/**
|
|
16
|
+
* True when `env` looks like a deployed environment: `NODE_ENV=production`
|
|
17
|
+
* or any {@link PAAS_MARKERS} set to a non-empty value. Decides whether a
|
|
18
|
+
* non-durable store (in-memory, local-fs) should fail loud instead of
|
|
19
|
+
* silently serving a production workload. A CI runner (`CI` set to a
|
|
20
|
+
* non-empty, non-`false` value) is never treated as deployed, so PaaS
|
|
21
|
+
* markers from an in-cluster CI agent do not trip it.
|
|
22
|
+
*/
|
|
23
|
+
const isDeployedEnv = (env) => {
|
|
24
|
+
const inCi = (env["CI"] ?? "") !== "" && env["CI"] !== "false";
|
|
25
|
+
return env["NODE_ENV"] === "production" || !inCi && PAAS_MARKERS.some((m) => (env[m] ?? "") !== "");
|
|
26
|
+
};
|
|
27
|
+
// packages/protocol/src/storage/memory.ts
|
|
28
|
+
const utf8Encoder = new TextEncoder();
|
|
29
|
+
const EPHEMERAL_ENV_OPT_IN = "BAERLY_ALLOW_EPHEMERAL_STORAGE";
|
|
30
|
+
const readProcessEnv = () => globalThis.process?.env ?? {};
|
|
31
|
+
let warnedEphemeralInDeployment = false;
|
|
32
|
+
const assertEphemeralAllowed = (explicitOptIn) => {
|
|
33
|
+
const env = readProcessEnv();
|
|
34
|
+
if (!isDeployedEnv(env)) return;
|
|
35
|
+
if (!explicitOptIn && env[EPHEMERAL_ENV_OPT_IN] !== "true") throw new BaerlyError("InvalidConfig", `Refusing to use in-memory storage in a deployed environment — all data is lost on restart. MemoryStorage is for tests/local dev only; configure a durable bucket (AWS S3 / Cloudflare R2). To intentionally opt in: new MemoryStorage({ ephemeral: true }) or ${EPHEMERAL_ENV_OPT_IN}=true.`);
|
|
36
|
+
if (!warnedEphemeralInDeployment) {
|
|
37
|
+
warnedEphemeralInDeployment = true;
|
|
38
|
+
console.warn("[baerly] in-memory storage in a deployed environment — ALL DATA IS LOST ON RESTART.");
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Compare two keys by their UTF-8 byte sequences — the order S3 and
|
|
43
|
+
* R2 use for `list`. JavaScript's default string sort compares UTF-16
|
|
44
|
+
* code units, which diverges from UTF-8 byte order for supplementary-
|
|
45
|
+
* plane characters (e.g. emoji sort before high-BMP characters under
|
|
46
|
+
* UTF-16 but after them in UTF-8). Using this keeps the in-memory
|
|
47
|
+
* reference backend faithful to the real adapters. (All kernel keys
|
|
48
|
+
* are ASCII base-32, where the two orders coincide — this only
|
|
49
|
+
* matters for adversarial / non-ASCII keys.)
|
|
50
|
+
*/
|
|
51
|
+
const compareKeysUtf8 = (a, b) => {
|
|
52
|
+
const ba = utf8Encoder.encode(a);
|
|
53
|
+
const bb = utf8Encoder.encode(b);
|
|
54
|
+
const n = Math.min(ba.length, bb.length);
|
|
55
|
+
for (let i = 0; i < n; i++) if (ba[i] !== bb[i]) return ba[i] - bb[i];
|
|
56
|
+
return ba.length - bb.length;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* In-memory `Storage`. The randomized property test runs against
|
|
60
|
+
* this; it must be deterministic — no clocks beyond the caller's,
|
|
61
|
+
* no randomness, no I/O.
|
|
62
|
+
*
|
|
63
|
+
* ETags are a monotonically increasing hex counter formatted in the
|
|
64
|
+
* `"<hex>"` shape S3 returns (the surrounding double-quotes are part
|
|
65
|
+
* of the ETag header value). Keys are stored verbatim.
|
|
66
|
+
*
|
|
67
|
+
* **Test-confidence caveat:** every method resolves on the microtask
|
|
68
|
+
* queue with no real concurrency, so `put` reads `existing` and writes
|
|
69
|
+
* back with no interleaving. MemoryStorage therefore CANNOT exercise the
|
|
70
|
+
* compare-and-swap race the writer-fence model depends on — two writers
|
|
71
|
+
* contending on one `current.json` always serialize here, so a green run
|
|
72
|
+
* is necessary but not sufficient. That race is covered only by the
|
|
73
|
+
* randomized integration tests against real S3 / Minio
|
|
74
|
+
* (`tests/integration/randomized.test.ts`, `node-minio` variant).
|
|
75
|
+
* Relatedly, `serverDate` returns the local clock, not an independent
|
|
76
|
+
* server clock (see the `put` return below).
|
|
77
|
+
*/
|
|
78
|
+
var MemoryStorage = class {
|
|
79
|
+
#objects = /* @__PURE__ */ new Map();
|
|
80
|
+
#etagCounter = 0;
|
|
81
|
+
constructor(opts) {
|
|
82
|
+
assertEphemeralAllowed(opts?.ephemeral === true);
|
|
83
|
+
}
|
|
84
|
+
#nextEtag() {
|
|
85
|
+
this.#etagCounter += 1;
|
|
86
|
+
return `"${this.#etagCounter.toString(16)}"`;
|
|
87
|
+
}
|
|
88
|
+
async get(key, opts) {
|
|
89
|
+
assertValidStorageKey(key);
|
|
90
|
+
opts?.signal?.throwIfAborted();
|
|
91
|
+
const stored = this.#objects.get(key);
|
|
92
|
+
if (stored === void 0) return null;
|
|
93
|
+
return {
|
|
94
|
+
body: stored.body,
|
|
95
|
+
etag: stored.etag
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
async put(key, body, opts) {
|
|
99
|
+
assertValidStorageKey(key);
|
|
100
|
+
opts?.signal?.throwIfAborted();
|
|
101
|
+
const existing = this.#objects.get(key);
|
|
102
|
+
if (opts?.ifNoneMatch === "*" && existing !== void 0) throw new BaerlyError("WriteConflict", `PUT ${key}: precondition failed (ifNoneMatch="*" but key exists)`);
|
|
103
|
+
if (opts?.ifMatch !== void 0) {
|
|
104
|
+
if (existing === void 0) throw new BaerlyError("WriteConflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
|
|
105
|
+
if (existing.etag !== opts.ifMatch) throw new BaerlyError("WriteConflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${existing.etag})`);
|
|
106
|
+
}
|
|
107
|
+
const etag = this.#nextEtag();
|
|
108
|
+
this.#objects.set(key, {
|
|
109
|
+
body,
|
|
110
|
+
etag,
|
|
111
|
+
...opts?.contentType !== void 0 && { contentType: opts.contentType }
|
|
112
|
+
});
|
|
113
|
+
return {
|
|
114
|
+
etag,
|
|
115
|
+
serverDate: /* @__PURE__ */ new Date()
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
async delete(key, opts) {
|
|
119
|
+
assertValidStorageKey(key);
|
|
120
|
+
opts?.signal?.throwIfAborted();
|
|
121
|
+
this.#objects.delete(key);
|
|
122
|
+
}
|
|
123
|
+
async *list(prefix, opts) {
|
|
124
|
+
opts?.signal?.throwIfAborted();
|
|
125
|
+
const startAfter = opts?.startAfter ?? "";
|
|
126
|
+
const maxKeys = opts?.maxKeys ?? 1e400;
|
|
127
|
+
const sorted = [...this.#objects.keys()].filter((k) => k.startsWith(prefix) && compareKeysUtf8(k, startAfter) > 0).toSorted(compareKeysUtf8);
|
|
128
|
+
let yielded = 0;
|
|
129
|
+
for (const key of sorted) {
|
|
130
|
+
if (yielded >= maxKeys) return;
|
|
131
|
+
opts?.signal?.throwIfAborted();
|
|
132
|
+
const stored = this.#objects.get(key);
|
|
133
|
+
if (stored === void 0) continue;
|
|
134
|
+
yield {
|
|
135
|
+
key,
|
|
136
|
+
etag: stored.etag
|
|
137
|
+
};
|
|
138
|
+
yielded += 1;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Test-only: drop all objects.
|
|
143
|
+
* @internal
|
|
144
|
+
*/
|
|
145
|
+
_clear() {
|
|
146
|
+
this.#objects.clear();
|
|
147
|
+
this.#etagCounter = 0;
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
// packages/server/src/indexes.ts
|
|
151
|
+
/**
|
|
152
|
+
* Secondary index declarations: the runtime check on the
|
|
153
|
+
* {@link IndexDefinition} shape, whose type lives in `@baerly/protocol`.
|
|
154
|
+
*
|
|
155
|
+
* A declaration changes no storage call and no read result. Reads and
|
|
156
|
+
* insert uniqueness take membership from the snapshot plus the committed
|
|
157
|
+
* log, and the writer maintains no index objects. Validation keeps the
|
|
158
|
+
* declared names and shapes reserved for an index-aware format;
|
|
159
|
+
* {@link validateIndexDefinition} runs at `Db.create` (`./config.ts`).
|
|
160
|
+
*
|
|
161
|
+
* Buckets written before 0.7 may hold inert marker objects under
|
|
162
|
+
* `<collection>/index/`. Nothing reads, writes or reclaims them.
|
|
163
|
+
*/
|
|
164
|
+
/** Path-safe segment name. */
|
|
165
|
+
const INDEX_NAME_RE = /^[a-z][a-z0-9_]*$/;
|
|
166
|
+
/**
|
|
167
|
+
* Reject malformed {@link IndexDefinition} shapes synchronously, at
|
|
168
|
+
* `Db.create`. See docs/adr/003-layout-versioning-cordon.md.
|
|
169
|
+
*
|
|
170
|
+
* @throws BaerlyError code="InvalidConfig" — reserved leading-`_` `name`,
|
|
171
|
+
* or an `on` field is a dotted path (only top-level fields are accepted).
|
|
172
|
+
* @throws BaerlyError code="SchemaError" — `name` fails the regex, or `on` is empty.
|
|
173
|
+
*/
|
|
174
|
+
const validateIndexDefinition = (def) => {
|
|
175
|
+
assertNameNotReserved(def.name, "index.name");
|
|
176
|
+
if (!INDEX_NAME_RE.test(def.name)) throw new BaerlyError("SchemaError", `index.name must match /^[a-z][a-z0-9_]*$/; got ${JSON.stringify(def.name)}`);
|
|
177
|
+
if (typeof def.on === "string") {
|
|
178
|
+
if (def.on.length === 0) throw new BaerlyError("SchemaError", `index ${def.name}.on must be non-empty`);
|
|
179
|
+
} else if (def.on.length === 0) throw new BaerlyError("SchemaError", `index ${def.name}.on must be non-empty array`);
|
|
180
|
+
for (const field of typeof def.on === "string" ? [def.on] : def.on) if (field.includes(".")) throw new BaerlyError("InvalidConfig", `index ${def.name}.on must name top-level fields; dotted paths are not supported (got ${JSON.stringify(field)})`);
|
|
181
|
+
if (def.predicate !== void 0) try {
|
|
182
|
+
validateWire(def.predicate);
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (error instanceof BaerlyError) throw new BaerlyError("SchemaError", `index ${def.name}.predicate is invalid: ${error.message}`, { cause: error });
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
// packages/server/src/config.ts
|
|
189
|
+
/**
|
|
190
|
+
* Flatten `BaerlyConfig.collections` into the per-collection
|
|
191
|
+
* `schemas` and `indexes` maps that {@link Db.create} consumes at
|
|
192
|
+
* runtime. Used by the Cloudflare and Node adapters to pipe a
|
|
193
|
+
* single `config` object through to the writer.
|
|
194
|
+
*
|
|
195
|
+
* Both adapters import this helper rather than inlining the loop
|
|
196
|
+
* so the projection rule (drop empty index arrays; omit absent
|
|
197
|
+
* schemas) stays in one place. Future `CollectionDefinition`
|
|
198
|
+
* fields (lifecycle hooks, replica_identity) land here too.
|
|
199
|
+
*
|
|
200
|
+
* Every declared index is validated here, so a malformed declaration
|
|
201
|
+
* fails at {@link Db.create} rather than at the first write. Indexes
|
|
202
|
+
* change no read result, so validation is all a declaration buys:
|
|
203
|
+
* it keeps the names and shapes reserved.
|
|
204
|
+
*
|
|
205
|
+
* @throws BaerlyError code="InvalidConfig" — an index `name` uses the
|
|
206
|
+
* reserved leading `_`, or an `on` field is a dotted path.
|
|
207
|
+
* @throws BaerlyError code="SchemaError" — an index `name` fails
|
|
208
|
+
* `/^[a-z][a-z0-9_]*$/`, `on` is empty, or `predicate` is invalid.
|
|
209
|
+
*/
|
|
210
|
+
const collectionsToMaps = (collections) => {
|
|
211
|
+
const schemas = /* @__PURE__ */ new Map();
|
|
212
|
+
const indexes = /* @__PURE__ */ new Map();
|
|
213
|
+
if (collections === void 0) return {
|
|
214
|
+
schemas,
|
|
215
|
+
indexes
|
|
216
|
+
};
|
|
217
|
+
for (const [name, def] of Object.entries(collections)) {
|
|
218
|
+
if (def.schema !== void 0) schemas.set(name, def.schema);
|
|
219
|
+
if (def.indexes !== void 0 && def.indexes.length > 0) {
|
|
220
|
+
for (const index of def.indexes) validateIndexDefinition(index);
|
|
221
|
+
indexes.set(name, def.indexes);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
schemas,
|
|
226
|
+
indexes
|
|
227
|
+
};
|
|
228
|
+
};
|
|
229
|
+
// packages/server/src/collection.ts
|
|
230
|
+
/**
|
|
231
|
+
* Build a `Collection<T>` bound to one `(tenant, collection)` read context.
|
|
232
|
+
* Cheap: zero I/O, allocates one closure. Each modifier call returns
|
|
233
|
+
* a FRESH `Query<T>` — calling `.where(p1)` and `.where(p2)` on the
|
|
234
|
+
* same `Collection<T>` produces two independent chains.
|
|
235
|
+
*
|
|
236
|
+
* `.count()` shorthand defers to the empty-state `Query<T>.count()`
|
|
237
|
+
* so the fold logic lives in one place.
|
|
238
|
+
*
|
|
239
|
+
* @example
|
|
240
|
+
* ```ts
|
|
241
|
+
* const collection = makeCollection<Ticket>({
|
|
242
|
+
* storage,
|
|
243
|
+
* collectionPrefix: "app/tickets/tenant/acme/manifests/tickets",
|
|
244
|
+
* collectionName: "tickets",
|
|
245
|
+
* });
|
|
246
|
+
* const open = await collection.where({ status: "open" }).all();
|
|
247
|
+
* ```
|
|
248
|
+
*
|
|
249
|
+
* @internal
|
|
250
|
+
*/
|
|
251
|
+
const makeCollection = (ctx) => {
|
|
252
|
+
const seed = {
|
|
253
|
+
wire: void 0,
|
|
254
|
+
order: void 0,
|
|
255
|
+
limit: void 0
|
|
256
|
+
};
|
|
257
|
+
const byId = (id) => ({
|
|
258
|
+
...seed,
|
|
259
|
+
wire: { clauses: [{
|
|
260
|
+
op: "eq",
|
|
261
|
+
field: "_id",
|
|
262
|
+
value: id
|
|
263
|
+
}] }
|
|
264
|
+
});
|
|
265
|
+
return {
|
|
266
|
+
name: ctx.collectionName,
|
|
267
|
+
first: () => makeQuery(ctx, seed).first(),
|
|
268
|
+
all: () => makeQuery(ctx, seed).all(),
|
|
269
|
+
count: () => makeQuery(ctx, seed).count(),
|
|
270
|
+
/**
|
|
271
|
+
* Read the row at `id`. `id` is checked by the stored-id rule (not the
|
|
272
|
+
* NFC write rule) before any I/O, so a row an earlier release stored
|
|
273
|
+
* under a non-NFC id stays readable.
|
|
274
|
+
*
|
|
275
|
+
* @throws BaerlyError code="InvalidConfig" — `id` breaks the key-segment
|
|
276
|
+
* rule; no row can be stored under it. Nothing was read.
|
|
277
|
+
*/
|
|
278
|
+
get: async (id) => {
|
|
279
|
+
assertReadDocId(id);
|
|
280
|
+
return await makeQuery(ctx, byId(id)).first();
|
|
281
|
+
},
|
|
282
|
+
where: (p) => makeQuery(ctx, seed).where(p),
|
|
283
|
+
order: (s) => makeQuery(ctx, {
|
|
284
|
+
...seed,
|
|
285
|
+
order: s
|
|
286
|
+
}),
|
|
287
|
+
limit: (n) => makeQuery(ctx, {
|
|
288
|
+
...seed,
|
|
289
|
+
limit: n
|
|
290
|
+
}),
|
|
291
|
+
/**
|
|
292
|
+
* Insert one document. UUIDv7 auto-id when `_id` is absent,
|
|
293
|
+
* `undefined` or `""`; otherwise the caller-supplied `_id` is honoured. The first
|
|
294
|
+
* insert of an `_id` wins: a pre-commit existence check surfaces
|
|
295
|
+
* `AlreadyExists` for a row already committed, and the writer's insert
|
|
296
|
+
* guard surfaces it for one a concurrent insert committed after that
|
|
297
|
+
* check — matches the locked `Collection.insert` throws contract
|
|
298
|
+
* (`@baerly/protocol/src/collection-api.ts`).
|
|
299
|
+
*
|
|
300
|
+
* Single-attempt per call: log-create contention is resolved inside
|
|
301
|
+
* `Writer.commit()`, and its errors surface unchanged.
|
|
302
|
+
*
|
|
303
|
+
* @throws BaerlyError code="AlreadyExists" — a live row holds `_id`,
|
|
304
|
+
* committed before or concurrently with this call; of concurrent
|
|
305
|
+
* inserts of one `_id`, at most one commits. Nothing was committed.
|
|
306
|
+
* Not retriable.
|
|
307
|
+
* @throws BaerlyError code="WriteConflict" — a rejected storage precondition
|
|
308
|
+
* the writer does not resolve; the write was not committed. The writer
|
|
309
|
+
* makes one attempt (log-create races are resolved inside it), so
|
|
310
|
+
* re-run the call to retry. Retriable.
|
|
311
|
+
* @throws BaerlyError code="AmbiguousCommit" — a committing create may be
|
|
312
|
+
* durable, but its outcome could not be resolved, so the row may or may
|
|
313
|
+
* not have been inserted. Re-read by a stable `_id`; absence is not proof
|
|
314
|
+
* of failure. Not retriable-by-default; see `Writer.commit`.
|
|
315
|
+
* @throws BaerlyError code="SchemaError" — from the per-collection
|
|
316
|
+
* `SchemaValidator` threaded via `collectionReadContext`.
|
|
317
|
+
* @throws BaerlyError code="InvalidConfig" — the supplied `_id` is not a
|
|
318
|
+
* string (`null` included), or breaks the key-segment rule, holds an
|
|
319
|
+
* unpaired UTF-16 surrogate, or is not NFC. Nothing was written.
|
|
320
|
+
*/
|
|
321
|
+
insert: (doc) => runInsert(ctx, doc),
|
|
322
|
+
/**
|
|
323
|
+
* Update the row at `id` by JSON-merge-patch. Forwards to the
|
|
324
|
+
* predicate-form `runUpdate` through a `byId` wire, so at most one row
|
|
325
|
+
* is matched. A write to the row that commits after the read is not
|
|
326
|
+
* lost: the patch is re-applied to it, and a row deleted there is left
|
|
327
|
+
* deleted with `modified: 0` (see `runUpdate`).
|
|
328
|
+
*
|
|
329
|
+
* @throws BaerlyError code="WriteConflict" — a rejected storage precondition
|
|
330
|
+
* the writer does not resolve, or log retention retired part of the
|
|
331
|
+
* commit window; the write was not committed. The writer makes one
|
|
332
|
+
* attempt (log-create races are resolved inside it), so re-run the
|
|
333
|
+
* call to retry. Retriable.
|
|
334
|
+
* @throws BaerlyError code="AmbiguousCommit" — a committing create may be
|
|
335
|
+
* durable, but its outcome could not be resolved, so the update may or
|
|
336
|
+
* may not have been applied. Re-read by `id`; absence is not proof of
|
|
337
|
+
* failure. Not retriable-by-default; see `Writer.commit`.
|
|
338
|
+
* @throws BaerlyError code="SchemaError" — merged post-image rejected by the
|
|
339
|
+
* collection's bound validator, or `applyMergePatch(prev, patch)` produced
|
|
340
|
+
* `undefined`.
|
|
341
|
+
* @throws BaerlyError code="InvalidConfig" — the patch's top-level `_id`
|
|
342
|
+
* is present and is not `id` (`null` included), or `id` holds an
|
|
343
|
+
* unpaired UTF-16 surrogate or is not NFC.
|
|
344
|
+
* @throws BaerlyError code="InvalidResponse" — the stored row's `_id` is
|
|
345
|
+
* not the string `id`; repair it with `replace(id, doc)`.
|
|
346
|
+
*/
|
|
347
|
+
update: (id, patch) => makeQuery(ctx, byId(id)).update(patch),
|
|
348
|
+
/**
|
|
349
|
+
* Replace the row at `id` wholesale, preserving doc identity. Last
|
|
350
|
+
* writer wins against a concurrent update; a concurrent delete is not
|
|
351
|
+
* undone (see `runReplaceById`).
|
|
352
|
+
*
|
|
353
|
+
* @throws BaerlyError code="NotFound" — no row exists at `id`, including
|
|
354
|
+
* one a concurrent delete removed after the read.
|
|
355
|
+
* @throws BaerlyError code="WriteConflict" — a rejected storage precondition
|
|
356
|
+
* the writer does not resolve; the write was not committed. The writer
|
|
357
|
+
* makes one attempt (log-create races are resolved inside it), so
|
|
358
|
+
* re-run the call to retry. Retriable.
|
|
359
|
+
* @throws BaerlyError code="AmbiguousCommit" — a committing create may be
|
|
360
|
+
* durable, but its outcome could not be resolved, so the replace may or
|
|
361
|
+
* may not have been applied. Re-read by `id`; absence is not proof of
|
|
362
|
+
* failure. Not retriable-by-default; see `Writer.commit`.
|
|
363
|
+
* @throws BaerlyError code="SchemaError" — post-image rejected by the
|
|
364
|
+
* collection's bound validator.
|
|
365
|
+
* @throws BaerlyError code="InvalidConfig" — `id` breaks the key-segment
|
|
366
|
+
* rule, holds an unpaired UTF-16 surrogate, or is not NFC. Nothing
|
|
367
|
+
* was written.
|
|
368
|
+
*/
|
|
369
|
+
replace: (id, doc) => runReplaceById(ctx, id, doc),
|
|
370
|
+
/**
|
|
371
|
+
* Tombstone the row at `id`. Forwards to the predicate-form `runDelete`
|
|
372
|
+
* through a `byId` wire, so at most one row is matched. A missing row is
|
|
373
|
+
* not an error — `deleted` is `0`. `id` need not be NFC, so a row an
|
|
374
|
+
* earlier release stored under a non-NFC id stays deletable. A row a
|
|
375
|
+
* concurrent delete removed after the read is not deleted again (nor a
|
|
376
|
+
* re-insert of its `_id`): `deleted` is `0` (see `runDelete`).
|
|
377
|
+
*
|
|
378
|
+
* @throws BaerlyError code="WriteConflict" — a rejected storage precondition
|
|
379
|
+
* the writer does not resolve; the write was not committed. The writer
|
|
380
|
+
* makes one attempt (log-create races are resolved inside it), so
|
|
381
|
+
* re-run the call to retry. Retriable.
|
|
382
|
+
* @throws BaerlyError code="AmbiguousCommit" — a committing create may be
|
|
383
|
+
* durable, but its outcome could not be resolved, so the tombstone may or
|
|
384
|
+
* may not have been applied. Re-read by `id`; absence is not proof of
|
|
385
|
+
* failure. Not retriable-by-default; see `Writer.commit`.
|
|
386
|
+
* @throws BaerlyError code="InvalidResponse" — the stored row's `_id` is
|
|
387
|
+
* not the string `id`; repair it with `replace(id, doc)`.
|
|
388
|
+
*/
|
|
389
|
+
delete: (id) => makeQuery(ctx, byId(id)).delete()
|
|
390
|
+
};
|
|
391
|
+
};
|
|
392
|
+
// packages/server/src/db.ts
|
|
393
|
+
/**
|
|
394
|
+
* Runtime entry point. One `Db` per `(app, tenant)` request.
|
|
395
|
+
*
|
|
396
|
+
* Construct via {@link Db.create} — the constructor is private so
|
|
397
|
+
* callers don't accidentally bypass validation.
|
|
398
|
+
*
|
|
399
|
+
* **Collection provisioning.** `Db` provisions collections implicitly on
|
|
400
|
+
* the first commit — the writer auto-creates the per-collection
|
|
401
|
+
* `current.json` manifest with a zero-state seed, costing one extra
|
|
402
|
+
* Class A PUT on the very first write per collection and zero
|
|
403
|
+
* thereafter. There is no `ensureCollection` method on this class. For
|
|
404
|
+
* eager pre-warm (seed scripts, deploy-time provisioning, CI fixtures
|
|
405
|
+
* that want the manifest in place before the first request), use
|
|
406
|
+
* {@link "@gusto/baerly-storage/dev".ensureTable}. The two seeds are
|
|
407
|
+
* equivalent, not byte-identical: each mints its own `generation`
|
|
408
|
+
* nonce. Harmless — `If-None-Match` means exactly one lands.
|
|
409
|
+
*
|
|
410
|
+
* @example
|
|
411
|
+
* ```ts
|
|
412
|
+
* import { Db } from "@gusto/baerly-storage";
|
|
413
|
+
* import { MemoryStorage } from "@gusto/baerly-storage";
|
|
414
|
+
*
|
|
415
|
+
* const db = Db.create({
|
|
416
|
+
* storage: new MemoryStorage(),
|
|
417
|
+
* app: "tickets",
|
|
418
|
+
* tenant: "acme-co",
|
|
419
|
+
* });
|
|
420
|
+
*
|
|
421
|
+
* await db.collection("tickets").insert({ title: "first ticket", status: "open" });
|
|
422
|
+
* const open = await db.collection("tickets").where({ status: "open" }).all();
|
|
423
|
+
* ```
|
|
424
|
+
*
|
|
425
|
+
* @remarks
|
|
426
|
+
* **Anti-patterns** (TS compile errors, not runtime rejections):
|
|
427
|
+
* - `db.collection(name).insertOne({...})` / `.insert({...})` —
|
|
428
|
+
* the Mongo verb. Use `.insert(row)` (returns `{ _id }`).
|
|
429
|
+
* - `db.collection(name).findOne({...})` / `.find({...})` —
|
|
430
|
+
* the Mongo read verbs. Use `.get(id)` for by-id reads and
|
|
431
|
+
* `.where({...}).first()` / `.all()` for predicate reads.
|
|
432
|
+
* - `db.collection(name).aggregate([...])` — no pipeline stage
|
|
433
|
+
* model. Compose via `.where().order().limit()` modifiers.
|
|
434
|
+
* - Raw SQL strings of any shape. The kernel has no SQL parser.
|
|
435
|
+
*/
|
|
436
|
+
var Db = class Db {
|
|
437
|
+
app;
|
|
438
|
+
tenant;
|
|
439
|
+
/**
|
|
440
|
+
* Underlying `Storage`, captured so the collection API can issue reads
|
|
441
|
+
* using physical keys directly.
|
|
442
|
+
*/
|
|
443
|
+
#storage;
|
|
444
|
+
/**
|
|
445
|
+
* Per-collection {@link SchemaValidator}s threaded onto every
|
|
446
|
+
* {@link CollectionReadContext} this `Db` mints. Empty map means "no
|
|
447
|
+
* validation declared" — every write proceeds at zero overhead.
|
|
448
|
+
*
|
|
449
|
+
* Derived from `config.collections[*].schema` via
|
|
450
|
+
* {@link collectionsToMaps} at {@link Db.create} time.
|
|
451
|
+
*/
|
|
452
|
+
#schemas;
|
|
453
|
+
constructor(app, tenant, storage, schemas) {
|
|
454
|
+
this.app = app;
|
|
455
|
+
this.tenant = tenant;
|
|
456
|
+
this.#storage = storage;
|
|
457
|
+
this.#schemas = schemas;
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Build a tenant-scoped `Db`. Throws
|
|
461
|
+
* `BaerlyError{code:"InvalidConfig"}` if either `app` or `tenant`
|
|
462
|
+
* is empty, contains `/`, is `"."` or `".."`, contains control
|
|
463
|
+
* characters, starts with the reserved `"_"` prefix, exceeds
|
|
464
|
+
* 256 bytes, contains an unpaired UTF-16 surrogate
|
|
465
|
+
* (`!name.isWellFormed()`), or is not in Unicode Normalization Form C
|
|
466
|
+
* (`name !== name.normalize("NFC")`). Names are never normalized for
|
|
467
|
+
* you: pass `name.normalize("NFC")`.
|
|
468
|
+
*
|
|
469
|
+
* @throws BaerlyError code="InvalidConfig" when `app`, `tenant`, or a
|
|
470
|
+
* `config.collections` key is empty, contains `/`, is `"."` or
|
|
471
|
+
* `".."`, contains control characters, starts with the reserved
|
|
472
|
+
* `"_"` prefix, exceeds 256 bytes, contains an unpaired surrogate,
|
|
473
|
+
* or is not NFC.
|
|
474
|
+
*
|
|
475
|
+
* @example
|
|
476
|
+
* ```ts
|
|
477
|
+
* const db = Db.create({ storage, app: "tickets", tenant: "acme" });
|
|
478
|
+
* await db.collection("tickets").insert({ title: "hi" });
|
|
479
|
+
* ```
|
|
480
|
+
*/
|
|
481
|
+
static create(config) {
|
|
482
|
+
const { storage, app, tenant } = config;
|
|
483
|
+
assertKeySegment(app, "app", "Db.create");
|
|
484
|
+
assertKeySegment(tenant, "tenant", "Db.create");
|
|
485
|
+
for (const name of Object.keys(config.config?.collections ?? {})) assertKeySegment(name, "collection", "Db.create");
|
|
486
|
+
const derived = config.config !== void 0 ? collectionsToMaps(config.config.collections) : void 0;
|
|
487
|
+
return new Db(app, tenant, storage, derived?.schemas ?? /* @__PURE__ */ new Map());
|
|
488
|
+
}
|
|
489
|
+
collection(name) {
|
|
490
|
+
return makeCollection(collectionReadContext(this, name));
|
|
491
|
+
}
|
|
492
|
+
static {
|
|
493
|
+
registerDbInternals((db) => ({
|
|
494
|
+
storage: db.#storage,
|
|
495
|
+
schemas: db.#schemas
|
|
496
|
+
}));
|
|
497
|
+
}
|
|
498
|
+
};
|
|
499
|
+
export { MemoryStorage as n, isDeployedEnv as r, Db as t };
|
|
500
|
+
|
|
501
|
+
//# sourceMappingURL=src-Dr9uo3dc.js.map
|