@gusto/baerly-storage 0.5.0 → 0.6.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 (102) hide show
  1. package/dist/API.md +3 -2
  2. package/dist/CHANGELOG.md +82 -0
  3. package/dist/THIRD-PARTY-LICENSES.txt +1 -1
  4. package/dist/auth.d.ts +1 -1
  5. package/dist/aws4fetch.esm-CXE5ZbAa.js +460 -0
  6. package/dist/aws4fetch.esm-CXE5ZbAa.js.map +1 -0
  7. package/dist/baerly.js +10 -10
  8. package/dist/baerly.spec.json +1 -1
  9. package/dist/client-react.d.ts +2 -2
  10. package/dist/{client-Fe8CwB73.d.ts → client-ypCm3zjt.d.ts} +2 -2
  11. package/dist/client.d.ts +2 -2
  12. package/dist/{cloudflare-DzKBrUlg.js → cloudflare-wrVYf4bb.js} +457 -56
  13. package/dist/cloudflare-wrVYf4bb.js.map +1 -0
  14. package/dist/cloudflare.d.ts +3 -3
  15. package/dist/cloudflare.js +5 -5
  16. package/dist/{config-1tv0-Yzm.js → config-B6nTy8e2.js} +435 -33
  17. package/dist/config-B6nTy8e2.js.map +1 -0
  18. package/dist/constants-CfeMWQWk.js.map +1 -1
  19. package/dist/{cost-DSMIVqzL.js → cost-_SE_SVgZ.js} +4 -4
  20. package/dist/{cost-DSMIVqzL.js.map → cost-_SE_SVgZ.js.map} +1 -1
  21. package/dist/{db-DsPkOVEH.d.ts → db-DjjthkTi.d.ts} +2 -2
  22. package/dist/{deploy-DonTr-CV.js → deploy-Di_Q01qx.js} +5 -5
  23. package/dist/deploy-Di_Q01qx.js.map +1 -0
  24. package/dist/dev-vite.d.ts +31 -27
  25. package/dist/dev-vite.js +60 -30
  26. package/dist/dev-vite.js.map +1 -1
  27. package/dist/dev.d.ts +1 -1
  28. package/dist/doctor-RWVRpvat.js +102 -0
  29. package/dist/doctor-RWVRpvat.js.map +1 -0
  30. package/dist/{dump-Bh5k26VQ.js → dump-m2vEYDNY.js} +4 -4
  31. package/dist/{dump-Bh5k26VQ.js.map → dump-m2vEYDNY.js.map} +1 -1
  32. package/dist/{export-DtF5tDIM.js → export-DenKwEQu.js} +4 -4
  33. package/dist/{export-DtF5tDIM.js.map → export-DenKwEQu.js.map} +1 -1
  34. package/dist/{fsck-D_djMO5D.js → fsck-2Vq-7-e2.js} +5 -5
  35. package/dist/{fsck-D_djMO5D.js.map → fsck-2Vq-7-e2.js.map} +1 -1
  36. package/dist/gcs-admin-Bx6xSNJj.d.ts +123 -0
  37. package/dist/gcs.d.ts +18 -0
  38. package/dist/gcs.js +2 -0
  39. package/dist/goog4-signer-Z7KnJ1su.js +321 -0
  40. package/dist/goog4-signer-Z7KnJ1su.js.map +1 -0
  41. package/dist/{http-DGd5tbNs.js → http-7zT29K3P.js} +4 -4
  42. package/dist/{http-DGd5tbNs.js.map → http-7zT29K3P.js.map} +1 -1
  43. package/dist/{aws4fetch.esm-p7eEzLCs.js → http-transport-BTgVCY5r.js} +24 -476
  44. package/dist/http-transport-BTgVCY5r.js.map +1 -0
  45. package/dist/http.d.ts +2 -2
  46. package/dist/http.js +2 -2
  47. package/dist/{index-BNRh23K9.d.ts → index-BHz92Acj.d.ts} +2 -2
  48. package/dist/{index-BYk9oCNf.d.ts → index-CEZKQsKt.d.ts} +3 -2
  49. package/dist/{index-CuA9Mi3K.d.ts → index-DP3ClvcA.d.ts} +7 -7
  50. package/dist/{index-0rZcMBwy.d.ts → index-uE-w2dgj.d.ts} +2 -2
  51. package/dist/index.d.ts +3 -3
  52. package/dist/index.js +3 -3
  53. package/dist/{inspect-6WZ-pC7-.js → inspect-BpYbH1DM.js} +5 -5
  54. package/dist/{inspect-6WZ-pC7-.js.map → inspect-BpYbH1DM.js.map} +1 -1
  55. package/dist/{log-tail-D98U1JBo.js → log-tail-QWU4wlu-.js} +3 -11
  56. package/dist/log-tail-QWU4wlu-.js.map +1 -0
  57. package/dist/{maintenance-B_e0T99L.d.ts → maintenance-BGHGt2Yg.d.ts} +2 -2
  58. package/dist/{maintenance-B4Dki6Ig.js → maintenance-DULFcpd1.js} +4 -17
  59. package/dist/maintenance-DULFcpd1.js.map +1 -0
  60. package/dist/{maintenance-C7coQp4c.js → maintenance-fEi-UZ2o.js} +5 -11
  61. package/dist/maintenance-fEi-UZ2o.js.map +1 -0
  62. package/dist/maintenance.d.ts +1 -1
  63. package/dist/maintenance.js +1 -1
  64. package/dist/node.d.ts +21 -60
  65. package/dist/node.js +4 -3
  66. package/dist/{observability-BmflLCdF.js → observability-Ch-VQJyE.js} +38 -16
  67. package/dist/{observability-BmflLCdF.js.map → observability-Ch-VQJyE.js.map} +1 -1
  68. package/dist/observability.d.ts +2 -2
  69. package/dist/observability.js +1 -1
  70. package/dist/{plan-a7PJHBCy.js → plan-C4qgiXSg.js} +2 -2
  71. package/dist/{plan-a7PJHBCy.js.map → plan-C4qgiXSg.js.map} +1 -1
  72. package/dist/{query-rAtXNQQB.js → query-C43r-6ib.js} +2 -2
  73. package/dist/{query-rAtXNQQB.js.map → query-C43r-6ib.js.map} +1 -1
  74. package/dist/{rebuild-index-BVzQSZlm.js → rebuild-index-BH1dc1p6.js} +4 -4
  75. package/dist/{rebuild-index-BVzQSZlm.js.map → rebuild-index-BH1dc1p6.js.map} +1 -1
  76. package/dist/{restore-R-4rbciV.js → restore-D0VYWzfP.js} +5 -5
  77. package/dist/{restore-R-4rbciV.js.map → restore-D0VYWzfP.js.map} +1 -1
  78. package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec--LykAdl1.js} +2 -2
  79. package/dist/{runtime-spec-Dsw2-n8S.js.map → runtime-spec--LykAdl1.js.map} +1 -1
  80. package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DD5gDc7t.d.ts} +6 -4
  81. package/dist/s3.d.ts +1 -1
  82. package/dist/s3.js +1 -1
  83. package/dist/sha256-CqcKTjw9.js +22 -0
  84. package/dist/sha256-CqcKTjw9.js.map +1 -0
  85. package/dist/{src-BL_JoPTn.js → src-BMFfDUI2.js} +68 -28
  86. package/dist/{src-BL_JoPTn.js.map → src-BMFfDUI2.js.map} +1 -1
  87. package/dist/{src-CYHFDrKz.js → src-DvbTEya2.js} +3 -3
  88. package/dist/{src-CYHFDrKz.js.map → src-DvbTEya2.js.map} +1 -1
  89. package/dist/{subcommand-DoDA-K7d.js → subcommand-BV68pqwJ.js} +2 -2
  90. package/dist/{subcommand-DoDA-K7d.js.map → subcommand-BV68pqwJ.js.map} +1 -1
  91. package/dist/{usage-DBV1eQHC.js → usage-BMZR8o6U.js} +3 -3
  92. package/dist/{usage-DBV1eQHC.js.map → usage-BMZR8o6U.js.map} +1 -1
  93. package/package.json +10 -4
  94. package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
  95. package/dist/cloudflare-DzKBrUlg.js.map +0 -1
  96. package/dist/config-1tv0-Yzm.js.map +0 -1
  97. package/dist/deploy-DonTr-CV.js.map +0 -1
  98. package/dist/doctor-DSIyCDg_.js +0 -346
  99. package/dist/doctor-DSIyCDg_.js.map +0 -1
  100. package/dist/log-tail-D98U1JBo.js.map +0 -1
  101. package/dist/maintenance-B4Dki6Ig.js.map +0 -1
  102. package/dist/maintenance-C7coQp4c.js.map +0 -1
