@gusto/baerly-storage 0.1.1 → 0.2.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 (114) hide show
  1. package/README.md +27 -3
  2. package/dist/API.md +103 -22
  3. package/dist/{app-config-Dj_nGBfj.d.ts → app-config-C0Bbw_Z6.d.ts} +9 -9
  4. package/dist/app-config.d.ts +1 -1
  5. package/dist/auth.d.ts +1 -1
  6. package/dist/baerly.js +10 -10
  7. package/dist/baerly.js.map +1 -1
  8. package/dist/bytes-BXdamO3L.js +11 -0
  9. package/dist/bytes-BXdamO3L.js.map +1 -0
  10. package/dist/{client-CC5yVs1S.d.ts → client-DYZfoZb9.d.ts} +3 -3
  11. package/dist/client-react.d.ts +76 -85
  12. package/dist/client-react.js +95 -53
  13. package/dist/client-react.js.map +1 -1
  14. package/dist/client.d.ts +3 -3
  15. package/dist/cloudflare.d.ts +31 -4
  16. package/dist/cloudflare.js +72 -6
  17. package/dist/cloudflare.js.map +1 -1
  18. package/dist/{config-Bsg8wgwo.js → config-DVfDGyw1.js} +82 -2
  19. package/dist/config-DVfDGyw1.js.map +1 -0
  20. package/dist/{context-Oj7ffwD-.js → context-DRZ3tZ5l.js} +3 -2
  21. package/dist/{context-Oj7ffwD-.js.map → context-DRZ3tZ5l.js.map} +1 -1
  22. package/dist/{cost-B1WiZxlf.js → cost-CQt1YRkA.js} +3 -4
  23. package/dist/{cost-B1WiZxlf.js.map → cost-CQt1YRkA.js.map} +1 -1
  24. package/dist/{current-json-BkatBzF7.js → current-json-C-EyJqs0.js} +107 -5
  25. package/dist/current-json-C-EyJqs0.js.map +1 -0
  26. package/dist/{db-aRMK_0R0.d.ts → db-BM3y2JQw.d.ts} +3 -3
  27. package/dist/{deploy-BB-wqbhf.js → deploy-CrAbfgCq.js} +2 -2
  28. package/dist/{deploy-BB-wqbhf.js.map → deploy-CrAbfgCq.js.map} +1 -1
  29. package/dist/dev-vite.d.ts +3 -3
  30. package/dist/dev-vite.js +3 -3
  31. package/dist/dev.d.ts +1 -1
  32. package/dist/dev.js +1 -1
  33. package/dist/{doctor-B8h9GCN9.js → doctor-Db-hzPmE.js} +144 -7
  34. package/dist/doctor-Db-hzPmE.js.map +1 -0
  35. package/dist/{dump-BHo_sIMZ.js → dump-BYA55NLP.js} +3 -4
  36. package/dist/{dump-BHo_sIMZ.js.map → dump-BYA55NLP.js.map} +1 -1
  37. package/dist/errors-DOdL95kK.js.map +1 -1
  38. package/dist/{export-Dz2PZKSR.js → export-Bhbz90-z.js} +4 -5
  39. package/dist/{export-Dz2PZKSR.js.map → export-Bhbz90-z.js.map} +1 -1
  40. package/dist/{fsck-DEz9lyCy.js → fsck-CPPZWt9p.js} +5 -8
  41. package/dist/fsck-CPPZWt9p.js.map +1 -0
  42. package/dist/{http-DeJEeUcO.js → http-Cw8p6y5b.js} +5 -5
  43. package/dist/{http-DeJEeUcO.js.map → http-Cw8p6y5b.js.map} +1 -1
  44. package/dist/http.d.ts +3 -3
  45. package/dist/http.js +1 -1
  46. package/dist/{index-m6pY8iRU.d.ts → index-C3JAH1Yo.d.ts} +14 -2
  47. package/dist/{index-5lX_5NxZ.d.ts → index-DSvwEUeF.d.ts} +63 -54
  48. package/dist/{index-DPaQhAro.d.ts → index-DwDTWPSU.d.ts} +2 -2
  49. package/dist/{index-spCBsIwm.d.ts → index-cUY-36AN.d.ts} +3 -3
  50. package/dist/index.d.ts +5 -5
  51. package/dist/index.js +3 -3
  52. package/dist/{indexes-BIH73Uv4.d.ts → indexes-DAu2AkTW.d.ts} +2 -2
  53. package/dist/{inspect-x02aFWnh.js → inspect-Bdbzvi-_.js} +5 -6
  54. package/dist/{inspect-x02aFWnh.js.map → inspect-Bdbzvi-_.js.map} +1 -1
  55. package/dist/maintenance-BRrThz8V.d.ts +449 -0
  56. package/dist/maintenance-BvOv6BMM.js +1295 -0
  57. package/dist/maintenance-BvOv6BMM.js.map +1 -0
  58. package/dist/maintenance-ClzBC1Vv.js +1895 -0
  59. package/dist/maintenance-ClzBC1Vv.js.map +1 -0
  60. package/dist/maintenance.d.ts +2 -323
  61. package/dist/maintenance.js +2 -2
  62. package/dist/node.d.ts +20 -79
  63. package/dist/node.js +2 -2
  64. package/dist/{observability-2IDYRuZK.js → observability-CpOiEN0k.js} +2 -2
  65. package/dist/{observability-2IDYRuZK.js.map → observability-CpOiEN0k.js.map} +1 -1
  66. package/dist/observability.d.ts +2 -2
  67. package/dist/observability.js +2 -2
  68. package/dist/{plan-Cs17VqjU.js → plan-DOTl21vq.js} +3 -4
  69. package/dist/{plan-Cs17VqjU.js.map → plan-DOTl21vq.js.map} +1 -1
  70. package/dist/{query-DcSbFLJt.js → query-BmiQy328.js} +58 -26
  71. package/dist/query-BmiQy328.js.map +1 -0
  72. package/dist/{rebuild-index-DwXM0WfA.js → rebuild-index-DC_nR6wP.js} +4 -5
  73. package/dist/{rebuild-index-DwXM0WfA.js.map → rebuild-index-DC_nR6wP.js.map} +1 -1
  74. package/dist/{restore-CbKVMMpm.js → restore-C6IcmLeA.js} +44 -120
  75. package/dist/restore-C6IcmLeA.js.map +1 -0
  76. package/dist/{log-walk-DIru96UT.js → snapshot-SS8USDUF.js} +187 -20
  77. package/dist/snapshot-SS8USDUF.js.map +1 -0
  78. package/dist/{src-Cr9C7_tT.js → src-DU1sCMlr.js} +315 -278
  79. package/dist/src-DU1sCMlr.js.map +1 -0
  80. package/dist/{src-n0Te1r98.js → src-QQ7jDeL2.js} +25 -6
  81. package/dist/src-QQ7jDeL2.js.map +1 -0
  82. package/dist/{src-Chafbw8r.js → src-zhEAmmF7.js} +35 -4
  83. package/dist/src-zhEAmmF7.js.map +1 -0
  84. package/dist/{bucket-uri-BrDEYvzy.js → subcommand-DZcHcsYp.js} +222 -22
  85. package/dist/subcommand-DZcHcsYp.js.map +1 -0
  86. package/dist/{usage-RVUQMLop.js → usage-CLjirdD-.js} +4 -4
  87. package/dist/{usage-RVUQMLop.js.map → usage-CLjirdD-.js.map} +1 -1
  88. package/dist/{validate-DhH1lO8I.js → validate-DCq_0DIn.js} +2 -2
  89. package/dist/validate-DCq_0DIn.js.map +1 -0
  90. package/package.json +13 -6
  91. package/dist/bucket-uri-BrDEYvzy.js.map +0 -1
  92. package/dist/config-Bsg8wgwo.js.map +0 -1
  93. package/dist/current-json-BkatBzF7.js.map +0 -1
  94. package/dist/doctor-B8h9GCN9.js.map +0 -1
  95. package/dist/fsck-DEz9lyCy.js.map +0 -1
  96. package/dist/indexes-BXn7a06a.js +0 -297
  97. package/dist/indexes-BXn7a06a.js.map +0 -1
  98. package/dist/log-walk-DIru96UT.js.map +0 -1
  99. package/dist/maintenance-Bn6ul9aV.js +0 -758
  100. package/dist/maintenance-Bn6ul9aV.js.map +0 -1
  101. package/dist/query-DcSbFLJt.js.map +0 -1
  102. package/dist/rebuild-index-C5gTXryd.js +0 -119
  103. package/dist/rebuild-index-C5gTXryd.js.map +0 -1
  104. package/dist/restore-CbKVMMpm.js.map +0 -1
  105. package/dist/snapshot-D7C4_FSl.js +0 -71
  106. package/dist/snapshot-D7C4_FSl.js.map +0 -1
  107. package/dist/snapshot-z_N9hpTe.js +0 -917
  108. package/dist/snapshot-z_N9hpTe.js.map +0 -1
  109. package/dist/src-Chafbw8r.js.map +0 -1
  110. package/dist/src-Cr9C7_tT.js.map +0 -1
  111. package/dist/src-n0Te1r98.js.map +0 -1
  112. package/dist/subcommand-BWs6K7zb.js +0 -110
  113. package/dist/subcommand-BWs6K7zb.js.map +0 -1
  114. package/dist/validate-DhH1lO8I.js.map +0 -1
