@gusto/baerly-storage 0.3.0 → 0.4.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 (141) hide show
  1. package/README.md +157 -92
  2. package/dist/API.md +64 -32
  3. package/dist/CHANGELOG.md +295 -5
  4. package/dist/RECIPES.md +125 -0
  5. package/dist/THIRD-PARTY-LICENSES.txt +22 -96
  6. package/dist/{app-config-BIzyAKzy.d.ts → app-config-DyiFK3_k.d.ts} +43 -11
  7. package/dist/app-config.d.ts +1 -1
  8. package/dist/auth.d.ts +1 -1
  9. package/dist/auth.js +13 -13
  10. package/dist/auth.js.map +1 -1
  11. package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
  12. package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
  13. package/dist/baerly.js +35 -15
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +342 -0
  16. package/dist/{client-BJXF3XJA.d.ts → client-Fe8CwB73.d.ts} +3 -3
  17. package/dist/client-react.d.ts +3 -3
  18. package/dist/client-react.js +4 -4
  19. package/dist/client-react.js.map +1 -1
  20. package/dist/client.d.ts +4 -4
  21. package/dist/client.js +3 -3
  22. package/dist/{cloudflare-Cn2ibODt.js → cloudflare-DzKBrUlg.js} +2 -2
  23. package/dist/{cloudflare-Cn2ibODt.js.map → cloudflare-DzKBrUlg.js.map} +1 -1
  24. package/dist/cloudflare.d.ts +49 -6
  25. package/dist/cloudflare.js +55 -21
  26. package/dist/cloudflare.js.map +1 -1
  27. package/dist/config-1tv0-Yzm.js +2693 -0
  28. package/dist/config-1tv0-Yzm.js.map +1 -0
  29. package/dist/constants-CfeMWQWk.js +222 -0
  30. package/dist/constants-CfeMWQWk.js.map +1 -0
  31. package/dist/{cost-BZ_MDBmn.js → cost-DSMIVqzL.js} +42 -43
  32. package/dist/cost-DSMIVqzL.js.map +1 -0
  33. package/dist/{current-json-DsN7FNY1.js → current-json-C6nhPOm1.js} +6 -204
  34. package/dist/current-json-C6nhPOm1.js.map +1 -0
  35. package/dist/{db-CCT6tDfY.d.ts → db-DsPkOVEH.d.ts} +3 -3
  36. package/dist/{deploy-BKKyGlSJ.js → deploy-DonTr-CV.js} +4 -4
  37. package/dist/{deploy-BKKyGlSJ.js.map → deploy-DonTr-CV.js.map} +1 -1
  38. package/dist/dev-vite.d.ts +9 -5
  39. package/dist/dev-vite.js +5 -4
  40. package/dist/dev-vite.js.map +1 -1
  41. package/dist/dev.d.ts +1 -1
  42. package/dist/dev.js +1 -1
  43. package/dist/{doctor-BVU4GNXN.js → doctor-DSIyCDg_.js} +5 -8
  44. package/dist/{doctor-BVU4GNXN.js.map → doctor-DSIyCDg_.js.map} +1 -1
  45. package/dist/{dump-DPEAKub6.js → dump-Bh5k26VQ.js} +9 -32
  46. package/dist/dump-Bh5k26VQ.js.map +1 -0
  47. package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
  48. package/dist/errors-Dfa3p78c.js.map +1 -0
  49. package/dist/{export-BcuCLFFe.js → export-DtF5tDIM.js} +9 -32
  50. package/dist/{export-BcuCLFFe.js.map → export-DtF5tDIM.js.map} +1 -1
  51. package/dist/{fsck-RXgLOaJG.js → fsck-D_djMO5D.js} +10 -33
  52. package/dist/fsck-D_djMO5D.js.map +1 -0
  53. package/dist/{http-Bd4byR4n.js → http-DxM9MflO.js} +123 -35
  54. package/dist/http-DxM9MflO.js.map +1 -0
  55. package/dist/http.d.ts +42 -26
  56. package/dist/http.js +3 -2
  57. package/dist/{index-DnBGSeuU.d.ts → index-0rZcMBwy.d.ts} +2 -2
  58. package/dist/{index-Cmsxx-ZN.d.ts → index-B6oexfOB.d.ts} +7 -7
  59. package/dist/{index-BDceQQi-.d.ts → index-BNRh23K9.d.ts} +4 -4
  60. package/dist/{index-DW7GT6M2.d.ts → index-BYk9oCNf.d.ts} +193 -163
  61. package/dist/index.d.ts +6 -6
  62. package/dist/index.js +4 -4
  63. package/dist/{indexes-Cx7uMXm0.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
  64. package/dist/{inspect-DhI49PSi.js → inspect-6WZ-pC7-.js} +10 -33
  65. package/dist/inspect-6WZ-pC7-.js.map +1 -0
  66. package/dist/key-Di6yyxFu.js +35 -0
  67. package/dist/key-Di6yyxFu.js.map +1 -0
  68. package/dist/{log-tail-DXeDkWEp.js → log-tail-D98U1JBo.js} +31 -7
  69. package/dist/log-tail-D98U1JBo.js.map +1 -0
  70. package/dist/{maintenance-CWBQpZ2y.js → maintenance-B4Dki6Ig.js} +77 -22
  71. package/dist/maintenance-B4Dki6Ig.js.map +1 -0
  72. package/dist/{maintenance-BkhUr72A.d.ts → maintenance-B_e0T99L.d.ts} +28 -5
  73. package/dist/{maintenance-C_KSkVjd.js → maintenance-C7coQp4c.js} +17 -16
  74. package/dist/maintenance-C7coQp4c.js.map +1 -0
  75. package/dist/maintenance.d.ts +3 -3
  76. package/dist/maintenance.js +3 -3
  77. package/dist/node.d.ts +168 -65
  78. package/dist/node.js +3 -2
  79. package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
  80. package/dist/normalize-rjnZLwS4.js.map +1 -0
  81. package/dist/{observability-BYd-RzEx.js → observability-wzs3-BL_.js} +233 -71
  82. package/dist/observability-wzs3-BL_.js.map +1 -0
  83. package/dist/observability.d.ts +2 -2
  84. package/dist/observability.js +1 -1
  85. package/dist/{plan-DIu_B6fy.js → plan-a7PJHBCy.js} +2 -2
  86. package/dist/{plan-DIu_B6fy.js.map → plan-a7PJHBCy.js.map} +1 -1
  87. package/dist/{query-sQNO5vU_.js → query-rAtXNQQB.js} +96 -207
  88. package/dist/query-rAtXNQQB.js.map +1 -0
  89. package/dist/{rebuild-index-DP4CqSSs.js → rebuild-index-BVzQSZlm.js} +9 -32
  90. package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
  91. package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
  92. package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
  93. package/dist/{restore-DpQYef6r.js → restore-R-4rbciV.js} +73 -100
  94. package/dist/restore-R-4rbciV.js.map +1 -0
  95. package/dist/runtime-spec-qL3_lTTU.js +391 -0
  96. package/dist/runtime-spec-qL3_lTTU.js.map +1 -0
  97. package/dist/s3-http-B-z8th6O.d.ts +60 -0
  98. package/dist/s3.d.ts +47 -0
  99. package/dist/s3.js +45 -0
  100. package/dist/s3.js.map +1 -0
  101. package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
  102. package/dist/shared-secret-DgEicd3x.js.map +1 -0
  103. package/dist/src-BG20LZs7.js +2271 -0
  104. package/dist/src-BG20LZs7.js.map +1 -0
  105. package/dist/{src-Db4-qVtM.js → src-CYHFDrKz.js} +51 -8
  106. package/dist/src-CYHFDrKz.js.map +1 -0
  107. package/dist/{src-CWpkSbvJ.js → src-DYZ4H1aF.js} +6 -5
  108. package/dist/src-DYZ4H1aF.js.map +1 -0
  109. package/dist/{subcommand-CP9NY2J4.js → subcommand-DoDA-K7d.js} +44 -6
  110. package/dist/subcommand-DoDA-K7d.js.map +1 -0
  111. package/dist/time-DUqvFMHq.js +119 -0
  112. package/dist/time-DUqvFMHq.js.map +1 -0
  113. package/dist/{usage-CTfDq9HR.js → usage-DBV1eQHC.js} +7 -22
  114. package/dist/usage-DBV1eQHC.js.map +1 -0
  115. package/dist/wire-izfGZDvr.js.map +1 -1
  116. package/package.json +52 -28
  117. package/dist/config-CGyBopy3.js +0 -5326
  118. package/dist/config-CGyBopy3.js.map +0 -1
  119. package/dist/cost-BZ_MDBmn.js.map +0 -1
  120. package/dist/current-json-DsN7FNY1.js.map +0 -1
  121. package/dist/dump-DPEAKub6.js.map +0 -1
  122. package/dist/errors-DOdL95kK.js.map +0 -1
  123. package/dist/fsck-RXgLOaJG.js.map +0 -1
  124. package/dist/http-Bd4byR4n.js.map +0 -1
  125. package/dist/inspect-DhI49PSi.js.map +0 -1
  126. package/dist/log-tail-DXeDkWEp.js.map +0 -1
  127. package/dist/maintenance-CWBQpZ2y.js.map +0 -1
  128. package/dist/maintenance-C_KSkVjd.js.map +0 -1
  129. package/dist/normalize-XWY25_sG.js.map +0 -1
  130. package/dist/observability-BYd-RzEx.js.map +0 -1
  131. package/dist/query-sQNO5vU_.js.map +0 -1
  132. package/dist/rebuild-index-DP4CqSSs.js.map +0 -1
  133. package/dist/restore-DpQYef6r.js.map +0 -1
  134. package/dist/shared-secret-BJdSwpgw.js.map +0 -1
  135. package/dist/src-CWpkSbvJ.js.map +0 -1
  136. package/dist/src-D24wDpzR.js +0 -6247
  137. package/dist/src-D24wDpzR.js.map +0 -1
  138. package/dist/src-Db4-qVtM.js.map +0 -1
  139. package/dist/subcommand-CP9NY2J4.js.map +0 -1
  140. package/dist/usage-CTfDq9HR.js.map +0 -1
  141. /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-CYHFDrKz.js","names":["#objects","#etagCounter","#nextEtag","#storage","#schemas","#indexes"],"sources":["../packages/protocol/src/env.ts","../packages/protocol/src/storage/memory.ts","../packages/server/src/config.ts","../packages/server/src/auth/internal/none-verifier.ts","../packages/server/src/auth/internal/resolve-verifier.ts","../packages/server/src/collection.ts","../packages/server/src/db.ts"],"sourcesContent":["// Deployment detection shared by the in-memory storage guard and the\n// Node resolveStorageFromEnv resolver. Pure (env passed in) so it stays\n// Workerd-loadable. Markers are vars each platform sets unconditionally:\n// Cloud Run, Heroku, Kubernetes, ECS, Railway, Render, Fly.\n//\n// The list is deliberately conservative: every marker here is set ONLY by\n// the platform at runtime, never by that platform's local dev emulator, so\n// detection cannot false-positive a developer's machine. Serverless markers\n// like VERCEL / NETLIFY / AWS_LAMBDA_FUNCTION_NAME are intentionally omitted\n// — their local emulators (`vercel dev`, `netlify dev`, SAM local) set the\n// same vars, so adding them would break local development. Before adding a\n// marker, confirm it is never set by that platform's dev tooling. An\n// unmarked host should set NODE_ENV=production to opt into the guard.\nexport const PAAS_MARKERS = [\n \"RAILWAY_ENVIRONMENT\",\n \"RENDER\",\n \"FLY_APP_NAME\",\n \"K_SERVICE\",\n \"DYNO\",\n \"KUBERNETES_SERVICE_HOST\",\n \"ECS_CONTAINER_METADATA_URI_V4\",\n] as const;\n\n/**\n * True when `env` looks like a deployed environment: `NODE_ENV=production`\n * or any {@link PAAS_MARKERS} set to a non-empty value. Decides whether a\n * non-durable store (in-memory, local-fs) should fail loud instead of\n * silently serving a production workload. A CI runner (`CI` set to a\n * non-empty, non-`false` value) is never treated as deployed, so PaaS\n * markers from an in-cluster CI agent do not trip it.\n */\nexport const isDeployedEnv = (env: Record<string, string | undefined>): boolean => {\n // A CI runner is never a deployment — even in a k8s pod that sets a PaaS\n // marker (e.g. KUBERNETES_SERVICE_HOST) — so it must not trip the markers.\n const inCi = (env[\"CI\"] ?? \"\") !== \"\" && env[\"CI\"] !== \"false\";\n return (\n env[\"NODE_ENV\"] === \"production\" || (!inCi && PAAS_MARKERS.some((m) => (env[m] ?? \"\") !== \"\"))\n );\n};\n","import { isDeployedEnv } from \"../env.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport { assertValidStorageKey } from \"./key.ts\";\nimport type {\n Storage,\n StorageGetOptions,\n StorageGetResult,\n StorageListEntry,\n StoragePutOptions,\n StoragePutResult,\n} from \"./types.ts\";\n\ninterface StoredObject {\n body: Uint8Array;\n etag: string;\n contentType?: string;\n}\n\nconst utf8Encoder = new TextEncoder();\n\nconst EPHEMERAL_ENV_OPT_IN = \"BAERLY_ALLOW_EPHEMERAL_STORAGE\";\n\n// Read process env without a `node:` import so protocol stays Workerd-\n// loadable (on Workerd `process` is absent → env is `{}` → not deployed).\nconst readProcessEnv = (): Record<string, string | undefined> =>\n (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n\nlet warnedEphemeralInDeployment = false;\n\n// Fail closed when in-memory storage would silently back a deployed\n// workload (writes \"succeed\" into RAM, vanish on restart). No-op in\n// dev/test; bypass in a deployment only via an explicit acknowledgement.\nconst assertEphemeralAllowed = (explicitOptIn: boolean): void => {\n const env = readProcessEnv();\n if (!isDeployedEnv(env)) {\n return;\n }\n if (!explicitOptIn && env[EPHEMERAL_ENV_OPT_IN] !== \"true\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"Refusing to use in-memory storage in a deployed environment — all data is lost on restart. \" +\n \"MemoryStorage is for tests/local dev only; configure a durable bucket (AWS S3 / Cloudflare R2). \" +\n `To intentionally opt in: new MemoryStorage({ ephemeral: true }) or ${EPHEMERAL_ENV_OPT_IN}=true.`,\n );\n }\n if (!warnedEphemeralInDeployment) {\n warnedEphemeralInDeployment = true;\n console.warn(\n \"[baerly] in-memory storage in a deployed environment — ALL DATA IS LOST ON RESTART.\",\n );\n }\n};\n\n/** Options for {@link MemoryStorage}. */\nexport interface MemoryStorageOptions {\n /**\n * Acknowledge the store is intentionally ephemeral — required to\n * construct in a detected deployment ({@link isDeployedEnv}); ignored in\n * dev/test. Env equivalent: `BAERLY_ALLOW_EPHEMERAL_STORAGE=true`.\n */\n ephemeral?: boolean;\n}\n\n/**\n * Compare two keys by their UTF-8 byte sequences — the order S3 and\n * R2 use for `list`. JavaScript's default string sort compares UTF-16\n * code units, which diverges from UTF-8 byte order for supplementary-\n * plane characters (e.g. emoji sort before high-BMP characters under\n * UTF-16 but after them in UTF-8). Using this keeps the in-memory\n * reference backend faithful to the real adapters. (All kernel keys\n * are ASCII base-32, where the two orders coincide — this only\n * matters for adversarial / non-ASCII keys.)\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 * In-memory `Storage`. The randomized property test runs against\n * this; it must be deterministic — no clocks beyond the caller's,\n * no randomness, no I/O.\n *\n * ETags are a monotonically increasing hex counter formatted in the\n * `\"<hex>\"` shape S3 returns (the surrounding double-quotes are part\n * of the ETag header value). Keys are stored verbatim.\n *\n * **Test-confidence caveat:** every method resolves on the microtask\n * queue with no real concurrency, so `put` reads `existing` and writes\n * back with no interleaving. MemoryStorage therefore CANNOT exercise the\n * compare-and-swap race the writer-fence model depends on — two writers\n * contending on one `current.json` always serialize here, so a green run\n * is necessary but not sufficient. That race is covered only by the\n * randomized integration tests against real S3 / Minio\n * (`tests/integration/randomized.test.ts`, `node-minio` variant).\n * Relatedly, `serverDate` returns the local clock, not an independent\n * server clock (see the `put` return below).\n */\nexport class MemoryStorage implements Storage {\n readonly #objects = new Map<string, StoredObject>();\n #etagCounter = 0;\n\n constructor(opts?: MemoryStorageOptions) {\n assertEphemeralAllowed(opts?.ephemeral === true);\n }\n\n #nextEtag(): string {\n this.#etagCounter += 1;\n return `\"${this.#etagCounter.toString(16)}\"`;\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n if (stored === undefined) {\n return null;\n }\n if (opts?.ifNoneMatch !== undefined && opts.ifNoneMatch === stored.etag) {\n // 304 Not Modified — caller's cached copy is current.\n return null;\n }\n return { body: stored.body, etag: stored.etag };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n const existing = this.#objects.get(key);\n\n if (opts?.ifNoneMatch === \"*\" && existing !== undefined) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifNoneMatch=\"*\" but key exists)`,\n );\n }\n if (opts?.ifMatch !== undefined) {\n if (existing === undefined) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n if (existing.etag !== opts.ifMatch) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${existing.etag})`,\n );\n }\n }\n\n const etag = this.#nextEtag();\n this.#objects.set(key, {\n body,\n etag,\n // Stryker disable next-line ObjectLiteral,ConditionalExpression: contentType is stored in the internal StoredObject but never returned by get() — the Storage interface has no contentType on StorageGetResult, so any mutation of this spread is observable-equivalent\n ...(opts?.contentType !== undefined && { contentType: opts.contentType }),\n });\n // `serverDate` is intentionally returned — the kernel's adaptive\n // clock-skew loop consumes the write-time server clock. `list()`\n // deliberately omits `lastModified`: the in-memory impl has no\n // independent server clock, and its only consumer (GC's `due_at`\n // anchor) falls back to `now()` when it is absent, so omitting it\n // changes nothing.\n return { etag, serverDate: new Date() };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n this.#objects.delete(key);\n }\n\n async *list(\n prefix: string,\n opts?: { startAfter?: string; maxKeys?: number; signal?: AbortSignal },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n const startAfter = opts?.startAfter ?? \"\";\n const maxKeys = opts?.maxKeys ?? Infinity;\n const sorted = [...this.#objects.keys()]\n .filter((k) => k.startsWith(prefix) && compareKeysUtf8(k, startAfter) > 0)\n .toSorted(compareKeysUtf8);\n let yielded = 0;\n for (const key of sorted) {\n if (yielded >= maxKeys) {\n return;\n }\n opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n // Stryker disable next-line ConditionalExpression,BlockStatement: unreachable guard — keys come from Map.keys() so the corresponding value is always present; this branch exists only to satisfy noUncheckedIndexedAccess\n if (stored === undefined) {\n continue;\n }\n yield { key, etag: stored.etag };\n yielded += 1;\n }\n }\n\n /**\n * Test-only: drop all objects.\n * @internal\n */\n _clear(): void {\n this.#objects.clear();\n this.#etagCounter = 0;\n }\n}\n\n// Process-singleton MemoryStorage map keyed by bucket. Tests that need\n// multiple `Db` / `Writer` instances to see each other's writes\n// against an in-memory backend reach for this via\n// {@link getOrCreateMemoryStorageForBucket}; {@link resetMemoryStorage}\n// drops every bucket between test cases.\nconst sharedPerBucket = new Map<string, MemoryStorage>();\n\n/**\n * Test isolation: drop every bucket's contents from the shared\n * memory storage used by {@link getOrCreateMemoryStorageForBucket}.\n * Direct `MemoryStorage` instances built via `new MemoryStorage()`\n * are unaffected — those are isolated by construction.\n */\nexport const resetMemoryStorage = (): void => {\n sharedPerBucket.clear();\n};\n\n/**\n * Get the process-singleton {@link MemoryStorage} for the named\n * bucket, creating one on first access. Use this when constructing\n * a `Storage` directly so multiple consumers in the same process\n * see each other's writes for the same bucket name.\n */\nexport const getOrCreateMemoryStorageForBucket = (bucket: string): MemoryStorage => {\n let s = sharedPerBucket.get(bucket);\n if (s === undefined) {\n s = new MemoryStorage();\n sharedPerBucket.set(bucket, s);\n }\n return s;\n};\n","/**\n * Runtime helpers for the `BaerlyConfig` shape.\n *\n * The type declarations (`BaerlyConfig`, `BaerlyAppConfig`,\n * `CollectionDefinition`, `CollectionNames`, `RowOf`, `UnboundConfig`,\n * `defineConfig`) live in `@baerly/protocol` — the cross-platform\n * package — so cross-platform consumers (client, scaffold\n * `baerly.config.ts`) can reference them without dragging the\n * Node-only server modules (`AsyncLocalStorage` etc.) into their\n * typecheck graph.\n *\n * This file keeps only the runtime helper `collectionsToMaps`, which\n * the Cloudflare and Node adapters call to flatten\n * `BaerlyConfig.collections` into the per-collection maps that\n * `Db.create` consumes.\n *\n * @see @baerly/protocol app-config.ts — type declarations.\n */\n\nimport type { BaerlyConfig, IndexDefinition, SchemaValidator } from \"@baerly/protocol\";\n\n/**\n * Flatten `BaerlyConfig.collections` into the per-collection\n * `schemas` and `indexes` maps that {@link Db.create} consumes at\n * runtime. Used by the Cloudflare and Node adapters to pipe a\n * single `config` object through to the writer/planner.\n *\n * Both adapters import this helper rather than inlining the loop\n * so the projection rule (drop empty index arrays; omit absent\n * schemas) stays in one place. Future `CollectionDefinition`\n * fields (lifecycle hooks, replica_identity) land here too.\n */\nexport const collectionsToMaps = (\n collections: BaerlyConfig[\"collections\"] | undefined,\n): {\n schemas: ReadonlyMap<string, SchemaValidator>;\n indexes: ReadonlyMap<string, ReadonlyArray<IndexDefinition>>;\n} => {\n const schemas = new Map<string, SchemaValidator>();\n const indexes = new Map<string, ReadonlyArray<IndexDefinition>>();\n if (collections === undefined) {\n return { schemas, indexes };\n }\n for (const [name, def] of Object.entries(collections)) {\n if (def.schema !== undefined) {\n schemas.set(name, def.schema);\n }\n if (def.indexes !== undefined && def.indexes.length > 0) {\n indexes.set(name, def.indexes);\n }\n }\n return { schemas, indexes };\n};\n","import type { Verifier } from \"@baerly/protocol\";\n\n/**\n * Internal helper backing `config.auth === \"none\"`. Returns a\n * `Verifier` that resolves every request to the supplied\n * `tenantPrefix` with `identity: { kind: \"none\" }`. The kernel\n * NEVER reads the `Authorization` header in this mode — the network\n * seam itself is the trust boundary.\n *\n * Discriminant note: `identity.kind === \"none\"` distinguishes the\n * \"operator opted into auth=none in baerly.config.ts\" branch from the\n * bearer-token paths (`kind: \"shared-secret\"`, `kind: \"jwt\"`, etc).\n *\n * Not part of the public surface. Consumed by `baerlyWorker` /\n * `baerlyNode` resolution; the operator-facing API is the typed\n * `auth: \"none\"` field on `BaerlyAppConfig`.\n *\n * @internal\n */\nexport const noAuthVerifier = (tenantPrefix: string): Verifier => {\n return async () => ({ tenantPrefix, identity: { kind: \"none\" } });\n};\n","import {\n type BaerlyAppConfig,\n BaerlyError,\n NO_AUTH_CONFIGURED_MESSAGE,\n SHARED_SECRET_MISSING_MESSAGE,\n type Verifier,\n} from \"@baerly/protocol\";\nimport { sharedSecret } from \"../presets/shared-secret.ts\";\nimport { noAuthVerifier } from \"./none-verifier.ts\";\n\n/**\n * Read env var lazily via a host-supplied accessor so the same\n * resolver works in CF Workers (env binding) and Node\n * (`process.env`). Returns `undefined` for an unset OR empty string —\n * both branches mean \"operator forgot to set it\".\n */\ntype EnvAccessor = (name: string) => string | undefined;\n\n/**\n * Inputs to {@link resolveVerifier}. `factoryVerifier` is the\n * adapter-factory `verifier:` option (may be undefined). `config`\n * carries the typed `auth` posture + the `tenant` pin. `readEnv`\n * is the per-host env accessor.\n */\nexport interface ResolveVerifierInput {\n readonly factoryVerifier: Verifier | undefined;\n readonly config: BaerlyAppConfig;\n readonly readEnv: EnvAccessor;\n}\n\n/**\n * Resolve the per-request `Verifier` for an adapter factory using the\n * fixed order:\n *\n * 1. `factoryVerifier` set → use as-is (highest precedence; enables\n * env-aware construction via `cloudflareAccess(env)` etc).\n * 2. else `config.auth === \"shared-secret\"` → read `SHARED_SECRET`\n * via `readEnv`; throw `BaerlyError(\"InvalidConfig\",\n * SHARED_SECRET_MISSING_MESSAGE)` when unset/empty; else build\n * `sharedSecret({ secret, tenantPrefix: config.tenant })`.\n * 3. else `config.auth === \"none\"` → `noAuthVerifier(config.tenant)`.\n * 4. else → throw `BaerlyError(\"InvalidConfig\",\n * NO_AUTH_CONFIGURED_MESSAGE)`.\n *\n * Pure function — no I/O, no side effects beyond `sharedSecret`'s\n * own validation. Caller invokes once at adapter init time (or on\n * first fetch, depending on platform `await`-at-top-level\n * constraints).\n *\n * @throws BaerlyError code=\"InvalidConfig\" — branches 2 and 4 above.\n *\n * @internal\n */\nexport const resolveVerifier = (input: ResolveVerifierInput): Verifier => {\n if (input.factoryVerifier !== undefined) {\n return input.factoryVerifier;\n }\n if (input.config.auth === \"shared-secret\") {\n const secret = input.readEnv(\"SHARED_SECRET\");\n if (secret === undefined || secret.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", SHARED_SECRET_MISSING_MESSAGE);\n }\n return sharedSecret({ secret, tenantPrefix: input.config.tenant });\n }\n if (input.config.auth === \"none\") {\n return noAuthVerifier(input.config.tenant);\n }\n // Exhaustiveness backstop. The AuthConfig union is locked to\n // [\"none\", \"shared-secret\"]; reaching this branch means the caller\n // passed a config that has neither the typed field nor a factory\n // override. Same operator remediation as the type-level error.\n throw new BaerlyError(\"InvalidConfig\", NO_AUTH_CONFIGURED_MESSAGE);\n};\n","/**\n * `Collection<T>` factory. `Db.collection(name)` returns the result of\n * `makeCollection(ctx)` — a cheap, no-I/O handle. By-id mutations route\n * through dedicated runners: `insert` → `runInsert`,\n * `replace(id, doc)` → `runReplaceById`. `update(id, patch)` and\n * `delete(id)` forward to the predicate-form runners via a `byId`\n * wire — those Query verbs are genuinely bulk, so the by-id case is\n * just a one-row predicate.\n *\n * `Collection.insert(doc)` is the public insert path. The locked\n * `Query<T>` interface (`@baerly/protocol/src/collection-api.ts`) intentionally\n * does NOT declare `insert` — chainable inserts are out of scope.\n * For an inserted doc whose predicate-bound shape matters,\n * `db.collection(...).insert(...)` is the path; predicates are a read-\n * side concern.\n */\n\nimport {\n type Collection,\n type DocumentData,\n type OrderSpec,\n type PredicateWire,\n} from \"@baerly/protocol\";\nimport { makeQuery, runInsert, runReplaceById, type CollectionReadContext } from \"./query.ts\";\n\n/**\n * Build a `Collection<T>` bound to one `(tenant, collection)` read context.\n * Cheap: zero I/O, allocates one closure. Each modifier call returns\n * a FRESH `Query<T>` — calling `.where(p1)` and `.where(p2)` on the\n * same `Collection<T>` produces two independent chains.\n *\n * `.count()` shorthand defers to the empty-state `Query<T>.count()`\n * so the fold logic lives in one place.\n *\n * @example\n * ```ts\n * const collection = makeCollection<Ticket>({\n * storage,\n * collectionPrefix: \"app/tickets/tenant/acme/manifests/tickets\",\n * collectionName: \"tickets\",\n * });\n * const open = await collection.where({ status: \"open\" }).all();\n * ```\n *\n * @internal\n */\nexport const makeCollection = <T extends DocumentData>(\n ctx: CollectionReadContext,\n): Collection<T> => {\n // Empty seed state. Every modifier merges into a frozen copy.\n const seed = {\n wire: undefined as PredicateWire | undefined,\n order: undefined as OrderSpec<T> | undefined,\n limit: undefined as number | undefined,\n };\n // Kernel-internal `_id`-shaped wire. Bypasses `validateWire`\n // (which rejects top-level `_id`) by construction — the wire is\n // never wire-submitted; it short-circuits to `Map.get` via\n // `singleIdFromPredicate` inside `runRead`.\n const byId = (id: string) => ({\n ...seed,\n wire: { clauses: [{ op: \"eq\" as const, field: \"_id\", value: id }] } as PredicateWire,\n });\n return {\n name: ctx.collectionName,\n first: () => makeQuery<T>(ctx, seed).first(),\n all: () => makeQuery<T>(ctx, seed).all(),\n count: () => makeQuery<T>(ctx, seed).count(),\n get: (id) => makeQuery<T>(ctx, byId(id)).first(),\n where: (p) => makeQuery<T>(ctx, seed).where(p),\n order: (s) => makeQuery<T>(ctx, { ...seed, order: s }),\n limit: (n) => makeQuery<T>(ctx, { ...seed, limit: n }),\n /**\n * Insert one document. UUIDv7 auto-id when `_id` is absent or\n * empty; otherwise the caller-supplied `_id` is honoured. A\n * pre-commit existence check against the materialised collection\n * surfaces `Conflict` on duplicate `_id` without round-tripping\n * to the writer — matches the locked `Collection.insert` throws\n * contract (`@baerly/protocol/src/collection-api.ts`).\n *\n * Single-attempt per call: CAS retries (up to 8 attempts) live\n * inside `Writer.commit()`. On retry-budget exhaustion the\n * writer throws `Conflict` and we surface unchanged.\n *\n * @throws BaerlyError code=\"Conflict\" — `_id` collision (pre-commit\n * check) or CAS retry budget exhausted.\n * @throws BaerlyError code=\"SchemaError\" — from the per-collection\n * `SchemaValidator` threaded via {@link Db.collectionReadContext}.\n */\n insert: (doc) => runInsert<T>(ctx, doc),\n update: (id, patch) => makeQuery<T>(ctx, byId(id)).update(patch),\n replace: (id, doc) => runReplaceById<T>(ctx, id, doc),\n delete: (id) => makeQuery<T>(ctx, byId(id)).delete(),\n };\n};\n","import {\n type BaerlyConfig,\n BaerlyError,\n type Collection,\n type CollectionNames,\n type CurrentJsonRead,\n decodeJsonBytes,\n type DocumentData,\n type IndexDefinition,\n logObjectKey,\n type LogEntry,\n readCurrentJson,\n type RowOf,\n type SchemaValidator,\n type Storage,\n type UnboundConfig,\n} from \"@baerly/protocol\";\nimport { collectionsToMaps } from \"./config.ts\";\nimport { probeTailFrom } from \"./log-tail.ts\";\nimport { assertPathSegment } from \"./path-segment.ts\";\nimport type { CollectionReadContext } from \"./query.ts\";\nimport { makeCollection } from \"./collection.ts\";\n\n/**\n * Physical-key prefix for a `(app, tenant)` pair. Trailing slash is\n * part of the prefix so a caller's `list(\"\")` resolves to\n * `list(\"app/<app>/tenant/<tenant>/\")` and cannot enumerate a sibling\n * tenant whose name shares a prefix.\n */\nconst physicalPrefixFor = (app: string, tenant: string): string => `app/${app}/tenant/${tenant}/`;\n\n/**\n * Runtime entry point. One `Db` per `(app, tenant)` request.\n *\n * Construct via {@link Db.create} — the constructor is private so\n * callers don't accidentally bypass validation.\n *\n * **Collection provisioning.** `Db` provisions collections implicitly on\n * the first commit — the writer auto-creates the per-collection\n * `current.json` manifest with a zero-state seed, costing one extra\n * Class A PUT on the very first write per collection and zero\n * thereafter. There is no `ensureCollection` method on this class. For\n * eager pre-warm (seed scripts, deploy-time provisioning, CI fixtures\n * that want byte-identical bytes before the first request), use\n * {@link \"@gusto/baerly-storage/dev\".ensureTable}.\n *\n * @example\n * ```ts\n * import { Db } from \"@gusto/baerly-storage\";\n * import { MemoryStorage } from \"@gusto/baerly-storage\";\n *\n * const db = Db.create({\n * storage: new MemoryStorage(),\n * app: \"tickets\",\n * tenant: \"acme-co\",\n * });\n *\n * await db.collection(\"tickets\").insert({ title: \"first ticket\", status: \"open\" });\n * const open = await db.collection(\"tickets\").where({ status: \"open\" }).all();\n * ```\n *\n * @remarks\n * **Anti-patterns** (TS compile errors, not runtime rejections):\n * - `db.collection(name).insertOne({...})` / `.insert({...})` —\n * the Mongo verb. Use `.insert(row)` (returns `{ _id }`).\n * - `db.collection(name).findOne({...})` / `.find({...})` —\n * the Mongo read verbs. Use `.get(id)` for by-id reads and\n * `.where({...}).first()` / `.all()` for predicate reads.\n * - `db.collection(name).aggregate([...])` — no pipeline stage\n * model. Compose via `.where().order().limit()` modifiers.\n * - Raw SQL strings of any shape. The kernel has no SQL parser.\n */\nexport class Db<TConfig extends BaerlyConfig = UnboundConfig> {\n readonly app: string;\n readonly tenant: string;\n /**\n * Underlying `Storage`, captured so the collection API can issue reads\n * using physical keys directly.\n */\n readonly #storage: Storage;\n /**\n * Per-collection {@link SchemaValidator}s threaded onto every\n * {@link CollectionReadContext} this `Db` mints. Empty map means \"no\n * validation declared\" — every write proceeds at zero overhead.\n *\n * Derived from `config.collections[*].schema` via\n * {@link collectionsToMaps} at {@link Db.create} time.\n */\n readonly #schemas: ReadonlyMap<string, SchemaValidator>;\n /**\n * Per-collection {@link IndexDefinition}s threaded onto every\n * {@link CollectionReadContext} this `Db` mints. Empty map means \"no\n * indexes declared\" — every read falls through to the snapshot +\n * log fold path.\n *\n * Derived from `config.collections[*].indexes` via\n * {@link collectionsToMaps} at {@link Db.create} time.\n */\n readonly #indexes: ReadonlyMap<string, ReadonlyArray<IndexDefinition>>;\n\n private constructor(\n app: string,\n tenant: string,\n storage: Storage,\n schemas: ReadonlyMap<string, SchemaValidator>,\n indexes: ReadonlyMap<string, ReadonlyArray<IndexDefinition>>,\n ) {\n this.app = app;\n this.tenant = tenant;\n this.#storage = storage;\n this.#schemas = schemas;\n this.#indexes = indexes;\n }\n\n /**\n * Build a tenant-scoped `Db`. Throws\n * `BaerlyError{code:\"InvalidConfig\"}` if either `app` or `tenant`\n * is empty, contains `/`, is `\".\"` or `\"..\"`, contains control\n * characters, starts with the reserved `\"_\"` prefix, or exceeds\n * 256 bytes.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `app` or `tenant` is\n * empty, contains `/`, is `\".\"` or `\"..\"`, contains control\n * characters, starts with the reserved `\"_\"` prefix, or exceeds\n * 256 bytes.\n *\n * @example\n * ```ts\n * const db = Db.create({ storage, app: \"tickets\", tenant: \"acme\" });\n * await db.collection(\"tickets\").insert({ title: \"hi\" });\n * ```\n */\n static create<TConfig extends BaerlyConfig = UnboundConfig>(config: {\n storage: Storage;\n app: string;\n tenant: string;\n /**\n * Optional. Pass the value returned by {@link defineConfig} from\n * your `baerly.config.ts`. Two things happen:\n *\n * 1. **Types.** `db.collection(name)` narrows `name` to declared\n * collection names and infers the row type from\n * `collections[name].schema` via {@link RowOf}.\n * 2. **Runtime.** Schemas and indexes are derived from\n * `config.collections` via {@link collectionsToMaps}. Schema\n * validation and index routing are wired automatically — no\n * second hand-off step.\n *\n * @example\n * ```ts\n * import config from \"../baerly.config.ts\";\n * const db = Db.create({\n * storage: new MemoryStorage(),\n * app: \"helpdesk\",\n * tenant: \"test\",\n * config,\n * });\n * // db.collection(\"tickets\") is typed AND validates writes against\n * // the schema declared in baerly.config.ts.\n * ```\n */\n config?: TConfig;\n }): Db<TConfig> {\n const { storage, app, tenant } = config;\n assertKeySegment(app, \"app\", \"Db.create\");\n assertKeySegment(tenant, \"tenant\", \"Db.create\");\n // Always derive runtime maps from `config.collections`. Absent\n // config ⇒ empty maps (no schemas, no indexes); the kernel\n // behaves the same as a config with `collections: {}`.\n const derived =\n config.config !== undefined ? collectionsToMaps(config.config.collections) : undefined;\n return new Db<TConfig>(\n app,\n tenant,\n storage,\n derived?.schemas ?? new Map(),\n derived?.indexes ?? new Map(),\n );\n }\n\n /**\n * Typed handle for a single collection. Cheap; creates no I/O. Same\n * `name` returns a FRESH `Collection<T>` object on each call (chain\n * identity is intentional — modifiers return new objects).\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `name` is empty,\n * contains `/`, is `\".\"` or `\"..\"`, contains control characters,\n * starts with the reserved `\"_\"` prefix, or exceeds 256 bytes.\n *\n * @example\n * ```ts\n * // With a baerly.config.ts bound via Db.create({..., config}),\n * // db.collection(name) infers the row type from the declared schema —\n * // no <Ticket> generic needed.\n * const open = await db.collection(\"tickets\")\n * .where({ status: \"open\" })\n * .order({ commit_ts: \"desc\" })\n * .limit(50)\n * .all();\n * ```\n */\n // One signature. When `TConfig` extends `UnboundConfig`,\n // `CollectionNames<UnboundConfig>` widens to `string` so kernel-internal\n // paths against `Db<UnboundConfig>` still resolve without a separate\n // untyped overload. The impl signature stays widened (`Collection<any>`)\n // — the runtime never narrows; `makeCollection<DocumentData>` builds a\n // single row-agnostic handle and TypeScript handles the rest at the\n // call site.\n collection<N extends CollectionNames<TConfig>>(\n name: N,\n ): Collection<RowOf<TConfig, N> & DocumentData>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- impl signature must be wider than the public overload; with Predicate<T> typed, Collection<DocumentData> is no longer assignable to Collection<RowOf<...>&DocumentData> due to contravariance on where(). `any` widens correctly.\n collection(name: string): Collection<any> {\n return makeCollection<DocumentData>(this.collectionReadContext(name));\n }\n\n /**\n * Build a freshly-seeded {@link CollectionReadContext} for `name`. The\n * HTTP router uses this so it can drive `runAllWithMeta` directly\n * (the return shape carries the manifest-pointer cursor used to\n * pack `_meta` onto the read response envelope). Application\n * callers should keep using\n * {@link Db.collection}; the chainable terminals destructure the cursor\n * out and discard it to keep the locked `Query<T>` signature.\n *\n * Runs the same `name`-validation guard as {@link Db.collection}.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `name` is empty,\n * contains `/`, is `\".\"` or `\"..\"`, contains control characters,\n * starts with the reserved `\"_\"` prefix, or exceeds 256 bytes.\n * @internal\n */\n collectionReadContext(name: string): CollectionReadContext {\n assertKeySegment(name, \"collection\", \"Db.collection\");\n const schema = this.#schemas.get(name);\n return {\n storage: this.#storage,\n collectionPrefix: `${physicalPrefixFor(this.app, this.tenant)}manifests/${name}`,\n collectionName: name,\n indexes: this.#indexes.get(name) ?? [],\n ...(schema !== undefined ? { schema } : {}),\n };\n }\n\n /**\n * Read + parse this `Db`'s `manifests/<collection>/current.json`. Returns\n * `null` when the collection has not been provisioned yet (no\n * `current.json` exists). Throws `BaerlyError{code:\"InvalidResponse\"}`\n * on a malformed body — same contract as the underlying\n * {@link readCurrentJson} helper in `@baerly/protocol`.\n *\n * Backs the `/v1/since` long-poll handler in\n * `packages/server/src/http/since.ts`; that handler needs the parsed\n * `CurrentJson` plus an ETag for the follow-up reads.\n *\n * @internal — typed seam for the HTTP handler; app code should use\n * the collection API.\n */\n async getCurrentJson(\n collection: string,\n opts?: { signal?: AbortSignal },\n ): Promise<CurrentJsonRead | null> {\n // Defensive at the db layer so ALL callers are covered — including\n // the `/v1/since` handler, whose only inline screen catches empty /\n // `/` and lets `..` / control bytes through into this key.\n assertPathSegment(collection, \"collection\");\n const key = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}/current.json`;\n return readCurrentJson(this.#storage, key, opts);\n }\n\n /**\n * Read + parse one `LogEntry` by `seq` from\n * `manifests/<collection>/log/<seq>.json`. Returns `null`\n * when the entry is missing — this typically means the GC sweeper\n * deleted the entry between a `readCurrentJson` and this GET (the\n * `/v1/since` handler treats the race as silent and skips the\n * entry). Throws `BaerlyError{code:\"InvalidResponse\"}` on a body\n * that isn't valid JSON.\n *\n * @internal — typed seam for the HTTP handler; app code should use\n * the collection API.\n */\n async getLogEntry(\n collection: string,\n seq: number,\n opts?: { signal?: AbortSignal },\n ): Promise<LogEntry | null> {\n // Defensive at the db layer so ALL callers are covered — same\n // rationale as `getCurrentJson`; the `/v1/since` poll reaches here.\n assertPathSegment(collection, \"collection\");\n const key = logObjectKey(\n `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`,\n seq,\n );\n const got = await this.#storage.get(key, opts);\n if (got === null) {\n return null;\n }\n let parsed: unknown;\n try {\n parsed = decodeJsonBytes(got.body);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `log entry at ${key}: body is not valid JSON`,\n error,\n );\n }\n return parsed as LogEntry;\n }\n\n /**\n * Forward-probe the TRUE committed log tail from `hint` (a lower\n * bound, typically `tail_hint`). Backs the `/v1/since` end-bound.\n *\n * @internal — typed seam for the HTTP handler.\n */\n async probeLogTail(\n collection: string,\n hint: number,\n opts?: { signal?: AbortSignal },\n ): Promise<number> {\n assertPathSegment(collection, \"collection\");\n const logPrefix = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`;\n const { tail } = await probeTailFrom(this.#storage, logPrefix, hint, opts);\n return tail;\n }\n}\n\n/**\n * Guard a string used as a path-segment in the bucket-key encoding.\n * Routes through the single shared {@link assertPathSegment} rule\n * (empty / `\"/\"` / `\".\"`|`\"..\"` / C0-C1 control / leading `\"_\"` (ADR-003) /\n * overlong), all as `BaerlyError{code:\"InvalidConfig\"}`. `role` and `verb`\n * are baked into the message so the caller doesn't need to format their own.\n *\n * Used by {@link Db.create} (twice — `app`, `tenant`) and\n * {@link Db.collectionReadContext} (once — `name`).\n *\n * @internal\n */\nconst assertKeySegment = (value: string, role: string, verb: string): void => {\n assertPathSegment(value, role, verb);\n};\n"],"mappings":";;;;;;;;AAaA,MAAa,eAAe;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAUA,MAAa,iBAAiB,QAAqD;CAGjF,MAAM,QAAQ,IAAI,SAAS,QAAQ,MAAM,IAAI,UAAU;CACvD,OACE,IAAI,gBAAgB,gBAAiB,CAAC,QAAQ,aAAa,MAAM,OAAO,IAAI,MAAM,QAAQ,EAAE;AAEhG;;;ACpBA,MAAM,cAAc,IAAI,YAAY;AAEpC,MAAM,uBAAuB;AAI7B,MAAM,uBACH,WAA0E,SAAS,OAAO,CAAC;AAE9F,IAAI,8BAA8B;AAKlC,MAAM,0BAA0B,kBAAiC;CAC/D,MAAM,MAAM,eAAe;CAC3B,IAAI,CAAC,cAAc,GAAG,GACpB;CAEF,IAAI,CAAC,iBAAiB,IAAI,0BAA0B,QAClD,MAAM,IAAI,YACR,iBACA,iQAEwE,qBAAqB,OAC/F;CAEF,IAAI,CAAC,6BAA6B;EAChC,8BAA8B;EAC9B,QAAQ,KACN,qFACF;CACF;AACF;;;;;;;;;;;AAsBA,MAAM,mBAAmB,GAAW,MAAsB;CACxD,MAAM,KAAK,YAAY,OAAO,CAAC;CAC/B,MAAM,KAAK,YAAY,OAAO,CAAC;CAC/B,MAAM,IAAI,KAAK,IAAI,GAAG,QAAQ,GAAG,MAAM;CACvC,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,GAAG,OAAO,GAAG,IACf,OAA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KE,SAAS,IAAI,IAAI,KAAK,CAAC;GACrC,GAAI,WAAW,KAAA,IAAY,EAAE,OAAO,IAAI,CAAC;EAC3C;CACF;;;;;;;;;;;;;;;CAgBA,MAAM,eACJ,YACA,MACiC;EAIjC,kBAAkB,YAAY,YAAY;EAC1C,MAAM,MAAM,GAAG,kBAAkB,KAAK,KAAK,KAAK,MAAM,EAAE,YAAY,WAAW;EAC/E,OAAO,gBAAgB,KAAKF,UAAU,KAAK,IAAI;CACjD;;;;;;;;;;;;;CAcA,MAAM,YACJ,YACA,KACA,MAC0B;EAG1B,kBAAkB,YAAY,YAAY;EAC1C,MAAM,MAAM,aACV,GAAG,kBAAkB,KAAK,KAAK,KAAK,MAAM,EAAE,YAAY,cACxD,GACF;EACA,MAAM,MAAM,MAAM,KAAKA,SAAS,IAAI,KAAK,IAAI;EAC7C,IAAI,QAAQ,MACV,OAAO;EAET,IAAI;EACJ,IAAI;GACF,SAAS,gBAAgB,IAAI,IAAI;EACnC,SAAS,OAAO;GACd,MAAM,IAAI,YACR,mBACA,gBAAgB,IAAI,2BACpB,KACF;EACF;EACA,OAAO;CACT;;;;;;;CAQA,MAAM,aACJ,YACA,MACA,MACiB;EACjB,kBAAkB,YAAY,YAAY;EAC1C,MAAM,YAAY,GAAG,kBAAkB,KAAK,KAAK,KAAK,MAAM,EAAE,YAAY;EAC1E,MAAM,EAAE,SAAS,MAAM,cAAc,KAAKA,UAAU,WAAW,MAAM,IAAI;EACzE,OAAO;CACT;AACF;;;;;;;;;;;;;AAcA,MAAM,oBAAoB,OAAe,MAAc,SAAuB;CAC5E,kBAAkB,OAAO,MAAM,IAAI;AACrC"}
@@ -1,6 +1,7 @@
1
- import { t as __commonJSMin } from "./chunk-EAsCxrDo.js";
2
- import { n as createCurrentJson } from "./current-json-DsN7FNY1.js";
3
- import { t as BaerlyError } from "./errors-DOdL95kK.js";
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";
4
5
  import { createHash } from "node:crypto";
5
6
  import { link, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
6
7
  import { tmpdir } from "node:os";
@@ -339,7 +340,7 @@ var LocalFsStorage = class {
339
340
  * `BaerlyError("InvalidConfig", …)`.
340
341
  */
341
342
  #pathFor(key) {
342
- if (key.length === 0) throw new BaerlyError("InvalidConfig", "LocalFsStorage: empty key");
343
+ assertValidStorageKey(key);
343
344
  if (key.startsWith("/")) throw new BaerlyError("InvalidConfig", `LocalFsStorage: leading "/" in key: ${key}`);
344
345
  if (key.includes("\\")) throw new BaerlyError("InvalidConfig", `LocalFsStorage: backslash in key: ${key}`);
345
346
  const segments = key.split("/");
@@ -388,4 +389,4 @@ const walk = async (root, out) => {
388
389
  //#endregion
389
390
  export { require_picocolors_browser as a, printDevBanner as i, ensureTable as n, renderDevLanding as r, LocalFsStorage as t };
390
391
 
391
- //# sourceMappingURL=src-CWpkSbvJ.js.map
392
+ //# sourceMappingURL=src-DYZ4H1aF.js.map
@@ -0,0 +1 @@
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,S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C,IAAI;CAC7B,OAAO,MAAM,SAAS,GAAG;EACvB,MAAM,MAAM,MAAM,IAAI;EACtB,IAAI;EACJ,IAAI;GACF,UAAU,MAAM,QAAQ,KAAK,EAAE,eAAe,KAAK,CAAC;EACtD,SAAS,OAAO;GACd,IAAI,iBAAiB,KAAK,KAAK,MAAM,SAAS,UAC5C;GAEF,MAAM;EACR;EACA,KAAK,MAAM,SAAS,SAAS;GAC3B,MAAM,OAAO,KAAK,KAAK,MAAM,IAAI;GACjC,IAAI,MAAM,YAAY,GACpB,MAAM,KAAK,IAAI;QACV,IAAI,MAAM,OAAO,KAAK,CAAC,MAAM,KAAK,WAAW,WAAW,GAG7D,IAAI,KAAK,SAAS,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,MAAM,GAAG,CAAC;EAE5D;CACF;AACF"}
@@ -1,10 +1,10 @@
1
- import { t as loadAppConfig } from "./config-CGyBopy3.js";
1
+ import { t as loadAppConfig } from "./config-1tv0-Yzm.js";
2
2
  import { a as setJsonMode, c as parseArgs, n as emitError, o as BaerlyError, s as defineCommand } from "./baerly.js";
3
3
  import "node:stream";
4
4
  //#region ../server/src/names.ts
5
- /** Reject names in the system-reserved leading-"_" namespace. See docs/adr/007-layout-versioning-cordon.md. */
5
+ /** Reject names in the system-reserved leading-"_" namespace. See docs/adr/003-layout-versioning-cordon.md. */
6
6
  const assertNameNotReserved = (name, context) => {
7
- if (name.startsWith("_")) throw new BaerlyError("InvalidConfig", `${context}: "${name}" is reserved — names beginning with "_" are reserved for system use. See docs/adr/007-layout-versioning-cordon.md.`);
7
+ if (name.startsWith("_")) throw new BaerlyError("InvalidConfig", `${context}: "${name}" is reserved — names beginning with "_" are reserved for system use. See docs/adr/003-layout-versioning-cordon.md.`);
8
8
  };
9
9
  const utf8 = new TextEncoder();
10
10
  const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/;
@@ -12,7 +12,7 @@ const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/;
12
12
  * The single validation rule for every caller-controlled key segment
13
13
  * (`_id`, `collection`, `app`, `tenant`) before it becomes a written
14
14
  * key segment or `LocalFsStorage` path. Rejects empty / `"/"` /
15
- * `"."`|`".."` / C0-C1 control / leading `"_"` (ADR-007) / `> MAX_SEGMENT_BYTES`,
15
+ * `"."`|`".."` / C0-C1 control / leading `"_"` (ADR-003) / `> MAX_SEGMENT_BYTES`,
16
16
  * all as `BaerlyError{code:"InvalidConfig"}`.
17
17
  *
18
18
  * @param role human label for the segment ("_id" | "collection" | "app" | "tenant").
@@ -29,6 +29,44 @@ const assertPathSegment = (value, role, verb = "") => {
29
29
  };
30
30
  //#endregion
31
31
  //#region src/subcommand.ts
32
+ /**
33
+ * Shared citty arg fragments for the flags every operator command
34
+ * takes with identical wording. Each subcommand spreads the ones it
35
+ * needs into its own `... as const satisfies ArgsDef` literal, so the
36
+ * `--bucket` / `--app` / `--tenant` / `--collection` / `--json`
37
+ * descriptions can't drift copy-to-copy (they did: `--collection` had
38
+ * both "Collection name" and "Collection name." variants). Bespoke
39
+ * flags (`--config`, `--indexes`, `--provider`, `--verbose`, …) stay
40
+ * inline in the command that owns them.
41
+ */
42
+ const BUCKET_ARG = {
43
+ type: "string",
44
+ required: true,
45
+ description: "Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)",
46
+ valueHint: "bucket-uri"
47
+ };
48
+ const APP_ARG = {
49
+ type: "string",
50
+ required: false,
51
+ description: "Application name segment (defaults to baerly.config.ts).",
52
+ valueHint: "app"
53
+ };
54
+ const TENANT_ARG = {
55
+ type: "string",
56
+ required: false,
57
+ description: "Tenant name segment (defaults to baerly.config.ts).",
58
+ valueHint: "tenant"
59
+ };
60
+ const COLLECTION_ARG = {
61
+ type: "string",
62
+ required: true,
63
+ description: "Collection name.",
64
+ valueHint: "name"
65
+ };
66
+ const JSON_ARG = {
67
+ type: "boolean",
68
+ description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
69
+ };
32
70
  /** Shared exit-code mapping for caught `BaerlyError`s. */
33
71
  const errorToExitCode = (code) => {
34
72
  if (code === "InvalidConfig") return 1;
@@ -154,6 +192,6 @@ const defineBaerlySubcommand = (def) => {
154
192
  };
155
193
  };
156
194
  //#endregion
157
- export { assertNameNotReserved as i, defineBaerlySubcommand as n, assertPathSegment as r, assertCollectionArg as t };
195
+ export { TENANT_ARG as a, assertPathSegment as c, JSON_ARG as i, assertNameNotReserved as l, BUCKET_ARG as n, assertCollectionArg as o, COLLECTION_ARG as r, defineBaerlySubcommand as s, APP_ARG as t };
158
196
 
159
- //# sourceMappingURL=subcommand-CP9NY2J4.js.map
197
+ //# sourceMappingURL=subcommand-DoDA-K7d.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subcommand-DoDA-K7d.js","names":[],"sources":["../packages/server/src/names.ts","../packages/server/src/path-segment.ts","../packages/cli/src/subcommand.ts"],"sourcesContent":["import { BaerlyError } from \"@baerly/protocol\";\n\n/** Reject names in the system-reserved leading-\"_\" namespace. See docs/adr/003-layout-versioning-cordon.md. */\nexport const assertNameNotReserved = (name: string, context: string): void => {\n if (name.startsWith(\"_\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${context}: \"${name}\" is reserved — names beginning with \"_\" are reserved for system use. See docs/adr/003-layout-versioning-cordon.md.`,\n );\n }\n};\n","import { BaerlyError } from \"@baerly/protocol\";\nimport { assertNameNotReserved } from \"./names.ts\";\n\n/**\n * Per-segment byte ceiling. S3 and R2 cap a full object key at 1024\n * UTF-8 bytes; a key is several segments, so this 256 leaves real prefix\n * headroom. The assembled multi-segment key sum is bounded separately on\n * the write path, not here. This is an intentional server-local *policy*\n * value (not the protocol-level S3/R2 fact `MAX_KEY_BYTES = 1024` in\n * `@baerly/protocol`'s `constants.ts`); it lives here, co-located with the\n * one rule that uses it, to keep `protocol/constants.ts` out of the\n * validator's bundle closure.\n */\nexport const MAX_SEGMENT_BYTES = 256;\nconst utf8 = new TextEncoder();\n// C0 (U+0000-U+001F) + DEL/C1 (U+007F-U+009F).\n// eslint-disable-next-line no-control-regex -- intentional control-char class\nconst CONTROL_CHARS = /[\\u0000-\\u001f\\u007f-\\u009f]/;\n\n/**\n * The single validation rule for every caller-controlled key segment\n * (`_id`, `collection`, `app`, `tenant`) before it becomes a written\n * key segment or `LocalFsStorage` path. Rejects empty / `\"/\"` /\n * `\".\"`|`\"..\"` / C0-C1 control / leading `\"_\"` (ADR-003) / `> MAX_SEGMENT_BYTES`,\n * all as `BaerlyError{code:\"InvalidConfig\"}`.\n *\n * @param role human label for the segment (\"_id\" | \"collection\" | \"app\" | \"tenant\").\n * @param verb optional calling-context label for the message.\n */\nexport const assertPathSegment = (value: string, role: string, verb = \"\"): void => {\n const where = verb === \"\" ? role : `${verb}: ${role}`;\n if (value.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", `${where} must be a non-empty string`);\n }\n if (value.includes(\"/\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${where} may not contain \"/\": ${JSON.stringify(value)}`,\n );\n }\n if (value === \".\" || value === \"..\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${where} may not be \".\" or \"..\": ${JSON.stringify(value)}`,\n );\n }\n if (CONTROL_CHARS.test(value)) {\n throw new BaerlyError(\"InvalidConfig\", `${where} may not contain control characters`);\n }\n if (utf8.encode(value).length > MAX_SEGMENT_BYTES) {\n throw new BaerlyError(\"InvalidConfig\", `${where} is too long (> ${MAX_SEGMENT_BYTES} bytes)`);\n }\n // Leading `_` is the ADR-003 reserved namespace.\n assertNameNotReserved(value, where);\n};\n","/**\n * Shared subcommand scaffolding for `baerly`.\n *\n * Every operator-facing subcommand (`inspect`, `export`, `doctor`, and\n * every `admin/*` command) was independently re-implementing the same\n * five pieces of boilerplate:\n *\n * 1. `setJsonMode(args.json === true)` before any emission.\n * 2. A `KNOWN_KEYS` whitelist asserting unknown `--flag` rejection.\n * 3. An `errorToExitCode(code)` mapping —\n * `InvalidConfig → 1`, `Conflict|Internal|InvalidResponse → 3`,\n * else `2`.\n * 4. `resolveAppTenant(args)` falling back through `baerly.config.*`\n * to either real values or hard-coded `\"app\"` / `\"tenant\"`\n * literals.\n * 5. Two parallel entry points: a citty `defineCommand` block that\n * calls `process.exit(code)` on failure, and a `runXxx(argv)`\n * function for in-process tests that returns the exit code.\n *\n * The five copies drifted: some commands suppressed protocol-level\n * errors (no `Conflict|Internal|InvalidResponse → 3` arm), and the\n * config-fallback silently produced `\"app\"` / `\"tenant\"` literals\n * (confidently-wrong output when no config is present).\n *\n * {@link defineBaerlySubcommand} centralizes the five pieces:\n * - Computes the known-keys set from `Object.keys(args)` itself, so\n * a new flag is picked up automatically.\n * - Applies the full 3-bucket exit-code mapping uniformly.\n * - {@link SubcommandContext.resolveAppTenant} throws\n * `BaerlyError(\"InvalidConfig\", …)` with a `--app` / `--tenant`\n * hint when neither flags nor a loadable `baerly.config.*` supply\n * the values.\n * - Returns a bundle of {@link SubcommandBundle.cmd} (citty wiring)\n * and {@link SubcommandBundle.run} (test entry) sharing one\n * wrapped handler.\n */\n\nimport { type Readable, type Writable } from \"node:stream\";\nimport { defineCommand, parseArgs, type ArgsDef, type ParsedArgs, type CommandDef } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { assertPathSegment } from \"@baerly/server/_internal/testing\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { emitError, setJsonMode } from \"./output.ts\";\n\n/**\n * Shared citty arg fragments for the flags every operator command\n * takes with identical wording. Each subcommand spreads the ones it\n * needs into its own `... as const satisfies ArgsDef` literal, so the\n * `--bucket` / `--app` / `--tenant` / `--collection` / `--json`\n * descriptions can't drift copy-to-copy (they did: `--collection` had\n * both \"Collection name\" and \"Collection name.\" variants). Bespoke\n * flags (`--config`, `--indexes`, `--provider`, `--verbose`, …) stay\n * inline in the command that owns them.\n */\nexport const BUCKET_ARG = {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n} as const;\n\nexport const APP_ARG = {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n} as const;\n\nexport const TENANT_ARG = {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n} as const;\n\nexport const COLLECTION_ARG = {\n type: \"string\",\n required: true,\n description: \"Collection name.\",\n valueHint: \"name\",\n} as const;\n\nexport const JSON_ARG = {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n} as const;\n\n/**\n * Optional stdin / stdout streams that a programmatic caller (today:\n * `runDump` / `runRestore` tests, and the export round-trip\n * integration test) can divert in place of `process.stdin` /\n * `process.stdout`. The citty entry point always uses the process\n * streams; only {@link SubcommandBundle.run} accepts these overrides.\n */\nexport interface SubcommandStreams {\n readonly stdin?: Readable;\n readonly stdout?: Writable;\n}\n\n/**\n * Capabilities the subcommand handler receives. Today: app/tenant\n * resolution. Kept narrow so the handler signature stays load-bearing\n * (the helper isn't a god object).\n */\ninterface SubcommandContext {\n /**\n * Returns `{ app, tenant }` resolved from explicit flags or\n * `baerly.config.{ts,js,mjs,json}` in the cwd.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — neither flag was\n * supplied AND no loadable config was found. The error message\n * includes a hint mentioning `--app` / `--tenant`.\n */\n readonly resolveAppTenant: (args: {\n readonly app?: string;\n readonly tenant?: string;\n }) => Promise<{ app: string; tenant: string }>;\n /**\n * Programmatic stdin / stdout overrides. `undefined` (or any\n * missing field) means \"use the process stream\". Only\n * `admin dump` / `admin restore` consume this; other commands\n * ignore the field.\n */\n readonly streams?: SubcommandStreams;\n}\n\n/**\n * Definition fed to {@link defineBaerlySubcommand}. `name` is the JSON\n * envelope tag (`\"inspect\"`, `\"admin.compact\"`, etc.); `args` is the\n * citty ArgsDef; `handler` returns the integer exit code.\n */\nexport interface SubcommandDef<TArgs extends ArgsDef> {\n /** JSON envelope `command` tag and the prefix of every emitted error. */\n readonly name: string;\n readonly meta: { readonly description: string };\n readonly args: TArgs;\n readonly handler: (args: ParsedArgs<TArgs>, ctx: SubcommandContext) => Promise<number>;\n}\n\n/**\n * Output of {@link defineBaerlySubcommand}. `cmd` plugs into\n * `subCommands` in `baerly.ts`; `run` is the in-process entry for\n * unit tests.\n */\nexport interface SubcommandBundle<TArgs extends ArgsDef> {\n readonly cmd: CommandDef<TArgs>;\n readonly run: (\n argv: readonly string[],\n options?: { readonly streams?: SubcommandStreams },\n ) => Promise<number>;\n}\n\n/** Shared exit-code mapping for caught `BaerlyError`s. */\nconst errorToExitCode = (code: string): number => {\n if (code === \"InvalidConfig\") {\n return 1;\n }\n if (code === \"Conflict\" || code === \"Internal\" || code === \"InvalidResponse\") {\n return 3;\n }\n return 2;\n};\n\n/**\n * Validate a `--collection` arg through the same shared rule the\n * server uses for every caller-controlled key segment, before it is\n * interpolated into a bucket key. Throws `BaerlyError(\"InvalidConfig\",\n * …)` on a traversal / empty / control-char / reserved value. `verb`\n * is the operator-facing command name (e.g. `\"baerly admin restore\"`,\n * `\"baerly inspect\"`) so the message names the exact command.\n *\n * (app/tenant are validated at their own chokepoint inside\n * `resolveAppTenant`; this guards the per-command `collection` arg.)\n */\nexport const assertCollectionArg = (collection: string, verb: string): void => {\n assertPathSegment(collection, \"collection\", verb);\n};\n\n/**\n * Build the app/tenant resolver. Captures `name` to surface the\n * calling subcommand in the InvalidConfig hint.\n */\nconst makeResolveAppTenant = (name: string): SubcommandContext[\"resolveAppTenant\"] => {\n return async (args) => {\n const flagApp = typeof args.app === \"string\" && args.app.length > 0 ? args.app : undefined;\n const flagTenant =\n typeof args.tenant === \"string\" && args.tenant.length > 0 ? args.tenant : undefined;\n let app: string;\n let tenant: string;\n if (flagApp !== undefined && flagTenant !== undefined) {\n app = flagApp;\n tenant = flagTenant;\n } else {\n let cfg: { app: string; tenant: string };\n try {\n cfg = await loadAppConfig();\n } catch (error) {\n // Re-throw with our own wording so the operator sees the\n // calling-command name and the hint to pass --app / --tenant\n // explicitly. The underlying loadAppConfig error is preserved\n // as the cause. (Only wraps a config-LOAD failure — the\n // segment validation below is intentionally outside this catch\n // so its own InvalidConfig message survives.)\n const inner = error instanceof BaerlyError ? error.message : (error as Error).message;\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly ${name}: --app / --tenant not supplied and no baerly.config.{ts,js,mjs,json} in cwd (${inner})`,\n error,\n );\n }\n app = flagApp ?? cfg.app;\n tenant = flagTenant ?? cfg.tenant;\n }\n // Single chokepoint covering every command that calls\n // resolveAppTenant: whatever the source (flags or config), the\n // resolved segments must pass the same shared rule before they\n // become bucket-key segments. A bad-but-supplied value throws\n // InvalidConfig, consistent with the \"not supplied\" case above.\n assertPathSegment(app, \"app\", `baerly ${name}`);\n assertPathSegment(tenant, \"tenant\", `baerly ${name}`);\n return { app, tenant };\n };\n};\n\n/**\n * Wrap `def.handler` with the standard JSON-mode toggle, unknown-key\n * rejection, and error-to-exit-code mapping. Shared by both the citty\n * `run({ args })` path and the test `run(argv)` path. The caller\n * supplies the {@link SubcommandContext}; this lets each `run(argv)`\n * invocation attach its own `streams` override without leaking across\n * invocations.\n */\nconst kebabToCamel = (s: string): string => s.replace(/-(\\w)/g, (_, c: string) => c.toUpperCase());\n\nconst wrapHandler = <TArgs extends ArgsDef>(\n def: SubcommandDef<TArgs>,\n): ((args: ParsedArgs<TArgs>, ctx: SubcommandContext) => Promise<number>) => {\n // Compute the allow-list once from the ArgsDef. citty injects `_`\n // for positional captures, so it must stay allowed. citty 0.2.2\n // also auto-injects a camelCase alias for every kebab-case flag\n // (e.g. `--where-comment` produces both `whereComment` and\n // `where-comment` on the parsed args), so each kebab key is\n // expanded to its camelCase variant in the allow-list too.\n const allowedKeys: ReadonlySet<string> = new Set(\n Object.keys(def.args)\n .flatMap((k) => (k.includes(\"-\") ? [k, kebabToCamel(k)] : [k]))\n .concat([\"_\"]),\n );\n return async (args, ctx) => {\n // `json` is conventional but not required — only toggle when it's\n // both declared in the ArgsDef and truthy on the parsed args.\n if (\"json\" in def.args) {\n setJsonMode((args as ParsedArgs<TArgs> & { json?: boolean }).json === true);\n }\n try {\n for (const k of Object.keys(args)) {\n if (!allowedKeys.has(k)) {\n throw new BaerlyError(\"InvalidConfig\", `baerly ${def.name}: unknown flag --${k}`);\n }\n }\n return await def.handler(args, ctx);\n } catch (error) {\n if (error instanceof BaerlyError) {\n emitError(def.name, error.code, error.message);\n return errorToExitCode(error.code);\n }\n emitError(def.name, \"Unknown\", (error as Error).message);\n return 2;\n }\n };\n};\n\n/**\n * Wrap a baerly subcommand. Returns `{ cmd, run }` —\n * - `cmd` is a citty `defineCommand` block; mount it in\n * `baerly.ts`'s `subCommands`. It calls `process.exit(code)` on a\n * non-zero exit so the parent process surfaces the failure.\n * - `run(argv)` is the in-process test entry. It parses `argv` with\n * citty's `parseArgs`, dispatches through the same wrapped\n * handler, and returns the integer exit code (does NOT call\n * `process.exit`).\n *\n * The two paths share `wrapHandler` so JSON-mode toggling,\n * unknown-flag rejection, and error-to-exit-code mapping behave\n * identically.\n */\nexport const defineBaerlySubcommand = <TArgs extends ArgsDef>(\n def: SubcommandDef<TArgs>,\n): SubcommandBundle<TArgs> => {\n const resolveAppTenant = makeResolveAppTenant(def.name);\n const wrapped = wrapHandler(def);\n\n const cmd = defineCommand({\n meta: { name: def.name, description: def.meta.description },\n args: def.args,\n run: async ({ args }) => {\n const code = await wrapped(args as ParsedArgs<TArgs>, { resolveAppTenant });\n if (code !== 0) {\n process.exit(code);\n }\n },\n });\n\n const run = async (\n argv: readonly string[],\n options?: { readonly streams?: SubcommandStreams },\n ): Promise<number> => {\n let parsed: ParsedArgs<TArgs>;\n try {\n parsed = parseArgs<TArgs>(argv as string[], def.args);\n } catch (error) {\n // Parse-time error from citty (missing required flag,\n // malformed value). Toggle JSON mode by sniffing argv since\n // we never reached the handler.\n setJsonMode(argv.includes(\"--json\"));\n emitError(def.name, \"InvalidConfig\", (error as Error).message);\n return 1;\n }\n return wrapped(parsed, { resolveAppTenant, streams: options?.streams });\n };\n\n return { cmd, run };\n};\n"],"mappings":";;;;;AAGA,MAAa,yBAAyB,MAAc,YAA0B;CAC5E,IAAI,KAAK,WAAW,GAAG,GACrB,MAAM,IAAI,YACR,iBACA,GAAG,QAAQ,KAAK,KAAK,oHACvB;AAEJ;ACIA,MAAM,OAAO,IAAI,YAAY;AAG7B,MAAM,gBAAgB;;;;;;;;;;;AAYtB,MAAa,qBAAqB,OAAe,MAAc,OAAO,OAAa;CACjF,MAAM,QAAQ,SAAS,KAAK,OAAO,GAAG,KAAK,IAAI;CAC/C,IAAI,MAAM,WAAW,GACnB,MAAM,IAAI,YAAY,iBAAiB,GAAG,MAAM,4BAA4B;CAE9E,IAAI,MAAM,SAAS,GAAG,GACpB,MAAM,IAAI,YACR,iBACA,GAAG,MAAM,wBAAwB,KAAK,UAAU,KAAK,GACvD;CAEF,IAAI,UAAU,OAAO,UAAU,MAC7B,MAAM,IAAI,YACR,iBACA,GAAG,MAAM,2BAA2B,KAAK,UAAU,KAAK,GAC1D;CAEF,IAAI,cAAc,KAAK,KAAK,GAC1B,MAAM,IAAI,YAAY,iBAAiB,GAAG,MAAM,oCAAoC;CAEtF,IAAI,KAAK,OAAO,KAAK,CAAC,CAAC,SAAA,KACrB,MAAM,IAAI,YAAY,iBAAiB,GAAG,MAAM,2BAA4C;CAG9F,sBAAsB,OAAO,KAAK;AACpC;;;;;;;;;;;;;ACAA,MAAa,aAAa;CACxB,MAAM;CACN,UAAU;CACV,aAAa;CACb,WAAW;AACb;AAEA,MAAa,UAAU;CACrB,MAAM;CACN,UAAU;CACV,aAAa;CACb,WAAW;AACb;AAEA,MAAa,aAAa;CACxB,MAAM;CACN,UAAU;CACV,aAAa;CACb,WAAW;AACb;AAEA,MAAa,iBAAiB;CAC5B,MAAM;CACN,UAAU;CACV,aAAa;CACb,WAAW;AACb;AAEA,MAAa,WAAW;CACtB,MAAM;CACN,aAAa;AACf;;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types.ts
3
+ /**
4
+ * Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle
5
+ * `<UUID>crypto.randomUUID()` throughout the codebase.
6
+ */
7
+ const uuid = () => crypto.randomUUID();
8
+ /**
9
+ * Mint a UUIDv7 — 48-bit Unix-millis prefix + 74 bits of randomness,
10
+ * formatted as a standard 8-4-4-4-12 UUID string per RFC 9562 §5.7.
11
+ * Lex-sortable by mint time, so it pairs well with object-storage
12
+ * list semantics. Returns a branded {@link UUID}.
13
+ *
14
+ * Uses `crypto.getRandomValues` which is universally available
15
+ * (Node 19+, Workerd, Bun, browsers).
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * const id = uuidv7();
20
+ * // e.g. "01956cad-4cc8-7abc-9def-0123456789ab"
21
+ * ```
22
+ */
23
+ const uuidv7 = () => {
24
+ const millis = Date.now();
25
+ const rand = /* @__PURE__ */ new Uint8Array(10);
26
+ crypto.getRandomValues(rand);
27
+ rand[0] = rand[0] & 15 | 112;
28
+ rand[2] = rand[2] & 63 | 128;
29
+ const millisHex = millis.toString(16).padStart(12, "0");
30
+ const b = Array.from(rand, (n) => n.toString(16).padStart(2, "0")).join("");
31
+ return `${millisHex.slice(0, 8)}-${millisHex.slice(8, 12)}-${b.slice(0, 4)}-${b.slice(4, 8)}-${b.slice(8, 20)}`;
32
+ };
33
+ /**
34
+ * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).
35
+ * Uses `COUNT_BIT_WIDTH` (see `packages/protocol/src/constants.ts`) to
36
+ * produce an 11-char descending base-32 string with a domain of
37
+ * 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1).
38
+ *
39
+ * Used together with {@link timestamp} (the descending base-32
40
+ * encoding of millis-since-epoch). See {@link uint2strDesc} for the
41
+ * lex-reversal property both rely on.
42
+ */
43
+ const countKey = (number) => uint2strDesc(number, 53);
44
+ const uint2str = (num, bits) => {
45
+ const maxBase32Length = Math.ceil(bits / 5);
46
+ return num.toString(32).padStart(maxBase32Length, "0");
47
+ };
48
+ /**
49
+ * Lex-reversed base-32 encoder for an unsigned integer in `[0, 2^bits)`.
50
+ * Pads to `Math.ceil(bits/5)` chars so all values in the domain compare
51
+ * lex against each other.
52
+ *
53
+ * **Order-reversal property:** for any pair of integers `a < b` (with
54
+ * `a, b ∈ [0, 2^bits)`), `uint2strDesc(a, bits) > uint2strDesc(b, bits)`
55
+ * lexicographically. Composed into an LSN of shape
56
+ * `<base32-time>_<session>_<seq>` (where both `<base32-time>` and
57
+ * `<seq>` use this encoder), a forward `Storage.list(prefix)`
58
+ * returns log entries in reverse-causal order — newer entries first.
59
+ *
60
+ * This is the structural property the read path leans on:
61
+ * `ListObjectsV2` is forward-only on S3, but the descending encoding
62
+ * makes "fetch the K newest entries" a single bounded LIST with
63
+ * `maxKeys=K` instead of a full-population LIST + in-memory reverse.
64
+ *
65
+ * Behaviourally verified across randomized populations in
66
+ * `packages/protocol/src/lsn-reverse-list.test.ts`. Quantified
67
+ * bytes-listed reduction is in
68
+ * `docs/spec/attachments/lsn-reverse-walk-baseline.json`
69
+ * (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:
70
+ * `docs/spec/sync-protocol.md` §"LSNs, wall clocks, and downstream
71
+ * consumers".
72
+ */
73
+ const uint2strDesc = (num, bits) => {
74
+ return uint2str(Math.pow(2, bits) - 1 - num, bits);
75
+ };
76
+ const str2uintDesc = (str, bits) => {
77
+ return Math.pow(2, bits) - 1 - parseInt(str, 32);
78
+ };
79
+ //#endregion
80
+ //#region packages/protocol/src/time.ts
81
+ /**
82
+ * Encode an epoch-millis instant as a lexicographically-DEScending
83
+ * base-32 key (newer sorts first). The load-bearing LSN ordering
84
+ * primitive — see {@link uint2strDesc}.
85
+ *
86
+ * `epoch` is REQUIRED and validated. There is no default: an argless
87
+ * call used to encode `0`, which descending-sorts as the most-ancient
88
+ * instant and would silently invert ordering. A non-finite, negative,
89
+ * or out-of-range `epoch` (e.g. a broken `Date.now()` returning `NaN`)
90
+ * would corrupt the key silently rather than fail loud, so it throws
91
+ * `Internal` instead — this is an invariant violation, not caller config
92
+ * (the only legitimate argument is `Date.now()`).
93
+ */
94
+ const timestamp = (epoch) => {
95
+ if (!Number.isInteger(epoch) || epoch < 0 || epoch >= 2 ** 42) throw new BaerlyError("Internal", `timestamp(): epoch must be a non-negative integer < 2^42 (got ${epoch})`);
96
+ return uint2strDesc(epoch, 42);
97
+ };
98
+ /**
99
+ * Delay for `ms` milliseconds, with optional cancellation. If
100
+ * `signal` aborts before the delay elapses, the returned promise
101
+ * rejects with `signal.reason`. Used by `S3HttpStorage`'s retry
102
+ * loop so shutdown can interrupt an in-flight backoff instead of
103
+ * waiting for it to complete.
104
+ */
105
+ const delay = (ms, signal) => new Promise((resolve, reject) => {
106
+ if (signal?.aborted) {
107
+ reject(signal.reason);
108
+ return;
109
+ }
110
+ const timer = setTimeout(resolve, ms);
111
+ signal?.addEventListener("abort", () => {
112
+ clearTimeout(timer);
113
+ reject(signal.reason);
114
+ }, { once: true });
115
+ });
116
+ //#endregion
117
+ export { uuid as a, str2uintDesc as i, timestamp as n, uuidv7 as o, countKey as r, delay as t };
118
+
119
+ //# sourceMappingURL=time-DUqvFMHq.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"time-DUqvFMHq.js","names":[],"sources":["../packages/protocol/src/types.ts","../packages/protocol/src/time.ts"],"sourcesContent":["import { COUNT_BIT_WIDTH } from \"./constants.ts\";\n\ndeclare const brand: unique symbol;\ntype Brand<B> = { [brand]: B };\n\n/**\n * Nominal-typing helper. `Branded<string, \"UUID\">` is a `string` at\n * runtime but the type system rejects mixing it with a plain `string` or\n * a string branded as something else. Used to prevent confusion bugs at\n * protocol boundaries (UUIDs vs. content versions are both strings, but\n * using the wrong one corrupts the per-collection log).\n *\n * Construct branded values via the helpers in this file (e.g. {@link uuid})\n * or with a tagged cast at a single, deliberate boundary — never `as string`\n * to widen one back. See `docs/contributing/conventions/src.md`.\n */\nexport type Branded<T, B> = T & Brand<B>;\n\n/**\n * A v4 UUID minted by this client. Used as session IDs and content\n * identifiers in non-versioned mode.\n */\nexport type UUID = Branded<string, \"UUID\">;\n\n/**\n * SHA-256 content digest, lowercase hex truncated to\n * `VERSION_HEX_LENGTH` (32 chars). Minted by\n * `versionFromContent` in `useVersioning=false` mode and used as\n * the `<key>@<version>` suffix in content keys.\n *\n * The synthetic `local-${op}` placeholder used for in-flight\n * optimistic updates also wears this brand — it never round-trips\n * to S3, only flows through local optimistic state.\n */\nexport type ContentVersionId = Branded<string, \"ContentVersionId\">;\n\n/**\n * Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle\n * `<UUID>crypto.randomUUID()` throughout the codebase.\n */\nexport const uuid = (): UUID => crypto.randomUUID() as UUID;\n\n/**\n * Mint a UUIDv7 — 48-bit Unix-millis prefix + 74 bits of randomness,\n * formatted as a standard 8-4-4-4-12 UUID string per RFC 9562 §5.7.\n * Lex-sortable by mint time, so it pairs well with object-storage\n * list semantics. Returns a branded {@link UUID}.\n *\n * Uses `crypto.getRandomValues` which is universally available\n * (Node 19+, Workerd, Bun, browsers).\n *\n * @example\n * ```ts\n * const id = uuidv7();\n * // e.g. \"01956cad-4cc8-7abc-9def-0123456789ab\"\n * ```\n */\nexport const uuidv7 = (): UUID => {\n const millis = Date.now();\n const rand = new Uint8Array(10);\n crypto.getRandomValues(rand);\n // Version nibble: top 4 bits of rand[0] = 0b0111 (v7). The byte\n // sits at the start of the \"version-and-rand-a\" group below.\n rand[0] = (rand[0]! & 0x0f) | 0x70;\n // Variant bits: top 2 bits of rand[2] = 0b10 (RFC 4122 variant).\n // This byte starts the \"variant-and-rand-b\" group below.\n rand[2] = (rand[2]! & 0x3f) | 0x80;\n const millisHex = millis.toString(16).padStart(12, \"0\");\n const b = Array.from(rand, (n) => n.toString(16).padStart(2, \"0\")).join(\"\");\n return `${millisHex.slice(0, 8)}-${millisHex.slice(8, 12)}-${b.slice(0, 4)}-${b.slice(4, 8)}-${b.slice(8, 20)}` as UUID;\n};\n\n/**\n * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).\n * Uses `COUNT_BIT_WIDTH` (see `packages/protocol/src/constants.ts`) to\n * produce an 11-char descending base-32 string with a domain of\n * 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1).\n *\n * Used together with {@link timestamp} (the descending base-32\n * encoding of millis-since-epoch). See {@link uint2strDesc} for the\n * lex-reversal property both rely on.\n */\nexport const countKey = (number: number): string => uint2strDesc(number, COUNT_BIT_WIDTH);\n\nexport const uint2str = (num: number, bits: number) => {\n const maxBase32Length = Math.ceil(bits / 5); // Change from 4 to 5 because log2(32) is roughly 5.\n const base32Representation = num.toString(32);\n return base32Representation.padStart(maxBase32Length, \"0\");\n};\n\nexport const str2uint = (str: string) => {\n return parseInt(str, 32); // Parse the string as base 32.\n};\n\n/**\n * Lex-reversed base-32 encoder for an unsigned integer in `[0, 2^bits)`.\n * Pads to `Math.ceil(bits/5)` chars so all values in the domain compare\n * lex against each other.\n *\n * **Order-reversal property:** for any pair of integers `a < b` (with\n * `a, b ∈ [0, 2^bits)`), `uint2strDesc(a, bits) > uint2strDesc(b, bits)`\n * lexicographically. Composed into an LSN of shape\n * `<base32-time>_<session>_<seq>` (where both `<base32-time>` and\n * `<seq>` use this encoder), a forward `Storage.list(prefix)`\n * returns log entries in reverse-causal order — newer entries first.\n *\n * This is the structural property the read path leans on:\n * `ListObjectsV2` is forward-only on S3, but the descending encoding\n * makes \"fetch the K newest entries\" a single bounded LIST with\n * `maxKeys=K` instead of a full-population LIST + in-memory reverse.\n *\n * Behaviourally verified across randomized populations in\n * `packages/protocol/src/lsn-reverse-list.test.ts`. Quantified\n * bytes-listed reduction is in\n * `docs/spec/attachments/lsn-reverse-walk-baseline.json`\n * (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:\n * `docs/spec/sync-protocol.md` §\"LSNs, wall clocks, and downstream\n * consumers\".\n */\nexport const uint2strDesc = (num: number, bits: number): string => {\n const maxValue = Math.pow(2, bits) - 1;\n return uint2str(maxValue - num, bits);\n};\n\nexport const str2uintDesc = (str: string, bits: number): number => {\n const maxValue = Math.pow(2, bits) - 1;\n const num = parseInt(str, 32); // Convert base32 string to number\n return maxValue - num;\n};\n","import { TIMESTAMP_BIT_WIDTH } from \"./constants.ts\";\nimport { BaerlyError } from \"./errors.ts\";\nimport { uint2strDesc } from \"./types.ts\";\n\n/**\n * Encode an epoch-millis instant as a lexicographically-DEScending\n * base-32 key (newer sorts first). The load-bearing LSN ordering\n * primitive — see {@link uint2strDesc}.\n *\n * `epoch` is REQUIRED and validated. There is no default: an argless\n * call used to encode `0`, which descending-sorts as the most-ancient\n * instant and would silently invert ordering. A non-finite, negative,\n * or out-of-range `epoch` (e.g. a broken `Date.now()` returning `NaN`)\n * would corrupt the key silently rather than fail loud, so it throws\n * `Internal` instead — this is an invariant violation, not caller config\n * (the only legitimate argument is `Date.now()`).\n */\nexport const timestamp = (epoch: number): string => {\n if (!Number.isInteger(epoch) || epoch < 0 || epoch >= 2 ** TIMESTAMP_BIT_WIDTH) {\n throw new BaerlyError(\n \"Internal\",\n `timestamp(): epoch must be a non-negative integer < 2^${TIMESTAMP_BIT_WIDTH} (got ${epoch})`,\n );\n }\n return uint2strDesc(epoch, TIMESTAMP_BIT_WIDTH);\n};\n\n/**\n * Delay for `ms` milliseconds, with optional cancellation. If\n * `signal` aborts before the delay elapses, the returned promise\n * rejects with `signal.reason`. Used by `S3HttpStorage`'s retry\n * loop so shutdown can interrupt an in-flight backoff instead of\n * waiting for it to complete.\n */\nexport const delay = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(signal.reason);\n },\n // Stryker disable next-line BooleanLiteral,ObjectLiteral: `{ once: true }` removes the\n // listener after the first fire. AbortController fires `abort` only once per signal, so\n // `once: false` / `{}` produce identical observable behaviour — the listener stays attached\n // to an already-fired signal, but calling reject on a settled Promise is a no-op. The\n // BooleanLiteral (once:false) and ObjectLiteral ({}) mutations are genuine equivalences.\n { once: true },\n );\n });\n"],"mappings":";;;;;;AAwCA,MAAa,aAAmB,OAAO,WAAW;;;;;;;;;;;;;;;;AAiBlD,MAAa,eAAqB;CAChC,MAAM,SAAS,KAAK,IAAI;CACxB,MAAM,uBAAO,IAAI,WAAW,EAAE;CAC9B,OAAO,gBAAgB,IAAI;CAG3B,KAAK,KAAM,KAAK,KAAM,KAAQ;CAG9B,KAAK,KAAM,KAAK,KAAM,KAAQ;CAC9B,MAAM,YAAY,OAAO,SAAS,EAAE,CAAC,CAAC,SAAS,IAAI,GAAG;CACtD,MAAM,IAAI,MAAM,KAAK,OAAO,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;CAC1E,OAAO,GAAG,UAAU,MAAM,GAAG,CAAC,EAAE,GAAG,UAAU,MAAM,GAAG,EAAE,EAAE,GAAG,EAAE,MAAM,GAAG,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,EAAE;AAC9G;;;;;;;;;;;AAYA,MAAa,YAAY,WAA2B,aAAa,QAAA,EAAuB;AAExF,MAAa,YAAY,KAAa,SAAiB;CACrD,MAAM,kBAAkB,KAAK,KAAK,OAAO,CAAC;CAE1C,OAD6B,IAAI,SAAS,EAChB,CAAC,CAAC,SAAS,iBAAiB,GAAG;AAC3D;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,gBAAgB,KAAa,SAAyB;CAEjE,OAAO,SADU,KAAK,IAAI,GAAG,IAAI,IAAI,IACV,KAAK,IAAI;AACtC;AAEA,MAAa,gBAAgB,KAAa,SAAyB;CAGjE,OAFiB,KAAK,IAAI,GAAG,IAAI,IAAI,IACzB,SAAS,KAAK,EACN;AACtB;;;;;;;;;;;;;;;;AC/GA,MAAa,aAAa,UAA0B;CAClD,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,KAAK,SAAS,KAAA,IACpD,MAAM,IAAI,YACR,YACA,iEAAqF,MAAM,EAC7F;CAEF,OAAO,aAAa,OAAA,EAA0B;AAChD;;;;;;;;AASA,MAAa,SAAS,IAAY,WAChC,IAAI,SAAe,SAAS,WAAW;CACrC,IAAI,QAAQ,SAAS;EACnB,OAAO,OAAO,MAAM;EACpB;CACF;CACA,MAAM,QAAQ,WAAW,SAAS,EAAE;CACpC,QAAQ,iBACN,eACM;EACJ,aAAa,KAAK;EAClB,OAAO,OAAO,MAAM;CACtB,GAMA,EAAE,MAAM,KAAK,CACf;AACF,CAAC"}
@@ -1,9 +1,7 @@
1
1
  import { t as decodeJsonBytes } from "./bytes-BXdamO3L.js";
2
- import { r as parseBucketUri, t as loadAppConfig } from "./config-CGyBopy3.js";
2
+ import { r as parseBucketUri, t as loadAppConfig } from "./config-1tv0-Yzm.js";
3
3
  import { i as isJsonMode, o as BaerlyError, r as emitSuccess } from "./baerly.js";
4
- import { n as defineBaerlySubcommand } from "./subcommand-CP9NY2J4.js";
5
- /** Number of trailing log entries the estimator reads per collection. */
6
- const SAMPLE_SIZE = 120;
4
+ import { a as TENANT_ARG, i as JSON_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-DoDA-K7d.js";
7
5
  /** Build the canonical `current.json` key for one collection. */
8
6
  const currentJsonKeyFor = (app, tenant, collection) => `app/${app}/tenant/${tenant}/manifests/${collection}/current.json`;
9
7
  /** Derive the `collectionPrefix` (everything before `/current.json`). */
@@ -103,7 +101,7 @@ const readCommitTsBatched = async (storage, keys) => {
103
101
  * root). Threaded through by `baerly inspect`.
104
102
  */
105
103
  const estimateWritesPerMin = async (storage, app, tenant, collection, opts = {}) => {
106
- const sampleSize = opts.sampleSize ?? SAMPLE_SIZE;
104
+ const sampleSize = opts.sampleSize ?? 120;
107
105
  const logPrefix = `${`${opts.keyPrefix ?? ""}${collectionPrefixOf(currentJsonKeyFor(app, tenant, collection))}`}/log/`;
108
106
  let allKeys;
109
107
  try {
@@ -251,22 +249,9 @@ const USAGE_ARGS = {
251
249
  description: "Override `baerly.config.ts:target`. One of \"cloudflare\" | \"node\".",
252
250
  valueHint: "target"
253
251
  },
254
- app: {
255
- type: "string",
256
- required: false,
257
- description: "Application name segment (defaults to baerly.config.ts).",
258
- valueHint: "app"
259
- },
260
- tenant: {
261
- type: "string",
262
- required: false,
263
- description: "Tenant name segment (defaults to baerly.config.ts).",
264
- valueHint: "tenant"
265
- },
266
- json: {
267
- type: "boolean",
268
- description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
269
- }
252
+ app: APP_ARG,
253
+ tenant: TENANT_ARG,
254
+ json: JSON_ARG
270
255
  };
271
256
  const SEVERITY_GLYPH = {
272
257
  ok: "✓",
@@ -336,4 +321,4 @@ bundle.run;
336
321
  //#endregion
337
322
  export { estimateWritesPerMin, usageCmd };
338
323
 
339
- //# sourceMappingURL=usage-CTfDq9HR.js.map
324
+ //# sourceMappingURL=usage-DBV1eQHC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-DBV1eQHC.js","names":[],"sources":["../packages/cli/src/admin/usage.ts"],"sourcesContent":["/**\n * `baerly admin usage` — all-collection writes/min health check.\n *\n * Reads the most recent `SAMPLE_SIZE` log entries for every collection\n * under `app/<app>/tenant/<tenant>/manifests/`, compares the spread of\n * their embedded `commit_ts` timestamps against the M-size operating\n * ceiling (~30 writes/min/collection — see `M_SIZE_WRITES_PER_MIN_PER_COLLECTION`\n * below and `docs/about/thesis.md`), and prints one finding per\n * collection — `info` when well under the ceiling, `warning` when\n * approaching or exceeding it.\n *\n * The ~100 collections/tenant fan-out guideline is bench-grounded:\n * `admin usage` costs ≈ N × (1 LIST + up to 120 GETs per collection)\n * — strictly linear. See `docs/spec/attachments/collection-fanout-baseline.json`\n * (`pnpm bench:collection-fanout`). Neither the ~100 figure nor the\n * >10 GB/tenant storage line is a code constant here; both are cost\n * signals documented in `docs/about/cost-model.md`.\n *\n * Distinct from `baerly cost` (the per-table, $/month projection):\n * `cost` is a developer-facing trajectory for one table, `usage` is an\n * operator-facing M-size graduation health check across all\n * collections.\n *\n * The pure-storage half — {@link estimateWritesPerMin},\n * {@link discoverCollections}, {@link runUsageScan} — takes a\n * `Storage` handle from the caller and never reads `process.env`.\n * The CLI wrapper at the bottom of the file constructs that\n * `Storage` from `--bucket=<uri>` via `parseBucketUri`. The\n * Cloudflare target short-circuits with an info-level \"not yet\n * wired\" finding pending the follow-up work in\n * `docs/followups/agent-friendliness.md` entry 10.\n *\n * Why GET each entry instead of relying on list-time\n * `Last-Modified`: `MemoryStorage` (the test backend) intentionally\n * does NOT surface `lastModified` on `list()`, and the\n * cross-backend story stays uniform if we always read `commit_ts`\n * from the `LogEntry` body. Sample size is bounded (`SAMPLE_SIZE`\n * GETs per collection), so the cost is acceptable for an opt-in\n * operator command.\n *\n * @see docs/about/thesis.md — M-size ceiling rationale.\n * @see docs/spec/log-entry-shape.md — `LogEntry.commit_ts` contract.\n * @see packages/server/src/compactor.ts:224-225 — `collectionPrefix` /\n * `collectionName` derivation pattern reused here.\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, decodeJsonBytes, type LogEntry, type Storage } from \"@baerly/protocol\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { loadAppConfig } from \"../config.ts\";\nimport { emitSuccess, isJsonMode } from \"../output.ts\";\nimport { APP_ARG, defineBaerlySubcommand, JSON_ARG, TENANT_ARG } from \"../subcommand.ts\";\n\n/**\n * Verdict-shaped finding the scan emits. Mirrors the\n * `severity / check / message / fix?` shape that `baerly doctor` uses,\n * but doesn't depend on `doctor/cloudflare.ts` — `admin usage` runs\n * outside the doctor surface.\n */\nexport interface UsageFinding {\n readonly severity: \"ok\" | \"info\" | \"warning\" | \"error\";\n readonly check: string;\n readonly message: string;\n readonly fix?: string;\n}\n\n/**\n * M-size writes-per-minute-per-collection ceiling from\n * `docs/about/thesis.md`. Crossing this with sustained traffic\n * means operators should consider graduating the workload to a\n * graduated store via `baerly export --target=postgres|sqlite|d1`.\n */\nexport const M_SIZE_WRITES_PER_MIN_PER_COLLECTION = 30;\n\n/** Number of trailing log entries the estimator reads per collection. */\nexport const SAMPLE_SIZE = 120;\n\n/** Per-collection verdict surfaced by {@link estimateWritesPerMin}. */\nexport interface UsageVerdict {\n /** Collection name (matches `LogEntry.collection`). */\n readonly collection: string;\n /**\n * Writes per minute estimated over the sample window. `NaN` when\n * fewer than 2 entries were observed (no defensible rate).\n */\n readonly writesPerMin: number;\n /** Percent of {@link M_SIZE_WRITES_PER_MIN_PER_COLLECTION}; `NaN` propagates. */\n readonly percentOfCeiling: number;\n /**\n * Severity scaled by distance to ceiling:\n * - `< 50%` → `\"info\"`\n * - `50–99%` → `\"warning\"` (\"approaching ceiling\")\n * - `≥ 100%` → `\"warning\"` (\"exceeds ceiling — consider export\")\n *\n * Severity `warning` never bumps the doctor's exit code above 0\n * (operators can still deploy / continue while approaching the\n * ceiling).\n */\n readonly severity: \"info\" | \"warning\";\n /** Human-readable one-liner suitable for a {@link UsageFinding}. */\n readonly message: string;\n /** Empty when no remediation is meaningful (under 50%). */\n readonly fix: string;\n}\n\n/** Build the canonical `current.json` key for one collection. */\nexport const currentJsonKeyFor = (app: string, tenant: string, collection: string): string =>\n `app/${app}/tenant/${tenant}/manifests/${collection}/current.json`;\n\n/** Derive the `collectionPrefix` (everything before `/current.json`). */\nexport const collectionPrefixOf = (currentJsonKey: string): string =>\n currentJsonKey.slice(0, currentJsonKey.lastIndexOf(\"/\"));\n\n/**\n * List every log key under `${collectionPrefix}/log/` for one collection.\n * Returns the keys in **chronological order** (oldest seq first).\n *\n * The on-bucket key shape is `<collectionPrefix>/log/<seq>.json` where\n * `<seq>` is a base-10 integer minted by `Writer`. Lex-ascending\n * key order disagrees with numeric seq order past seq=9 (`log/10.json`\n * sorts before `log/2.json`), so we parse the trailing integer out of\n * each key and sort numerically.\n *\n * Caller is expected to slice the trailing N entries — the writes/min\n * estimator only needs the most recent sample.\n */\n// Parse the `<seq>` integer from a `<logPrefix>/<seq>.json` key. Returns\n// `NaN` when the basename isn't a finite integer (the caller filters\n// those out before sorting). Hoisted out of {@link listLogKeysSortedBySeq}\n// so a function instance isn't allocated per list entry.\nconst seqOfLogKey = (key: string): number => {\n const slash = key.lastIndexOf(\"/\");\n const dot = key.lastIndexOf(\".json\");\n if (slash === -1 || dot === -1 || dot <= slash) {\n return Number.NaN;\n }\n const seqStr = key.slice(slash + 1, dot);\n const n = Number.parseInt(seqStr, 10);\n return Number.isFinite(n) ? n : Number.NaN;\n};\n\nconst listLogKeysSortedBySeq = async (\n storage: Storage,\n logPrefix: string,\n): Promise<readonly string[]> => {\n const keys: string[] = [];\n for await (const entry of storage.list(logPrefix)) {\n keys.push(entry.key);\n }\n return keys\n .filter((k) => Number.isFinite(seqOfLogKey(k)))\n .toSorted((a, b) => seqOfLogKey(a) - seqOfLogKey(b));\n};\n\n/**\n * Fetch a `LogEntry` body at `key`, returning its `commit_ts` parsed\n * to epoch-ms. Returns `null` when the object is missing (a peer may\n * have GC'd it between list and get); throws `BaerlyError` on a\n * malformed body so the caller can downgrade the whole collection's\n * scan to an error-level finding.\n */\nconst readCommitTsMs = async (storage: Storage, key: string): Promise<number | null> => {\n const got = await storage.get(key);\n if (got === null) {\n return null;\n }\n let parsed: LogEntry;\n try {\n parsed = decodeJsonBytes<LogEntry>(got.body);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `usage scan: log entry at ${key} is not valid JSON`,\n error,\n );\n }\n if (typeof parsed.commit_ts !== \"string\") {\n throw new BaerlyError(\"InvalidResponse\", `usage scan: log entry at ${key} missing commit_ts`);\n }\n const ms = Date.parse(parsed.commit_ts);\n if (!Number.isFinite(ms)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `usage scan: log entry at ${key} has unparseable commit_ts ${JSON.stringify(parsed.commit_ts)}`,\n );\n }\n return ms;\n};\n\n/**\n * Read each key with bounded concurrency. Mirrors the pattern in\n * `packages/server/src/log-walk.ts` — we cap parallelism to keep a\n * single doctor pass from blowing through the storage backend's\n * connection budget. Keeps a small constant rather than reaching for\n * `MAX_PARALLEL_LOG_READS` (8) so the doctor command is gentle by\n * default.\n */\nconst PARALLEL_READS = 8;\n\nconst readCommitTsBatched = async (\n storage: Storage,\n keys: readonly string[],\n): Promise<readonly (number | null)[]> => {\n const out: (number | null)[] = Array.from({ length: keys.length });\n for (let i = 0; i < keys.length; i += PARALLEL_READS) {\n const chunk = keys.slice(i, i + PARALLEL_READS);\n const results = await Promise.all(chunk.map((k) => readCommitTsMs(storage, k)));\n for (let j = 0; j < results.length; j++) {\n out[i + j] = results[j] ?? null;\n }\n }\n return out;\n};\n\n/**\n * Estimate writes/min for one collection.\n *\n * Reads the last `sampleSize` log entries (default `SAMPLE_SIZE`)\n * for `<app>/<tenant>/<collection>`, computes\n * `(observedEntries - 1) / ((maxTs - minTs) / 60_000)`\n * minutes, compares against {@link M_SIZE_WRITES_PER_MIN_PER_COLLECTION},\n * and returns a {@link UsageVerdict}.\n *\n * Edge cases:\n * - Fewer than 2 entries observable → `writesPerMin = NaN`,\n * severity `info`, no fix. Operators see \"not enough log\n * entries to estimate.\"\n * - All entries share the same `commit_ts` (e.g. a tight batch) →\n * the denominator is clamped to 1 second so the rate degrades\n * gracefully instead of dividing by zero.\n *\n * @throws BaerlyError code=\"NetworkError\" — wrapped storage failure\n * while listing. The caller (Node doctor backend) catches and\n * converts to a warning-severity finding so one bad collection\n * doesn't fail the whole scan.\n * @throws BaerlyError code=\"InvalidResponse\" — a sampled log entry\n * body is malformed; same caller treatment.\n * @param opts.keyPrefix - When the bucket has a non-empty key prefix\n * (e.g. `s3://my-bucket/some/prefix`), pass it here (ending in\n * `/`). Defaults to `\"\"`. Necessary for prefixed-bucket\n * correctness; ignored by `runUsageScan` (Node doctor scans the\n * root). Threaded through by `baerly inspect`.\n */\nexport const estimateWritesPerMin = async (\n storage: Storage,\n app: string,\n tenant: string,\n collection: string,\n opts: { readonly sampleSize?: number; readonly keyPrefix?: string } = {},\n): Promise<UsageVerdict> => {\n const sampleSize = opts.sampleSize ?? SAMPLE_SIZE;\n const keyPrefix = opts.keyPrefix ?? \"\";\n const collectionPrefix = `${keyPrefix}${collectionPrefixOf(currentJsonKeyFor(app, tenant, collection))}`;\n const logPrefix = `${collectionPrefix}/log/`;\n\n let allKeys: readonly string[];\n try {\n allKeys = await listLogKeysSortedBySeq(storage, logPrefix);\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"NetworkError\",\n `usage scan: list ${logPrefix} failed: ${(error as Error).message}`,\n error,\n );\n }\n const sample = allKeys.slice(Math.max(0, allKeys.length - sampleSize));\n if (sample.length < 2) {\n return {\n collection,\n writesPerMin: Number.NaN,\n percentOfCeiling: Number.NaN,\n severity: \"info\",\n message: `collection ${collection}: not enough log entries to estimate (saw ${sample.length}, need >= 2)`,\n fix: \"\",\n };\n }\n const commitTs = await readCommitTsBatched(storage, sample);\n const timestamps = commitTs.filter((v): v is number => v !== null);\n if (timestamps.length < 2) {\n return {\n collection,\n writesPerMin: Number.NaN,\n percentOfCeiling: Number.NaN,\n severity: \"info\",\n message: `collection ${collection}: not enough readable log entries to estimate (resolved ${timestamps.length}, need >= 2)`,\n fix: \"\",\n };\n }\n let minTs = timestamps[0]!;\n let maxTs = timestamps[0]!;\n for (const t of timestamps) {\n if (t < minTs) {\n minTs = t;\n }\n if (t > maxTs) {\n maxTs = t;\n }\n }\n // Guard the denominator: a tight batch may produce identical\n // commit_ts values; degrade to a one-second window so we never\n // divide by zero.\n const minutes = Math.max(1 / 60, (maxTs - minTs) / 60_000);\n const writesPerMin = (timestamps.length - 1) / minutes;\n const pct = (writesPerMin / M_SIZE_WRITES_PER_MIN_PER_COLLECTION) * 100;\n\n let severity: \"info\" | \"warning\" = \"info\";\n let message = `collection ${collection}: ${writesPerMin.toFixed(1)} writes/min (~${pct.toFixed(0)}% of M-size ceiling, sampled ${timestamps.length} entries)`;\n let fix = \"\";\n if (pct >= 100) {\n severity = \"warning\";\n message += \" — exceeds the M-size ceiling.\";\n fix = `consider graduating: \\`baerly export --target=postgres|sqlite|d1 --bucket=<bucket> --app=${app} --tenant=${tenant} --collection=${collection}\\``;\n } else if (pct >= 50) {\n severity = \"warning\";\n message += \" — approaching the M-size ceiling.\";\n fix = \"monitor; plan graduation via `baerly export --target=postgres|sqlite|d1`\";\n }\n return { collection, writesPerMin, percentOfCeiling: pct, severity, message, fix };\n};\n\n/**\n * Discover the set of collections under `<app>/<tenant>/manifests/`\n * by listing the bucket. Each collection is the immediate\n * subdirectory name (the segment after `manifests/` and before the\n * next `/`).\n *\n * Returns a deduped, lex-sorted list. An empty list means there are\n * no committed collections under this app/tenant yet — the caller\n * surfaces a single info finding rather than scanning per-collection.\n *\n * @throws BaerlyError code=\"NetworkError\" — wrapped list failure.\n */\nexport const discoverCollections = async (\n storage: Storage,\n app: string,\n tenant: string,\n): Promise<readonly string[]> => {\n const prefix = `app/${app}/tenant/${tenant}/manifests/`;\n const names = new Set<string>();\n try {\n for await (const entry of storage.list(prefix)) {\n const rest = entry.key.slice(prefix.length);\n const slash = rest.indexOf(\"/\");\n const name = slash === -1 ? rest : rest.slice(0, slash);\n if (name.length > 0) {\n names.add(name);\n }\n }\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"NetworkError\",\n `usage scan: list ${prefix} failed: ${(error as Error).message}`,\n error,\n );\n }\n return [...names].toSorted();\n};\n\n/**\n * Orchestrate the usage scan against a caller-supplied\n * {@link Storage}. The CLI wrapper handles bucket-URI construction;\n * this helper runs the shared discover → per-collection-estimate →\n * finding-push loop.\n *\n * Mutates `findings` in place. Returns when the scan completes\n * (success or per-collection failure all surface as findings). The\n * outer CLI exit code is driven by the rollup over all findings.\n *\n * Errors land as warnings (not errors) so one bad collection doesn't\n * abort the whole scan and so the operator stays deployable while a\n * single object is being investigated.\n */\nexport const runUsageScan = async (\n context: { readonly app: string; readonly tenant: string },\n storage: Storage,\n findings: UsageFinding[],\n): Promise<void> => {\n let collections: readonly string[];\n try {\n collections = await discoverCollections(storage, context.app, context.tenant);\n } catch (error) {\n findings.push({\n severity: \"warning\",\n check: \"usage-discover\",\n message: `could not enumerate collections under app/${context.app}/tenant/${context.tenant}/manifests/: ${error instanceof BaerlyError ? error.message : (error as Error).message}`,\n });\n return;\n }\n if (collections.length === 0) {\n findings.push({\n severity: \"info\",\n check: \"usage-empty\",\n message: `no collections found under app/${context.app}/tenant/${context.tenant}/manifests/; nothing to scan.`,\n });\n return;\n }\n for (const c of collections) {\n try {\n const verdict = await estimateWritesPerMin(storage, context.app, context.tenant, c);\n findings.push({\n severity: verdict.severity,\n check: `usage-${c}`,\n message: verdict.message,\n ...(verdict.fix !== \"\" && { fix: verdict.fix }),\n });\n } catch (error) {\n findings.push({\n severity: \"warning\",\n check: `usage-${c}`,\n message: `failed to estimate writes/min for ${c}: ${error instanceof BaerlyError ? error.message : (error as Error).message}`,\n });\n }\n }\n};\n\n// ---------------------------------------------------------------------------\n// CLI surface — `baerly admin usage`\n// ---------------------------------------------------------------------------\n\nconst USAGE_ARGS = {\n bucket: {\n type: \"string\",\n required: false,\n description:\n \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>). Required for --target=node.\",\n valueHint: \"bucket-uri\",\n },\n target: {\n type: \"string\",\n required: false,\n description: 'Override `baerly.config.ts:target`. One of \"cloudflare\" | \"node\".',\n valueHint: \"target\",\n },\n app: APP_ARG,\n tenant: TENANT_ARG,\n json: JSON_ARG,\n} as const satisfies ArgsDef;\n\nconst SEVERITY_GLYPH: Record<UsageFinding[\"severity\"], string> = {\n ok: \"✓\",\n info: \"•\",\n warning: \"⚠\",\n error: \"✗\",\n};\n\nconst renderText = (target: string, findings: readonly UsageFinding[]): string => {\n const lines: string[] = [];\n lines.push(`baerly admin usage --target=${target}`);\n lines.push(\"\");\n for (const f of findings) {\n lines.push(` ${SEVERITY_GLYPH[f.severity]} ${f.message}`);\n if (f.fix !== undefined && f.fix !== \"\") {\n lines.push(` fix: ${f.fix}`);\n }\n }\n let warnings = 0;\n let errors = 0;\n for (const f of findings) {\n if (f.severity === \"warning\") {\n warnings++;\n } else if (f.severity === \"error\") {\n errors++;\n }\n }\n lines.push(\"\");\n lines.push(\n `Status: ${errors} error${errors === 1 ? \"\" : \"s\"}, ${warnings} warning${warnings === 1 ? \"\" : \"s\"}.`,\n );\n return lines.join(\"\\n\") + \"\\n\";\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.usage\",\n meta: {\n description:\n \"All-collection writes/min health check; flags collections approaching the M-size ceiling.\",\n },\n args: USAGE_ARGS,\n handler: async (args, ctx) => {\n // Avoid loading the config when --target is explicit — the CLI\n // should still work outside an app directory if the operator\n // pins target + app + tenant on the flags.\n const target = args.target ?? (await loadAppConfig().then((c) => c.target));\n if (target !== \"cloudflare\" && target !== \"node\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin usage: unsupported --target ${JSON.stringify(target)} (one of \"cloudflare\" | \"node\")`,\n );\n }\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n\n const findings: UsageFinding[] = [];\n\n if (target === \"cloudflare\") {\n // The CLI runs in Node and can't reach a Workerd-side R2 binding\n // from `--bucket=<uri>`; full CF wiring is a follow-up — see\n // `docs/followups/agent-friendliness.md` entry 10.\n findings.push({\n severity: \"info\",\n check: \"usage.cloudflare\",\n message:\n \"baerly admin usage is not yet wired for --target=cloudflare. See docs/followups/agent-friendliness.md entry 10.\",\n });\n } else {\n if (args.bucket === undefined || args.bucket.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerly admin usage: --bucket=<uri> is required for --target=node\",\n );\n }\n const parsed = await parseBucketUri(args.bucket);\n await runUsageScan({ app, tenant }, parsed.storage, findings);\n }\n\n if (isJsonMode()) {\n emitSuccess({\n command: \"admin.usage\",\n status: \"ok\",\n target,\n findings: findings.map((f) => ({\n severity: f.severity,\n check: f.check,\n message: f.message,\n ...(f.fix !== undefined && f.fix !== \"\" && { fix: f.fix }),\n })),\n });\n } else {\n process.stdout.write(renderText(target, findings));\n }\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin usage`. */\nexport const usageCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runUsage = bundle.run;\n"],"mappings":";;;;;AA0GA,MAAa,qBAAqB,KAAa,QAAgB,eAC7D,OAAO,IAAI,UAAU,OAAO,aAAa,WAAW;;AAGtD,MAAa,sBAAsB,mBACjC,eAAe,MAAM,GAAG,eAAe,YAAY,GAAG,CAAC;;;;;;;;;;;;;;AAmBzD,MAAM,eAAe,QAAwB;CAC3C,MAAM,QAAQ,IAAI,YAAY,GAAG;CACjC,MAAM,MAAM,IAAI,YAAY,OAAO;CACnC,IAAI,UAAU,MAAM,QAAQ,MAAM,OAAO,OACvC,OAAO;CAET,MAAM,SAAS,IAAI,MAAM,QAAQ,GAAG,GAAG;CACvC,MAAM,IAAI,OAAO,SAAS,QAAQ,EAAE;CACpC,OAAO,OAAO,SAAS,CAAC,IAAI,IAAI;AAClC;AAEA,MAAM,yBAAyB,OAC7B,SACA,cAC+B;CAC/B,MAAM,OAAiB,CAAC;CACxB,WAAW,MAAM,SAAS,QAAQ,KAAK,SAAS,GAC9C,KAAK,KAAK,MAAM,GAAG;CAErB,OAAO,KACJ,QAAQ,MAAM,OAAO,SAAS,YAAY,CAAC,CAAC,CAAC,CAAC,CAC9C,UAAU,GAAG,MAAM,YAAY,CAAC,IAAI,YAAY,CAAC,CAAC;AACvD;;;;;;;;AASA,MAAM,iBAAiB,OAAO,SAAkB,QAAwC;CACtF,MAAM,MAAM,MAAM,QAAQ,IAAI,GAAG;CACjC,IAAI,QAAQ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CACrE;EAEF,MAAM,EAAE,KAAK,WAAW,MAAM,IAAI,iBAAiB;GAAE,KAAK,KAAK;GAAK,QAAQ,KAAK;EAAO,CAAC;EAEzF,MAAM,WAA2B,CAAC;EAElC,IAAI,WAAW,cAIb,SAAS,KAAK;GACZ,UAAU;GACV,OAAO;GACP,SACE;EACJ,CAAC;OACI;GACL,IAAI,KAAK,WAAW,KAAA,KAAa,KAAK,OAAO,WAAW,GACtD,MAAM,IAAI,YACR,iBACA,kEACF;GAEF,MAAM,SAAS,MAAM,eAAe,KAAK,MAAM;GAC/C,MAAM,aAAa;IAAE;IAAK;GAAO,GAAG,OAAO,SAAS,QAAQ;EAC9D;EAEA,IAAI,WAAW,GACb,YAAY;GACV,SAAS;GACT,QAAQ;GACR;GACA,UAAU,SAAS,KAAK,OAAO;IAC7B,UAAU,EAAE;IACZ,OAAO,EAAE;IACT,SAAS,EAAE;IACX,GAAI,EAAE,QAAQ,KAAA,KAAa,EAAE,QAAQ,MAAM,EAAE,KAAK,EAAE,IAAI;GAC1D,EAAE;EACJ,CAAC;OAED,QAAQ,OAAO,MAAM,WAAW,QAAQ,QAAQ,CAAC;EAEnD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,WAAW,OAAO;AAOP,OAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"wire-izfGZDvr.js","names":[],"sources":["../packages/protocol/src/query/wire.ts"],"sourcesContent":["/**\n * Wire-format predicate types. A predicate normalises to a flat list\n * of {@link PredicateClause} records; the server, client, matcher,\n * merger, and validator all consume the wire form. Object-literal\n * (`Predicate<T>`) and callback (`PredicateBuilder<T>`) forms compile\n * to this shape via `./normalize.ts` / `./builder.ts`.\n */\n\nimport type { DocumentValue } from \"../json.ts\";\n\n/**\n * Locked operator vocabulary. Methods on {@link PredicateBuilder}\n * map 1:1 to these names; the validator rejects any other.\n *\n * `eq` — strict equality.\n * `gt` / `gte` / `lt` / `lte` — scalar range. Bounds must be `string`\n * or finite `number`. Type-mismatched actuals are always-miss.\n * `in` — set membership. Empty array → `UnsatisfiablePredicate`.\n */\nexport type PredicateOpName = \"eq\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"in\";\n\n/**\n * One clause in a normalised predicate. `field` is a top-level key\n * or a dotted path. `value` is an array iff `op === \"in\"`.\n *\n * `op: \"eq\"` on a primitive `value` is plain equality. The\n * normaliser flattens nested literal sub-predicates\n * (`{ assignee: { team: \"x\" } }`) to dotted-path `eq` clauses\n * (`{op:\"eq\", field:\"assignee.team\", value:\"x\"}`), so an `eq`\n * value at the wire level is never a nested non-primitive object\n * — only callback-form `q.eq(\"nested\", { ... })` could produce\n * one, and that requires the type system to allow it at the call\n * site.\n */\nexport interface PredicateClause {\n readonly op: PredicateOpName;\n readonly field: string;\n readonly value: DocumentValue | ReadonlyArray<DocumentValue>;\n}\n\n/**\n * Normalised predicate envelope. The wire form is a flat list of\n * clauses; multiple clauses across all fields AND together. The\n * empty wire `{ clauses: [] }` matches every document.\n *\n * Wire mirror on the HTTP surface: `?where=` carries the JSON\n * encoding of this object. See `packages/server/API.md` for the\n * literal example.\n */\nexport interface PredicateWire {\n readonly clauses: ReadonlyArray<PredicateClause>;\n}\n\n/** @internal Empty match-all wire — re-used to avoid re-allocating. */\nexport const EMPTY_PREDICATE_WIRE: PredicateWire = { clauses: [] };\n"],"mappings":";;AAsDA,MAAa,uBAAsC,EAAE,SAAS,CAAC,EAAE"}
1
+ {"version":3,"file":"wire-izfGZDvr.js","names":[],"sources":["../packages/protocol/src/query/wire.ts"],"sourcesContent":["/**\n * Wire-format predicate types. A predicate normalises to a flat list\n * of {@link PredicateClause} records; the server, client, matcher,\n * merger, and validator all consume the wire form. Object-literal\n * (`Predicate<T>`) and callback (`PredicateBuilder<T>`) forms compile\n * to this shape via `./normalize.ts` / `./builder.ts`.\n */\n\nimport type { DocumentValue } from \"../json.ts\";\n\n/**\n * Runtime mirror of {@link PredicateOpName}. The type derives from this\n * tuple so the value is the single source of truth: the spec generator\n * and the drift gate enumerate `PREDICATE_OPS`, and tsgo rejects any\n * member added to the type-union without a matching tuple entry.\n */\nexport const PREDICATE_OPS = [\"eq\", \"gt\", \"gte\", \"lt\", \"lte\", \"in\"] as const;\n\n/**\n * Locked operator vocabulary. Methods on {@link PredicateBuilder}\n * map 1:1 to these names; the validator rejects any other.\n *\n * `eq` — strict equality.\n * `gt` / `gte` / `lt` / `lte` — scalar range. Bounds must be `string`\n * or finite `number`. Type-mismatched actuals are always-miss.\n * `in` — set membership. Empty array → `UnsatisfiablePredicate`.\n */\nexport type PredicateOpName = (typeof PREDICATE_OPS)[number];\n\n/**\n * One clause in a normalised predicate. `field` is a top-level key\n * or a dotted path. `value` is an array iff `op === \"in\"`.\n *\n * `op: \"eq\"` on a primitive `value` is plain equality. The\n * normaliser flattens nested literal sub-predicates\n * (`{ assignee: { team: \"x\" } }`) to dotted-path `eq` clauses\n * (`{op:\"eq\", field:\"assignee.team\", value:\"x\"}`), so an `eq`\n * value at the wire level is never a nested non-primitive object\n * — only callback-form `q.eq(\"nested\", { ... })` could produce\n * one, and that requires the type system to allow it at the call\n * site.\n */\nexport interface PredicateClause {\n readonly op: PredicateOpName;\n readonly field: string;\n readonly value: DocumentValue | ReadonlyArray<DocumentValue>;\n}\n\n/**\n * Normalised predicate envelope. The wire form is a flat list of\n * clauses; multiple clauses across all fields AND together. The\n * empty wire `{ clauses: [] }` matches every document.\n *\n * Wire mirror on the HTTP surface: `?where=` carries the JSON\n * encoding of this object. See `packages/server/API.md` for the\n * literal example.\n */\nexport interface PredicateWire {\n readonly clauses: ReadonlyArray<PredicateClause>;\n}\n\n/** @internal Empty match-all wire — re-used to avoid re-allocating. */\nexport const EMPTY_PREDICATE_WIRE: PredicateWire = { clauses: [] };\n"],"mappings":";;AA8DA,MAAa,uBAAsC,EAAE,SAAS,CAAC,EAAE"}