@@ -2,8 +2,8 @@ import { t as sharedSecret } from "./shared-secret-DgEicd3x.js";
2
2
  import { a as decodeJsonBytes, i as readCurrentJson } from "./current-json-C6nhPOm1.js";
3
3
  import { _ as SHARED_SECRET_MISSING_MESSAGE, h as NO_AUTH_CONFIGURED_MESSAGE } from "./constants-CfeMWQWk.js";
4
4
  import { t as BaerlyError } from "./errors-Dfa3p78c.js";
5
- import { T as logObjectKey, w as probeTailFrom } from "./maintenance-B4Dki6Ig.js";
6
- import { a as runReplaceById, i as runInsert, s as assertPathSegment, t as makeQuery } from "./query-rAtXNQQB.js";
5
+ import { T as logObjectKey, w as probeTailFrom } from "./maintenance-DULFcpd1.js";
6
+ import { a as runReplaceById, i as runInsert, s as assertPathSegment, t as makeQuery } from "./query-C43r-6ib.js";
7
7
  import { t as assertValidStorageKey } from "./key-Di6yyxFu.js";
8
8
  //#region packages/protocol/src/env.ts
9
9
  const PAAS_MARKERS = [
@@ -533,4 +533,4 @@ const assertKeySegment = (value, role, verb) => {
533
533
  //#endregion
534
534
  export { isDeployedEnv as a, MemoryStorage as i, resolveVerifier as n, collectionsToMaps as r, Db as t };
535
535
 
536
- //# sourceMappingURL=src-CYHFDrKz.js.map
536
+ //# sourceMappingURL=src-DvbTEya2.js.map
@@ -1 +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 assertPathSeg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;;;;;;;;;;;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
+ {"version":3,"file":"src-DvbTEya2.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,KA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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
@@ -194,4 +194,4 @@ const defineBaerlySubcommand = (def) => {
194
194
  //#endregion
195
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 };
196
196
 
197
- //# sourceMappingURL=subcommand-DoDA-K7d.js.map
197
+ //# sourceMappingURL=subcommand-BV68pqwJ.js.map
@@ -1 +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 {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I;EAE5E,IAAI;GACF,KAAK,MAAM,KAAK,OAAO,KAAK,IAAI,GAC9B,IAAI,CAAC,YAAY,IAAI,CAAC,GACpB,MAAM,IAAI,YAAY,iBAAiB,UAAU,IAAI,KAAK,mBAAmB,GAAG;GAGpF,OAAO,MAAM,IAAI,QAAQ,MAAM,GAAG;EACpC,SAAS,OAAO;GACd,IAAI,iBAAiB,aAAa;IAChC,UAAU,IAAI,MAAM,MAAM,MAAM,MAAM,OAAO;IAC7C,OAAO,gBAAgB,MAAM,IAAI;GACnC;GACA,UAAU,IAAI,MAAM,WAAY,MAAgB,OAAO;GACvD,OAAO;EACT;CACF;AACF;;;;;;;;;;;;;;;AAgBA,MAAa,0BACX,QAC4B;CAC5B,MAAM,mBAAmB,qBAAqB,IAAI,IAAI;CACtD,MAAM,UAAU,YAAY,GAAG;CAE/B,MAAM,MAAM,cAAc;EACxB,MAAM;GAAE,MAAM,IAAI;GAAM,aAAa,IAAI,KAAK;EAAY;EAC1D,MAAM,IAAI;EACV,KAAK,OAAO,EAAE,WAAW;GACvB,MAAM,OAAO,MAAM,QAAQ,MAA2B,EAAE,iBAAiB,CAAC;GAC1E,IAAI,SAAS,GACX,QAAQ,KAAK,IAAI;EAErB;CACF,CAAC;CAED,MAAM,MAAM,OACV,MACA,YACoB;EACpB,IAAI;EACJ,IAAI;GACF,SAAS,UAAiB,MAAkB,IAAI,IAAI;EACtD,SAAS,OAAO;GAId,YAAY,KAAK,SAAS,QAAQ,CAAC;GACnC,UAAU,IAAI,MAAM,iBAAkB,MAAgB,OAAO;GAC7D,OAAO;EACT;EACA,OAAO,QAAQ,QAAQ;GAAE;GAAkB,SAAS,SAAS;EAAQ,CAAC;CACxE;CAEA,OAAO;EAAE;EAAK;CAAI;AACpB"}
1
+ {"version":3,"file":"subcommand-BV68pqwJ.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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cAAc;EACxB,MAAM;GAAE,MAAM,IAAI;GAAM,aAAa,IAAI,KAAK;EAAY;EAC1D,MAAM,IAAI;EACV,KAAK,OAAO,EAAE,WAAW;GACvB,MAAM,OAAO,MAAM,QAAQ,MAA2B,EAAE,iBAAiB,CAAC;GAC1E,IAAI,SAAS,GACX,QAAQ,KAAK,IAAI;EAErB;CACF,CAAC;CAED,MAAM,MAAM,OACV,MACA,YACoB;EACpB,IAAI;EACJ,IAAI;GACF,SAAS,UAAiB,MAAkB,IAAI,IAAI;EACtD,SAAS,OAAO;GAId,YAAY,KAAK,SAAS,QAAQ,CAAC;GACnC,UAAU,IAAI,MAAM,iBAAkB,MAAgB,OAAO;GAC7D,OAAO;EACT;EACA,OAAO,QAAQ,QAAQ;GAAE;GAAkB,SAAS,SAAS;EAAQ,CAAC;CACxE;CAEA,OAAO;EAAE;EAAK;CAAI;AACpB"}
@@ -1,7 +1,7 @@
1
1
  import { t as decodeJsonBytes } from "./bytes-BXdamO3L.js";
2
- import { r as parseBucketUri, t as loadAppConfig } from "./config-1tv0-Yzm.js";
2
+ import { r as parseBucketUri, t as loadAppConfig } from "./config-B6nTy8e2.js";
3
3
  import { i as isJsonMode, o as BaerlyError, r as emitSuccess } from "./baerly.js";
4
- import { a as TENANT_ARG, i as JSON_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-DoDA-K7d.js";
4
+ import { a as TENANT_ARG, i as JSON_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-BV68pqwJ.js";
5
5
  /** Build the canonical `current.json` key for one collection. */
6
6
  const currentJsonKeyFor = (app, tenant, collection) => `app/${app}/tenant/${tenant}/manifests/${collection}/current.json`;
7
7
  /** Derive the `collectionPrefix` (everything before `/current.json`). */
@@ -321,4 +321,4 @@ bundle.run;
321
321
  //#endregion
322
322
  export { estimateWritesPerMin, usageCmd };
323
323
 
324
- //# sourceMappingURL=usage-DBV1eQHC.js.map
324
+ //# sourceMappingURL=usage-BMZR8o6U.js.map
@@ -1 +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,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W,QAAQ,QAAQ,CAAC;EAEnD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,WAAW,OAAO;AAOP,OAAO"}
1
+ {"version":3,"file":"usage-BMZR8o6U.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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AE,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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gusto/baerly-storage",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Document database for S3 and Cloudflare R2 that runs in your request handler — tiny, LLM-friendly TypeScript API, no database server",
5
5
  "keywords": [
6
6
  "append-only-log",
@@ -64,6 +64,10 @@
64
64
  "types": "./dist/s3.d.ts",
65
65
  "import": "./dist/s3.js"
66
66
  },
67
+ "./gcs": {
68
+ "types": "./dist/gcs.d.ts",
69
+ "import": "./dist/gcs.js"
70
+ },
67
71
  "./maintenance": {
68
72
  "types": "./dist/maintenance.d.ts",
69
73
  "import": "./dist/maintenance.js"
@@ -97,7 +101,7 @@
97
101
  "access": "public"
98
102
  },
99
103
  "dependencies": {
100
- "@logtape/logtape": "2.2.2"
104
+ "@logtape/logtape": "2.2.4"
101
105
  },
102
106
  "devDependencies": {
103
107
  "@arethetypeswrong/cli": "^0.18.4",
@@ -139,9 +143,9 @@
139
143
  "vitest": "^4.1.9",
140
144
  "yaml": "2.9.0",
141
145
  "@baerly/adapter-cloudflare": "0.1.0",
142
- "@baerly/client": "0.1.0",
143
146
  "@baerly/adapter-node": "0.1.0",
144
147
  "@baerly/dev": "0.1.0",
148
+ "@baerly/client": "0.1.0",
145
149
  "@baerly/protocol": "0.1.0",
146
150
  "@baerly/server": "0.1.0"
147
151
  },
@@ -179,7 +183,7 @@
179
183
  "baerly": "node dist/baerly.js",
180
184
  "release": "node scripts/publish.mjs",
181
185
  "changeset": "changeset",
182
- "changeset:version": "changeset version && node scripts/gen-spec.ts && rm -f packages/create-baerly-storage/CHANGELOG.md",
186
+ "changeset:version": "changeset version && node scripts/gen-spec.ts && node scripts/check-version-matrix.ts --write && rm -f packages/create-baerly-storage/CHANGELOG.md",
183
187
  "format": "oxfmt .",
184
188
  "format:check": "oxfmt --check .",
185
189
  "lint": "oxlint tests packages",
@@ -207,6 +211,7 @@
207
211
  "verify:agent": "tsgo --noEmit --pretty false && oxlint --format=unix --quiet tests packages && pnpm run verify:rest && pnpm run verify:docs",
208
212
  "verify:spec": "node scripts/check-spec-drift.ts",
209
213
  "verify:version-matrix": "node scripts/check-version-matrix.ts",
214
+ "verify:artifacts": "node scripts/check-spec-drift.ts && node scripts/check-version-matrix.ts",
210
215
  "verify:docs": "node scripts/verify-docs.mjs && node scripts/verify-docs-taxonomy.mjs && remark . --quiet --frail --no-stdout && node scripts/verify-mermaid.mjs",
211
216
  "verify:doc-taxonomy": "node scripts/verify-docs-taxonomy.mjs",
212
217
  "verify:doc-links": "remark . --quiet --frail --no-stdout",
@@ -220,6 +225,7 @@
220
225
  "bench:r2:interpret": "node --import ./bench/register-hooks.mjs bench/r2-contention-interpret.ts",
221
226
  "bench:load": "node --import ./bench/register-hooks.mjs bench/load-harness/cli.ts",
222
227
  "bench:load:minio": "MINIO=1 node --import ./bench/register-hooks.mjs bench/load-harness/cli.ts --variant=node-minio",
228
+ "bench:load:gcs": "GCS=1 node --import ./bench/register-hooks.mjs bench/load-harness/cli.ts --variant=node-gcs",
223
229
  "bench:load:matrix": "node --import ./bench/register-hooks.mjs bench/load-harness/matrix.ts",
224
230
  "bench:lsn-reverse-walk": "node --import ./bench/register-hooks.mjs bench/lsn-reverse-walk.ts",
225
231
  "bench:fold-cost": "node --import ./bench/register-hooks.mjs bench/fold-cost.ts",