@@ -1,7 +1,7 @@
1
- import { a as decodeJsonBytes, t as parseBucketUri } from "./bucket-uri-BrDEYvzy.js";
2
- import { t as loadAppConfig } from "./config-Bsg8wgwo.js";
1
+ import { t as decodeJsonBytes } from "./bytes-BXdamO3L.js";
2
+ import { t as loadAppConfig } from "./config-DVfDGyw1.js";
3
+ import { n as parseBucketUri, t as defineBaerlySubcommand } from "./subcommand-DZcHcsYp.js";
3
4
  import { i as isJsonMode, o as BaerlyError, r as emitSuccess } from "./baerly.js";
4
- import { t as defineBaerlySubcommand } from "./subcommand-BWs6K7zb.js";
5
5
  /** Number of trailing log entries the estimator reads per collection. */
6
6
  const SAMPLE_SIZE = 120;
7
7
  /** Build the canonical `current.json` key for one collection. */
@@ -336,4 +336,4 @@ bundle.run;
336
336
  //#endregion
337
337
  export { estimateWritesPerMin, usageCmd };
338
338
 
339
- //# sourceMappingURL=usage-RVUQMLop.js.map
339
+ //# sourceMappingURL=usage-CLjirdD-.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"usage-RVUQMLop.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\n * `docs/about/thesis.md:50-68`), and prints one finding per collection\n * — `info` when well under the ceiling, `warning` when approaching or\n * exceeding it.\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 { defineBaerlySubcommand } 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. */\nconst 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: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\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":";;;;;AAoEA,MAAM,cAAc;;AA+BpB,MAAa,qBAAqB,KAAa,QAAgB,eAC7D,OAAO,IAAI,UAAU,OAAO,aAAa,WAAW;;A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M,aAAa;IAAE;IAAK;GAAO,GAAG,OAAO,SAAS,QAAQ;EAC9D;EAEA,IAAI,WAAW,GACb,YAAY;GACV,SAAS;GACT,QAAQ;GACR;GACA,UAAU,SAAS,KAAK,OAAO;IAC7B,UAAU,EAAE;IACZ,OAAO,EAAE;IACT,SAAS,EAAE;IACX,GAAI,EAAE,QAAQ,KAAA,KAAa,EAAE,QAAQ,MAAM,EAAE,KAAK,EAAE,IAAI;GAC1D,EAAE;EACJ,CAAC;OAED,QAAQ,OAAO,MAAM,WAAW,QAAQ,QAAQ,CAAC;EAEnD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,WAAW,OAAO;AAOP,OAAO"}
1
+ {"version":3,"file":"usage-CLjirdD-.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\n * `docs/about/thesis.md:50-68`), and prints one finding per collection\n * — `info` when well under the ceiling, `warning` when approaching or\n * exceeding it.\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 { defineBaerlySubcommand } 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. */\nconst 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: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\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":";;;;;AAoEA,MAAM,cAAc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D,MAAM,IAAI,YACR,iBACA,kEACF;GAEF,MAAM,SAAS,MAAM,eAAe,KAAK,MAAM;GAC/C,MAAM,aAAa;IAAE;IAAK;GAAO,GAAG,OAAO,SAAS,QAAQ;EAC9D;EAEA,IAAI,WAAW,GACb,YAAY;GACV,SAAS;GACT,QAAQ;GACR;GACA,UAAU,SAAS,KAAK,OAAO;IAC7B,UAAU,EAAE;IACZ,OAAO,EAAE;IACT,SAAS,EAAE;IACX,GAAI,EAAE,QAAQ,KAAA,KAAa,EAAE,QAAQ,MAAM,EAAE,KAAK,EAAE,IAAI;GAC1D,EAAE;EACJ,CAAC;OAED,QAAQ,OAAO,MAAM,WAAW,QAAQ,QAAQ,CAAC;EAEnD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,WAAW,OAAO;AAOP,OAAO"}
@@ -334,7 +334,7 @@ const validateClause = (clause, index) => {
334
334
  const { op, field, value } = clause;
335
335
  if (typeof op !== "string" || !OP_NAMES.includes(op)) throw new BaerlyError("InvalidConfig", `Predicate clause at index ${index} has unsupported op ${JSON.stringify(op)} — supported: ${OP_NAMES.join(" / ")}.`);
336
336
  if (typeof field !== "string" || field.length === 0) throw new BaerlyError("InvalidConfig", `Predicate clause at index ${index} has empty / non-string field.`);
337
- if (field === "_id") throw new BaerlyError("InvalidConfig", "Predicates may not key on \"_id\"; use .get(id) / .update(id, patch) / .replace(id, doc) / .delete(id) instead.");
337
+ if (field === "_id" || field.startsWith("_id.")) throw new BaerlyError("InvalidConfig", "Predicates may not key on \"_id\"; use .get(id) / .update(id, patch) / .replace(id, doc) / .delete(id) instead.");
338
338
  if (op === "in") {
339
339
  if (!Array.isArray(value)) throw new BaerlyError("InvalidConfig", `Predicate clause at index ${index} (op="in", field=${JSON.stringify(field)}) must carry an array value.`);
340
340
  if (value.length === 0) throw new BaerlyError("UnsatisfiablePredicate", `Predicate clause at index ${index} (op="in", field=${JSON.stringify(field)}) has empty value array — no document can match.`);
@@ -374,4 +374,4 @@ const validateRangeBound = (value, field, clauseIndex) => {
374
374
  //#endregion
375
375
  export { matchesWire as n, validateWire as t };
376
376
 
377
- //# sourceMappingURL=validate-DhH1lO8I.js.map
377
+ //# sourceMappingURL=validate-DCq_0DIn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate-DCq_0DIn.js","names":[],"sources":["../packages/protocol/src/query/_internals.ts","../packages/protocol/src/query/matches.ts","../packages/protocol/src/query/satisfiable.ts","../packages/protocol/src/query/validate.ts"],"sourcesContent":["/**\n * Shared helpers for the predicate algebras in `./validate.ts`,\n * `./matches.ts`, and `./merge.ts`. These exist as a single module\n * because more than one of those files uses them and duplicating\n * the implementations would drift over time.\n *\n * Only {@link deepEqualDocumentValue} is part of the public surface;\n * the comparator primitives (`compareScalar`, `sameComparableType`,\n * `formatPath`) are internal to the protocol package and imported\n * by `./validate.ts` / `./merge.ts` / `./normalize.ts` directly.\n */\n\nimport type { DocumentValue } from \"../json.ts\";\n\n/** @internal Same primitive type for comparison purposes. */\nexport const sameComparableType = (a: DocumentValue, b: DocumentValue): boolean =>\n (typeof a === \"string\" && typeof b === \"string\") ||\n (typeof a === \"number\" && typeof b === \"number\");\n\n/**\n * @internal Returns negative / zero / positive for a<b / a==b / a>b.\n */\nexport const compareScalar = (a: DocumentValue, b: DocumentValue): number => {\n if (typeof a === \"number\" && typeof b === \"number\") {\n return a - b;\n }\n if (typeof a === \"string\" && typeof b === \"string\") {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n }\n return 0;\n};\n\n/** @internal Render a predicate path for use in error messages. */\nexport const formatPath = (path: ReadonlyArray<string>): string =>\n path.length === 0 ? \"<root>\" : path.map((p) => JSON.stringify(p)).join(\".\");\n\n/**\n * Recursive structural equality for `DocumentValue` values. Lifted to\n * `export` so the filtered-index implication checker (in\n * `@baerly/server`'s query planner) and other callers can reuse the\n * same comparison rule the validator + merger already trust. Two\n * values `a` and `b` are equal iff:\n *\n * - they are reference-equal (covers primitives and object identity);\n * - or they are both non-`null` objects with the same key set, and\n * every value pair is recursively equal.\n *\n * Arrays are out-of-band for `DocumentValue`; this function rejects\n * them implicitly via the same key-set walk (an array reads as an\n * object with numeric-string keys plus a `length` exposure that\n * `Object.keys` happens to skip — defensive callers should still gate\n * with `Array.isArray` first).\n */\nexport const deepEqualDocumentValue = (a: DocumentValue, b: DocumentValue): boolean => {\n if (a === b) {\n return true;\n } // primitives + object identity\n if (typeof a !== \"object\" || typeof b !== \"object\") {\n return false;\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) {\n return false;\n }\n for (const key of aKeys) {\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent — a key in aKeys but absent from b makes b[key] undefined, which the `aSub === undefined || bSub === undefined` guard below catches identically; no input observes the difference.\n if (!(key in b)) {\n return false;\n }\n const aSub = (a as Record<string, DocumentValue>)[key];\n const bSub = (b as Record<string, DocumentValue>)[key];\n // Stryker disable next-line LogicalOperator,ConditionalExpression: equivalent — this guard is a redundant fast-path. Whichever way it is mutated (operator `||`→`&&`, or either `=== undefined` operand forced to false), a slot that is undefined still flows into deepEqualDocumentValue below, whose typeof check returns false for `(undefined, defined)`; the only case that reaches `true` is both-undefined, which the surviving sibling operand still catches. No input over 500k randomized DocumentValues observes a difference.\n if (aSub === undefined || bSub === undefined) {\n return false;\n }\n if (!deepEqualDocumentValue(aSub, bSub)) {\n return false;\n }\n }\n return true;\n};\n","/**\n * Wire predicate evaluator. Walks a validated {@link PredicateWire}\n * against a `JSONObject` document and returns `true` iff every\n * clause holds. Multiple clauses across all fields AND together.\n *\n * Pre-condition: `wire` must have been returned by\n * {@link validateWire} (see `./validate.ts`). Passing an\n * un-validated wire is a caller bug; behaviour is undefined.\n *\n * Companion modules: `./validate.ts` (construction-time check),\n * `./merge.ts` (AND-merge), `./wire.ts` (types).\n */\n\nimport type { DocumentValue, JSONObject, JSONValue } from \"../json.ts\";\n\nimport type { PredicateClause, PredicateWire } from \"./wire.ts\";\n\n/**\n * Evaluate a validated wire-form predicate against a `JSONObject`\n * document. Returns `true` iff every clause holds.\n *\n * @example\n * ```ts\n * matchesWire(\n * { clauses: [{ op: \"eq\", field: \"status\", value: \"open\" }] },\n * { status: \"open\", priority: \"p1\" },\n * ); // true\n *\n * matchesWire(\n * { clauses: [{ op: \"in\", field: \"priority\", value: [\"p1\", \"p2\"] }] },\n * { priority: \"p3\" },\n * ); // false\n *\n * matchesWire(\n * {\n * clauses: [\n * { op: \"gte\", field: \"count\", value: 1 },\n * { op: \"lt\", field: \"count\", value: 10 },\n * ],\n * },\n * { count: 5 },\n * ); // true\n * ```\n */\nexport const matchesWire = (wire: PredicateWire, doc: JSONObject): boolean => {\n for (const clause of wire.clauses) {\n const actual = lookupPath(doc, clause.field);\n if (!matchesClause(clause, actual)) {\n return false;\n }\n }\n return true;\n};\n\nconst lookupPath = (doc: JSONObject, field: string): JSONValue | undefined => {\n // Fast path: no dot → top-level lookup. Avoids allocating a split\n // array for the common case.\n // Stryker disable next-line StringLiteral,BlockStatement,ConditionalExpression: fast-path equivalence — for any valid field, the slow split-and-traverse path produces the same result; the fast path is a performance optimisation only\n if (!field.includes(\".\")) {\n return doc[field];\n }\n const segments = field.split(\".\");\n let cursor: JSONValue | undefined = doc;\n for (const segment of segments) {\n if (\n // Stryker disable next-line ConditionalExpression: redundant guard — cursor===undefined is always caught by the typeof check on the next line (typeof undefined!==\"object\" is true); removing this check is observationally equivalent\n cursor === undefined ||\n cursor === null ||\n // Stryker disable next-line ConditionalExpression: redundant guard — for non-object primitives, (primitive as JSONObject)[segment] returns undefined; the next iteration's cursor===undefined check catches it; removing this check produces the same return value\n typeof cursor !== \"object\" ||\n Array.isArray(cursor)\n ) {\n // Traversal hit a primitive, null, missing key, or array\n // before consuming the path. Predicate cannot match.\n return undefined;\n }\n cursor = (cursor as JSONObject)[segment];\n }\n return cursor;\n};\n\nconst matchesClause = (clause: PredicateClause, actual: JSONValue | undefined): boolean => {\n switch (clause.op) {\n case \"eq\": {\n return matchesEq(clause.value as DocumentValue, actual);\n }\n case \"in\": {\n return matchesIn(clause.value as ReadonlyArray<DocumentValue>, actual);\n }\n case \"gt\": {\n return compareGT(actual, clause.value as DocumentValue, false);\n }\n case \"gte\": {\n return compareGT(actual, clause.value as DocumentValue, true);\n }\n case \"lt\": {\n return compareLT(actual, clause.value as DocumentValue, false);\n }\n case \"lte\": {\n return compareLT(actual, clause.value as DocumentValue, true);\n }\n }\n};\n\nconst matchesEq = (expected: DocumentValue, actual: JSONValue | undefined): boolean => {\n if (typeof expected === \"object\") {\n // Nested object equality is a sub-predicate match — open-world:\n // doc may carry extra keys. The object-form normaliser flattens\n // nested sub-predicates to dotted-path clauses on the way in, so\n // the only callers reaching this branch are callback-form\n // `q.eq(\"nested\", { ... })`.\n if (\n // Stryker disable next-line ConditionalExpression: redundant guard — actual===undefined is caught by the typeof check below (typeof undefined!==\"object\" is true); removing this check produces the same false result\n actual === undefined ||\n actual === null ||\n typeof actual !== \"object\" ||\n Array.isArray(actual)\n ) {\n return false;\n }\n for (const subKey of Object.keys(expected)) {\n const subExpected = (expected as Record<string, DocumentValue>)[subKey];\n if (subExpected === undefined) {\n continue;\n }\n const subActual = (actual as JSONObject)[subKey];\n if (!matchesEq(subExpected, subActual)) {\n return false;\n }\n }\n return true;\n }\n return expected === actual;\n};\n\nconst matchesIn = (\n members: ReadonlyArray<DocumentValue>,\n actual: JSONValue | undefined,\n): boolean => {\n for (const m of members) {\n // Stryker disable next-line ConditionalExpression: equivalence — for non-null primitives, matchesEq(m, actual) reduces to `m === actual` (the typeof check fails); routing all members through matchesEq (→true) gives the same result as the two-branch structure\n if (typeof m === \"object\") {\n if (matchesEq(m, actual)) {\n return true;\n }\n } else if (m === actual) {\n return true;\n }\n }\n return false;\n};\n\nconst compareGT = (\n actual: JSONValue | undefined,\n bound: DocumentValue,\n inclusive: boolean,\n): boolean => {\n if (typeof bound === \"string\") {\n return typeof actual === \"string\" && (inclusive ? actual >= bound : actual > bound);\n }\n if (typeof bound === \"number\") {\n return typeof actual === \"number\" && (inclusive ? actual >= bound : actual > bound);\n }\n // Validator forbids boolean / null / object range bounds; defensive miss.\n return false;\n};\n\nconst compareLT = (\n actual: JSONValue | undefined,\n bound: DocumentValue,\n inclusive: boolean,\n): boolean => {\n if (typeof bound === \"string\") {\n return typeof actual === \"string\" && (inclusive ? actual <= bound : actual < bound);\n }\n if (typeof bound === \"number\") {\n return typeof actual === \"number\" && (inclusive ? actual <= bound : actual < bound);\n }\n return false;\n};\n","/**\n * Per-field satisfiability check for a {@link PredicateWire}. Groups\n * clauses by field, then runs the same logic the pre-redesign\n * `assertOpObjectSatisfiable` ran on a single op-object — but\n * generalised across N clauses on the same field (the wire merger\n * concatenates lists without coalescing).\n *\n * Triggers:\n * - Two `eq` clauses on the same field with different values →\n * `InvalidConfig` (the same conflict that pre-redesign\n * `mergePredicates` threw on shared primitive keys).\n * - Range bounds with `lo > hi` (or `lo == hi` with strict on\n * either side) → `UnsatisfiablePredicate`.\n * - `eq` value outside the residual range interval or absent from\n * every `in` set on the same field → `UnsatisfiablePredicate`.\n * - `in` sets that intersect to empty across multiple clauses →\n * `UnsatisfiablePredicate`.\n *\n * Used by both `./validate.ts` (wire-arrival check) and\n * `./merge.ts` (post-merge re-check, kept in lockstep).\n */\n\nimport { BaerlyError } from \"../errors.ts\";\nimport type { DocumentValue } from \"../json.ts\";\n\nimport {\n compareScalar,\n deepEqualDocumentValue,\n formatPath,\n sameComparableType,\n} from \"./_internals.ts\";\nimport type { PredicateClause, PredicateWire } from \"./wire.ts\";\n\ninterface FieldGroup {\n readonly eqs: DocumentValue[];\n readonly ins: ReadonlyArray<DocumentValue>[];\n lo?: { value: DocumentValue; inclusive: boolean };\n hi?: { value: DocumentValue; inclusive: boolean };\n}\n\nconst groupByField = (wire: PredicateWire): Map<string, FieldGroup> => {\n const out = new Map<string, FieldGroup>();\n for (const clause of wire.clauses) {\n let group = out.get(clause.field);\n if (group === undefined) {\n group = { eqs: [], ins: [] };\n out.set(clause.field, group);\n }\n applyClause(group, clause.field, clause);\n }\n return out;\n};\n\nconst applyClause = (group: FieldGroup, field: string, clause: PredicateClause): void => {\n switch (clause.op) {\n case \"eq\": {\n group.eqs.push(clause.value as DocumentValue);\n return;\n }\n case \"in\": {\n group.ins.push(clause.value as ReadonlyArray<DocumentValue>);\n return;\n }\n case \"gt\": {\n tightenLower(group, field, clause.value as DocumentValue, false);\n return;\n }\n case \"gte\": {\n tightenLower(group, field, clause.value as DocumentValue, true);\n return;\n }\n case \"lt\": {\n tightenUpper(group, field, clause.value as DocumentValue, false);\n return;\n }\n case \"lte\": {\n tightenUpper(group, field, clause.value as DocumentValue, true);\n return;\n }\n }\n};\n\nconst tightenLower = (\n group: FieldGroup,\n field: string,\n value: DocumentValue,\n inclusive: boolean,\n): void => {\n if (group.lo === undefined) {\n group.lo = { value, inclusive };\n return;\n }\n if (!sameComparableType(group.lo.value, value)) {\n // Type-incompatible bounds on the same field — the user wrote\n // (say) `q.gt(\"x\", 1).gt(\"x\", \"a\")`. Range matching is type-\n // strict at evaluation time so this is always-miss; surface\n // eagerly as `UnsatisfiablePredicate`.\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has type-incompatible lower bounds (${JSON.stringify(group.lo.value)} vs ${JSON.stringify(value)}).`,\n );\n }\n const c = compareScalar(group.lo.value, value);\n // Stryker disable next-line ConditionalExpression: two sub-expression-to-true mutants are\n // equivalent. (1) `inclusive === false → true`: fires when c=0, existing=inclusive,\n // new=inclusive — tighten updates lo to {value, inclusive=true}, identical to the existing\n // {same value, inclusive=true}; no observable change. (2) `group.lo.inclusive === true → true`:\n // fires when c=0, new=exclusive, existing=exclusive — tighten updates lo to {value, false},\n // identical to existing {same value, false}; no observable change.\n if (c < 0 || (c === 0 && inclusive === false && group.lo.inclusive === true)) {\n group.lo = { value, inclusive };\n }\n};\n\nconst tightenUpper = (\n group: FieldGroup,\n field: string,\n value: DocumentValue,\n inclusive: boolean,\n): void => {\n if (group.hi === undefined) {\n group.hi = { value, inclusive };\n return;\n }\n if (!sameComparableType(group.hi.value, value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has type-incompatible upper bounds (${JSON.stringify(group.hi.value)} vs ${JSON.stringify(value)}).`,\n );\n }\n const c = compareScalar(group.hi.value, value);\n // Stryker disable next-line ConditionalExpression: two sub-expression-to-true mutants are\n // equivalent. (1) `inclusive === false → true`: fires when c=0, existing=inclusive,\n // new=inclusive — tighten updates hi to {value, inclusive=true}, same as existing; no change.\n // (2) `group.hi.inclusive === true → true`: fires when c=0, new=exclusive, existing=exclusive —\n // tighten updates hi to {value, false}, same as existing; no observable change.\n if (c > 0 || (c === 0 && inclusive === false && group.hi.inclusive === true)) {\n group.hi = { value, inclusive };\n }\n};\n\nconst intersectInSets = (\n sets: ReadonlyArray<ReadonlyArray<DocumentValue>>,\n): ReadonlyArray<DocumentValue> => {\n // Stryker disable ConditionalExpression,BlockStatement,ArrayDeclaration: dead-code guard\n // — callers only invoke intersectInSets when group.ins.length > 1 (i.e., sets.length >= 2),\n // so sets.length === 0 is unreachable in production. Any mutation here is an equivalent mutant.\n if (sets.length === 0) {\n return [];\n }\n // Stryker restore ConditionalExpression,BlockStatement,ArrayDeclaration\n let acc: ReadonlyArray<DocumentValue> = sets[0]!;\n for (let i = 1; i < sets.length; i++) {\n const next: DocumentValue[] = [];\n for (const a of acc) {\n for (const b of sets[i]!) {\n if (deepEqualDocumentValue(a, b)) {\n next.push(a);\n break;\n }\n }\n }\n acc = next;\n }\n return acc;\n};\n\n/**\n * Check that every per-field clause group on `wire` is jointly\n * satisfiable. Throws `BaerlyError{code:\"UnsatisfiablePredicate\"}`\n * (or `\"InvalidConfig\"` for conflicting `eq` clauses) on the\n * first contradiction. Returns `void` on success.\n */\nexport const assertWireSatisfiable = (wire: PredicateWire): void => {\n const groups = groupByField(wire);\n for (const [field, group] of groups) {\n // Multiple `eq` clauses on the same field must agree.\n // Stryker disable next-line EqualityOperator,ConditionalExpression: equivalent — the inner\n // loop starts at i=1, so with 0 or 1 eqs the loop body never executes regardless of whether\n // we enter the outer if. `>= 1` enters with 1 eq (0 loop iterations); `true` enters with 0\n // eqs (0 loop iterations). Both are observationally identical to `> 1`.\n if (group.eqs.length > 1) {\n for (let i = 1; i < group.eqs.length; i++) {\n if (!deepEqualDocumentValue(group.eqs[0]!, group.eqs[i]!)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Conflicting equality clauses on field ${formatPath([field])} (${JSON.stringify(group.eqs[0]!)} vs ${JSON.stringify(group.eqs[i]!)}). Predicate chains must agree on shared equality.`,\n );\n }\n }\n }\n const eq = group.eqs[0];\n // Range interval must be non-empty.\n if (\n group.lo !== undefined &&\n group.hi !== undefined &&\n sameComparableType(group.lo.value, group.hi.value)\n ) {\n const c = compareScalar(group.lo.value, group.hi.value);\n if (c > 0 || (c === 0 && (!group.lo.inclusive || !group.hi.inclusive))) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has empty interval (lo=${JSON.stringify(group.lo.value)} ${group.lo.inclusive ? \"gte\" : \"gt\"}, hi=${JSON.stringify(group.hi.value)} ${group.hi.inclusive ? \"lte\" : \"lt\"}).`,\n );\n }\n }\n // `eq` outside the residual interval / membership set.\n if (eq !== undefined) {\n if (group.lo !== undefined) {\n if (!sameComparableType(eq, group.lo.value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} (${typeof eq}) is type-incompatible with lower bound ${JSON.stringify(group.lo.value)} (${typeof group.lo.value}); range ops require matching primitive types.`,\n );\n }\n const c = compareScalar(eq, group.lo.value);\n if (c < 0 || (c === 0 && !group.lo.inclusive)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} excluded by lower bound ${JSON.stringify(group.lo.value)} (${group.lo.inclusive ? \"gte\" : \"gt\"}).`,\n );\n }\n }\n if (group.hi !== undefined) {\n if (!sameComparableType(eq, group.hi.value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} (${typeof eq}) is type-incompatible with upper bound ${JSON.stringify(group.hi.value)} (${typeof group.hi.value}); range ops require matching primitive types.`,\n );\n }\n const c = compareScalar(eq, group.hi.value);\n if (c > 0 || (c === 0 && !group.hi.inclusive)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} excluded by upper bound ${JSON.stringify(group.hi.value)} (${group.hi.inclusive ? \"lte\" : \"lt\"}).`,\n );\n }\n }\n // Stryker disable next-line EqualityOperator,ConditionalExpression: equivalent — the for-of\n // loop over group.ins is a no-op when group.ins is empty, so `>= 0` (always true) and\n // `true` (always enter) produce identical behavior: zero iterations when ins is empty,\n // same iterations as `> 0` when ins is non-empty.\n if (group.ins.length > 0) {\n for (const set of group.ins) {\n let found = false;\n for (const m of set) {\n if (deepEqualDocumentValue(eq, m)) {\n found = true;\n break;\n }\n }\n if (!found) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} not present in in() set.`,\n );\n }\n }\n }\n }\n // Multiple `in` sets must intersect non-empty.\n // Stryker disable next-line EqualityOperator: equivalent — intersectInSets([single_set])\n // returns that set unchanged; since validateWire rejects empty in-arrays, the single set\n // is always non-empty, so isect.length === 0 is false and no throw occurs. `>= 1` (entering\n // with 1 in-set) behaves identically to `> 1` (skipping for 1 in-set).\n if (group.ins.length > 1) {\n const isect = intersectInSets(group.ins);\n if (isect.length === 0) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has empty in() intersection across multiple clauses.`,\n );\n }\n }\n }\n};\n","/**\n * Wire predicate validator. Walks a {@link PredicateWire} and throws\n * on a structurally bad clause (`BaerlyError{code:\"InvalidConfig\"}`)\n * or a per-field clause group that contradicts itself\n * (`BaerlyError{code:\"UnsatisfiablePredicate\"}`).\n *\n * The object-form normaliser at `./normalize.ts` enforces shape on\n * the way in (rejecting `$`-keys / non-scalars / null / undefined);\n * the callback builder at `./builder.ts` enforces shape via the\n * type system. This validator is the wire-arrival check: it runs\n * over already-normalised clauses, defending against raw-`fetch`\n * callers who bypass the typed seam and submit arbitrary JSON.\n *\n * Companion modules: `./matches.ts` (evaluator), `./merge.ts`\n * (AND-merge). Shared helpers live in `./_internals.ts`.\n */\n\nimport { BaerlyError } from \"../errors.ts\";\n\nimport { assertWireSatisfiable } from \"./satisfiable.ts\";\nimport type { PredicateClause, PredicateOpName, PredicateWire } from \"./wire.ts\";\n\nconst OP_NAMES: ReadonlyArray<PredicateOpName> = [\"eq\", \"gt\", \"gte\", \"lt\", \"lte\", \"in\"];\nconst RANGE_OPS: ReadonlyArray<PredicateOpName> = [\"gt\", \"gte\", \"lt\", \"lte\"];\n\n/**\n * Validate a normalised predicate wire. Throws\n * `BaerlyError{code:\"InvalidConfig\"}` on a structurally bad clause,\n * or `BaerlyError{code:\"UnsatisfiablePredicate\"}` when a clause\n * group on one field contradicts itself.\n *\n * Returns the wire unchanged on success — callers can thread the\n * validated wire forward.\n *\n * @example\n * ```ts\n * validateWire({ clauses: [{ op: \"eq\", field: \"status\", value: \"open\" }] }); // ok\n * validateWire({ clauses: [{ op: \"in\", field: \"priority\", value: [] }] }); // throws UnsatisfiablePredicate\n * validateWire({ clauses: [{ op: \"eq\", field: \"_id\", value: \"x\" }] }); // throws InvalidConfig (top-level _id)\n * ```\n */\nexport const validateWire = (wire: PredicateWire): PredicateWire => {\n if (\n wire === null ||\n typeof wire !== \"object\" ||\n !Array.isArray((wire as { clauses?: unknown }).clauses)\n ) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate wire must be an object with a \"clauses\" array.`,\n );\n }\n for (let i = 0; i < wire.clauses.length; i++) {\n validateClause(wire.clauses[i]!, i);\n }\n assertWireSatisfiable(wire);\n return wire;\n};\n\nconst validateClause = (clause: PredicateClause, index: number): void => {\n if (clause === null || typeof clause !== \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} must be an object — got ${JSON.stringify(clause)}.`,\n );\n }\n const { op, field, value } = clause;\n // Stryker disable next-line ConditionalExpression: `typeof op !== \"string\"` is redundant —\n // OP_NAMES contains only string literals; Array.prototype.includes uses SameValueZero\n // (effectively ===), so any non-string op is already rejected by the `!includes` half.\n // The early string-type check is a readability guard, not an observable branch.\n if (typeof op !== \"string\" || !(OP_NAMES as ReadonlyArray<string>).includes(op)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} has unsupported op ${JSON.stringify(op)} — supported: ${OP_NAMES.join(\" / \")}.`,\n );\n }\n if (typeof field !== \"string\" || field.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} has empty / non-string field.`,\n );\n }\n // Reject `_id` AND any nested `_id.<path>` — `Path<T>` excludes both\n // (`\"_id\" | \\`_id.${string}\\``), so a raw-wire caller (the threat this\n // validator names) must not slip a dotted `_id.x` past a check that\n // only matched the exact root field.\n if (field === \"_id\" || field.startsWith(\"_id.\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n 'Predicates may not key on \"_id\"; use .get(id) / .update(id, patch) / .replace(id, doc) / .delete(id) instead.',\n );\n }\n if (op === \"in\") {\n if (!Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} (op=\"in\", field=${JSON.stringify(field)}) must carry an array value.`,\n );\n }\n if (value.length === 0) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate clause at index ${index} (op=\"in\", field=${JSON.stringify(field)}) has empty value array — no document can match.`,\n );\n }\n for (let i = 0; i < value.length; i++) {\n validateMemberValue(value[i], field, index, i);\n }\n return;\n }\n if (Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} (op=${JSON.stringify(op)}, field=${JSON.stringify(field)}) must carry a primitive value, got an array — only op=\"in\" accepts arrays.`,\n );\n }\n if ((RANGE_OPS as ReadonlyArray<string>).includes(op)) {\n validateRangeBound(value, field, index);\n return;\n }\n validateScalar(value, field, index);\n};\n\nconst validateMemberValue = (\n value: unknown,\n field: string,\n clauseIndex: number,\n memberIndex: number,\n): void => {\n // Stryker disable next-line ConditionalExpression: `|| value === undefined` is redundant —\n // undefined falls through to `typeof value` = \"undefined\", which is caught by the\n // `t !== \"string\" && t !== \"number\" && t !== \"boolean\"` check below with the same\n // InvalidConfig code. The early check gives a more descriptive \"undefined\" message\n // but no input can distinguish the two code paths via the public error code alone.\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is ${value === null ? \"null\" : \"undefined\"} — members must be string / number / boolean / nested object.`,\n );\n }\n if (Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is an array — members must be string / number / boolean / nested object.`,\n );\n }\n const t = typeof value;\n if (t === \"object\") {\n return;\n }\n if (t !== \"string\" && t !== \"number\" && t !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} has unsupported type ${JSON.stringify(t)} — must be string / number / boolean / nested object.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n\nconst validateScalar = (value: unknown, field: string, clauseIndex: number): void => {\n // Stryker disable next-line ConditionalExpression: `|| value === undefined` is redundant —\n // undefined falls through to `typeof value` = \"undefined\", caught by the\n // `t !== \"string\" && t !== \"number\" && t !== \"boolean\"` check with the same code.\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value is ${value === null ? \"null\" : \"undefined\"} — terminal values must be string / number / boolean / nested object.`,\n );\n }\n const t = typeof value;\n if (t === \"object\") {\n // Equality clauses against nested objects survive only via callback\n // form (the normaliser flattens object-form sub-predicates to\n // dotted-path eq clauses). Keep the structural recursion light —\n // values are sealed from the typed seam.\n return;\n }\n if (t !== \"string\" && t !== \"number\" && t !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value has unsupported type ${JSON.stringify(t)} — must be string / number / boolean / nested object.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n\nconst validateRangeBound = (value: unknown, field: string, clauseIndex: number): void => {\n // Stryker disable next-line ConditionalExpression: `|| value === undefined` is redundant —\n // undefined falls through to `typeof value` = \"undefined\", caught by `t !== \"string\" && t !== \"number\"`\n // with the same InvalidConfig code.\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is ${value === null ? \"null\" : \"undefined\"} — range bounds must be string or finite number.`,\n );\n }\n const t = typeof value;\n if (t === \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is a boolean — range bounds must be string or finite number (booleans are not ordered).`,\n );\n }\n if (t === \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is a nested object — range bounds must be string or finite number.`,\n );\n }\n if (t !== \"string\" && t !== \"number\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) has unsupported type ${JSON.stringify(t)} — must be string or finite number.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n"],"mappings":";;;AAeA,MAAa,sBAAsB,GAAkB,MAClD,OAAO,MAAM,YAAY,OAAO,MAAM,YACtC,OAAO,MAAM,YAAY,OAAO,MAAM;;;;AAKzC,MAAa,iBAAiB,GAAkB,MAA6B;CAC3E,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UACxC,OAAO,IAAI;CAEb,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UAAU;EAClD,IAAI,IAAI,GACN,OAAO;EAET,IAAI,IAAI,GACN,OAAO;EAET,OAAO;CACT;CACA,OAAO;AACT;;AAGA,MAAa,cAAc,SACzB,KAAK,WAAW,IAAI,WAAW,KAAK,KAAK,MAAM,KAAK,UAAU,CAAC,CAAC,EAAE,KAAK,GAAG;;;;;;;;;;;;;;;;;;AAmB5E,MAAa,0BAA0B,GAAkB,MAA8B;CACrF,IAAI,MAAM,GACR,OAAO;CAET,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UACxC,OAAO;CAET,MAAM,QAAQ,OAAO,KAAK,CAAC;CAC3B,MAAM,QAAQ,OAAO,KAAK,CAAC;CAC3B,IAAI,MAAM,WAAW,MAAM,QACzB,OAAO;CAET,KAAK,MAAM,OAAO,OAAO;EAEvB,IAAI,EAAE,OAAO,IACX,OAAO;EAET,MAAM,OAAQ,EAAoC;EAClD,MAAM,OAAQ,EAAoC;EAElD,IAAI,SA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,YAAY,UAAU,KAAK,UAAU,KAAK,EAAE,qEACjF;CAEF,IAAI,MAAM,YAAY,MAAM,UAC1B,MAAM,IAAI,YACR,iBACA,mCAAmC,YAAY,UAAU,KAAK,UAAU,KAAK,EAAE,yBAAyB,KAAK,UAAU,CAAC,EAAE,oCAC5H;CAEF,IAAI,MAAM,YAAY,CAAC,OAAO,SAAS,KAAe,GACpD,MAAM,IAAI,YACR,iBACA,mCAAmC,YAAY,UAAU,KAAK,UAAU,KAAK,EAAE,OAAO,OAAO,KAAK,EAAE,wEACtG;AAEJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gusto/baerly-storage",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Vendorless document database that runs over any S3-compatible storage API.",
5
5
  "keywords": [
6
6
  "cloudflare-workers",
@@ -27,7 +27,7 @@
27
27
  "url": "git+https://github.com/Gusto/baerly-storage.git"
28
28
  },
29
29
  "bin": {
30
- "baerly": "./dist/baerly.js"
30
+ "baerly": "dist/baerly.js"
31
31
  },
32
32
  "files": [
33
33
  "dist"
@@ -95,6 +95,8 @@
95
95
  "@cloudflare/workers-types": "^4.20260527.1",
96
96
  "@fast-check/vitest": "^0.4.1",
97
97
  "@hono/node-server": "^2.0.4",
98
+ "@stryker-mutator/core": "9.6.1",
99
+ "@stryker-mutator/vitest-runner": "9.6.1",
98
100
  "@testing-library/react": "^16.3.2",
99
101
  "@types/node": "^25.9.1",
100
102
  "@types/pg": "^8.20.0",
@@ -103,6 +105,7 @@
103
105
  "@typescript/native-preview": "7.0.0-dev.20260526.1",
104
106
  "@vitest/coverage-v8": "^4.1.7",
105
107
  "aws4fetch": "1.0.20",
108
+ "esbuild": "^0.28.0",
106
109
  "execa": "^9.6.1",
107
110
  "fast-check": "^4.8.0",
108
111
  "happy-dom": "^20.9.0",
@@ -117,12 +120,12 @@
117
120
  "vite": "^8.0.14",
118
121
  "vitest": "^4.1.7",
119
122
  "yaml": "2.9.0",
120
- "@baerly/protocol": "0.1.0",
121
- "@baerly/client": "0.1.0",
122
123
  "@baerly/adapter-cloudflare": "0.1.0",
123
- "@baerly/server": "0.1.0",
124
+ "@baerly/adapter-node": "0.1.0",
124
125
  "@baerly/dev": "0.1.0",
125
- "@baerly/adapter-node": "0.1.0"
126
+ "@baerly/client": "0.1.0",
127
+ "@baerly/protocol": "0.1.0",
128
+ "@baerly/server": "0.1.0"
126
129
  },
127
130
  "peerDependencies": {
128
131
  "@cloudflare/workers-types": "^4",
@@ -156,6 +159,7 @@
156
159
  "test:export-round-trip": "vitest run --project=default tests/integration/export-round-trip.test.ts",
157
160
  "build": "rolldown -c && pnpm -r --filter \"./packages/*\" build",
158
161
  "baerly": "node dist/baerly.js",
162
+ "release": "node scripts/publish.mjs",
159
163
  "format": "oxfmt tests packages",
160
164
  "format:check": "oxfmt --check tests packages",
161
165
  "lint": "oxlint tests packages",
@@ -166,6 +170,9 @@
166
170
  "test:adapter-node": "MINIO=1 vitest run --project=default packages/adapter-node",
167
171
  "test:adapters": "pnpm test:adapter-cloudflare && pnpm test:adapter-node",
168
172
  "test:manual-e2e": "vitest run --project=default manual-e2e/cloudflare/e2e.test.ts manual-e2e/node/e2e.test.ts",
173
+ "test:mutate": "stryker run",
174
+ "mutate:survivors": "node scripts/mutation-survivors.mjs",
175
+ "test:coverage:protocol": "vitest run --config stryker.vitest.config.ts --coverage --coverage.provider=v8 --coverage.include='packages/protocol/src/**/*.ts' --coverage.exclude='**/*.test.ts' --coverage.exclude='**/*.test-d.ts' --coverage.exclude='**/index.ts'",
169
176
  "gate:day-one": "vitest run --project=default tests/integration/day-one-handshake.test.ts",
170
177
  "bundle-sizes": "node scripts/bundle-sizes.mjs",
171
178
  "verify": "pnpm run typecheck && pnpm run verify:examples && pnpm run lint && node scripts/add-ts-extensions.mjs --check && node scripts/lint-use-query.mjs && node scripts/lint-package-layers.mjs && pnpm run verify:docs",