@gusto/baerly-storage 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.md +176 -70
- package/dist/API.md +213 -139
- package/dist/CHANGELOG.md +434 -0
- package/dist/RECIPES.md +125 -0
- package/dist/THIRD-PARTY-LICENSES.txt +238 -0
- package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-DyiFK3_k.d.ts} +55 -11
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +301 -301
- package/dist/auth.js.map +1 -1
- package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
- package/dist/baerly.js +35 -15
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +342 -0
- package/dist/bytes-BXdamO3L.js.map +1 -1
- package/dist/{client-DYZfoZb9.d.ts → client-Fe8CwB73.d.ts} +10 -10
- package/dist/client-react.d.ts +3 -3
- package/dist/client-react.js +4 -4
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +4 -4
- package/dist/client.js +3 -3
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-CINJPKCW.js → cloudflare-DzKBrUlg.js} +178 -2
- package/dist/cloudflare-DzKBrUlg.js.map +1 -0
- package/dist/cloudflare.d.ts +49 -6
- package/dist/cloudflare.js +59 -26
- package/dist/cloudflare.js.map +1 -1
- package/dist/config-1tv0-Yzm.js +2693 -0
- package/dist/config-1tv0-Yzm.js.map +1 -0
- package/dist/constants-CfeMWQWk.js +222 -0
- package/dist/constants-CfeMWQWk.js.map +1 -0
- package/dist/context-DRZ3tZ5l.js.map +1 -1
- package/dist/{cost-CQt1YRkA.js → cost-DSMIVqzL.js} +43 -42
- package/dist/cost-DSMIVqzL.js.map +1 -0
- package/dist/current-json-C6nhPOm1.js +190 -0
- package/dist/current-json-C6nhPOm1.js.map +1 -0
- package/dist/{db-BM3y2JQw.d.ts → db-DsPkOVEH.d.ts} +26 -108
- package/dist/{deploy-CrAbfgCq.js → deploy-DonTr-CV.js} +12 -5
- package/dist/deploy-DonTr-CV.js.map +1 -0
- package/dist/dev-vite.d.ts +11 -7
- package/dist/dev-vite.js +7 -6
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-Db-hzPmE.js → doctor-DSIyCDg_.js} +14 -136
- package/dist/doctor-DSIyCDg_.js.map +1 -0
- package/dist/{dump-BYA55NLP.js → dump-Bh5k26VQ.js} +10 -31
- package/dist/dump-Bh5k26VQ.js.map +1 -0
- package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
- package/dist/errors-Dfa3p78c.js.map +1 -0
- package/dist/{export-Bhbz90-z.js → export-DtF5tDIM.js} +11 -32
- package/dist/{export-Bhbz90-z.js.map → export-DtF5tDIM.js.map} +1 -1
- package/dist/{fsck-CPPZWt9p.js → fsck-D_djMO5D.js} +28 -39
- package/dist/fsck-D_djMO5D.js.map +1 -0
- package/dist/{http-Cw8p6y5b.js → http-DxM9MflO.js} +151 -79
- package/dist/http-DxM9MflO.js.map +1 -0
- package/dist/http.d.ts +42 -26
- package/dist/http.js +3 -2
- package/dist/{index-DwDTWPSU.d.ts → index-0rZcMBwy.d.ts} +10 -7
- package/dist/{index-C3JAH1Yo.d.ts → index-B6oexfOB.d.ts} +9 -9
- package/dist/{index-cUY-36AN.d.ts → index-BNRh23K9.d.ts} +21 -5
- package/dist/{index-DSvwEUeF.d.ts → index-BYk9oCNf.d.ts} +240 -202
- package/dist/index.d.ts +6 -6
- package/dist/index.js +5 -5
- package/dist/{indexes-DAu2AkTW.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
- package/dist/{inspect-Bdbzvi-_.js → inspect-6WZ-pC7-.js} +21 -36
- package/dist/inspect-6WZ-pC7-.js.map +1 -0
- package/dist/key-Di6yyxFu.js +35 -0
- package/dist/key-Di6yyxFu.js.map +1 -0
- package/dist/{snapshot-SS8USDUF.js → log-tail-D98U1JBo.js} +179 -84
- package/dist/log-tail-D98U1JBo.js.map +1 -0
- package/dist/{maintenance-ClzBC1Vv.js → maintenance-B4Dki6Ig.js} +438 -176
- package/dist/maintenance-B4Dki6Ig.js.map +1 -0
- package/dist/{maintenance-BRrThz8V.d.ts → maintenance-B_e0T99L.d.ts} +114 -26
- package/dist/{maintenance-BvOv6BMM.js → maintenance-C7coQp4c.js} +217 -94
- package/dist/maintenance-C7coQp4c.js.map +1 -0
- package/dist/maintenance.d.ts +3 -2
- package/dist/maintenance.js +3 -2
- package/dist/node.d.ts +176 -68
- package/dist/node.js +3 -2
- package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
- package/dist/normalize-rjnZLwS4.js.map +1 -0
- package/dist/{observability-CpOiEN0k.js → observability-wzs3-BL_.js} +279 -109
- package/dist/observability-wzs3-BL_.js.map +1 -0
- package/dist/observability.d.ts +3 -3
- package/dist/observability.js +1 -1
- package/dist/{plan-DOTl21vq.js → plan-a7PJHBCy.js} +7 -4
- package/dist/plan-a7PJHBCy.js.map +1 -0
- package/dist/{query-BmiQy328.js → query-rAtXNQQB.js} +1063 -1202
- package/dist/query-rAtXNQQB.js.map +1 -0
- package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-BVzQSZlm.js} +10 -32
- package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
- package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
- package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
- package/dist/restore-R-4rbciV.js +778 -0
- package/dist/restore-R-4rbciV.js.map +1 -0
- package/dist/runtime-spec-qL3_lTTU.js +391 -0
- package/dist/runtime-spec-qL3_lTTU.js.map +1 -0
- package/dist/s3-http-B-z8th6O.d.ts +60 -0
- package/dist/s3.d.ts +47 -0
- package/dist/s3.js +45 -0
- package/dist/s3.js.map +1 -0
- package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
- package/dist/shared-secret-DgEicd3x.js.map +1 -0
- package/dist/src-BG20LZs7.js +2271 -0
- package/dist/src-BG20LZs7.js.map +1 -0
- package/dist/{src-zhEAmmF7.js → src-CYHFDrKz.js} +82 -99
- package/dist/src-CYHFDrKz.js.map +1 -0
- package/dist/{src-QQ7jDeL2.js → src-DYZ4H1aF.js} +44 -23
- package/dist/src-DYZ4H1aF.js.map +1 -0
- package/dist/subcommand-DoDA-K7d.js +197 -0
- package/dist/subcommand-DoDA-K7d.js.map +1 -0
- package/dist/time-DUqvFMHq.js +119 -0
- package/dist/time-DUqvFMHq.js.map +1 -0
- package/dist/{usage-CLjirdD-.js → usage-DBV1eQHC.js} +7 -22
- package/dist/usage-DBV1eQHC.js.map +1 -0
- package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
- package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
- package/dist/wire-izfGZDvr.js.map +1 -1
- package/package.json +77 -42
- package/dist/cloudflare-CINJPKCW.js.map +0 -1
- package/dist/config-DVfDGyw1.js +0 -278
- package/dist/config-DVfDGyw1.js.map +0 -1
- package/dist/cost-CQt1YRkA.js.map +0 -1
- package/dist/current-json-C-EyJqs0.js +0 -354
- package/dist/current-json-C-EyJqs0.js.map +0 -1
- package/dist/deploy-CrAbfgCq.js.map +0 -1
- package/dist/doctor-Db-hzPmE.js.map +0 -1
- package/dist/dump-BYA55NLP.js.map +0 -1
- package/dist/errors-DOdL95kK.js.map +0 -1
- package/dist/fsck-CPPZWt9p.js.map +0 -1
- package/dist/http-Cw8p6y5b.js.map +0 -1
- package/dist/inspect-Bdbzvi-_.js.map +0 -1
- package/dist/maintenance-BvOv6BMM.js.map +0 -1
- package/dist/maintenance-ClzBC1Vv.js.map +0 -1
- package/dist/normalize-XWY25_sG.js.map +0 -1
- package/dist/observability-CpOiEN0k.js.map +0 -1
- package/dist/plan-DOTl21vq.js.map +0 -1
- package/dist/query-BmiQy328.js.map +0 -1
- package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
- package/dist/restore-C6IcmLeA.js +0 -771
- package/dist/restore-C6IcmLeA.js.map +0 -1
- package/dist/shared-secret-BJdSwpgw.js.map +0 -1
- package/dist/snapshot-SS8USDUF.js.map +0 -1
- package/dist/src-DU1sCMlr.js +0 -6236
- package/dist/src-DU1sCMlr.js.map +0 -1
- package/dist/src-QQ7jDeL2.js.map +0 -1
- package/dist/src-zhEAmmF7.js.map +0 -1
- package/dist/subcommand-DZcHcsYp.js +0 -5122
- package/dist/subcommand-DZcHcsYp.js.map +0 -1
- package/dist/usage-CLjirdD-.js.map +0 -1
- /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
package/dist/dev-vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev-vite.js","names":[],"sources":["../packages/dev/src/vite-plugin.ts"],"sourcesContent":["import type { AddressInfo } from \"node:net\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport type { Plugin } from \"vite\";\nimport { baerlyNode } from \"@baerly/adapter-node\";\nimport type { BaerlyAppConfig, Verifier } from \"@baerly/protocol\";\nimport { Db, resolveVerifier } from \"@baerly/server\";\nimport { type DevBannerHint, printDevBanner } from \"./dev-banner.ts\";\nimport { ensureTable } from \"./ensure-table.ts\";\nimport { LocalFsStorage } from \"./local-fs.ts\";\n\nexport interface BaerlyDevOptions {\n /**\n * The project's `baerly.config.ts`. `app`, `tenant`, `auth`, and the\n * table set (`Object.keys(config.collections)`) are derived from it.\n * Per-collection schemas/indexes flow through to the in-process\n * listener the same way `baerlyNode` / `baerlyWorker` pipe them.\n */\n readonly config: BaerlyAppConfig;\n /**\n * Shared-secret token. **Optional.** Required only when\n * `config.auth === \"shared-secret\"` and `verifier` is unset — in\n * that branch, clients must send `Authorization: Bearer <secret>`\n * AND the middleware injects the same bearer server-side before\n * forwarding to the in-process listener.\n *\n * Ignored when `config.auth === \"none\"` (no bearer to inject) or\n * when `verifier` is supplied (the operator owns the auth seam).\n *\n * Throwing the symmetric `InvalidConfig` on a misconfig matches\n * production behaviour: forgetting `SHARED_SECRET` in dev fails\n * fast at `vite dev` startup with the same locked wording the\n * adapter would emit.\n */\n readonly secret?: string;\n /**\n * Per-request `Verifier`. **Optional.** When set, overrides both\n * `config.auth` and `secret` (same precedence as the production\n * adapter factories). Use for dev-mode JWT validation against a\n * staging IdP, or any custom auth shape.\n */\n readonly verifier?: Verifier;\n /** Absolute path to the data directory for LocalFsStorage. */\n readonly dataDir: string;\n /** Optional async seed callback, invoked after ensureTable, before mount. */\n readonly seed?: (db: Db) => Promise<void>;\n /** Extra hints appended to the dev banner. */\n readonly hints?: readonly DevBannerHint[];\n /** Set to false to suppress the dev banner. Default: true. */\n readonly banner?: boolean;\n}\n\nconst isV1Path = (url: string): boolean =>\n url === \"/v1\" || url.startsWith(\"/v1/\") || url.startsWith(\"/v1?\");\n\n/**\n * Inject `Authorization: ${value}` into a Node `IncomingMessage` such\n * that BOTH the parsed (`req.headers`) and the wire-form (`req.rawHeaders`)\n * views agree.\n *\n * Why both: `req.headers` is the parsed-and-lowercased JS map most\n * connect-style middleware reads, but Node→Fetch bridges typically\n * rebuild the Fetch `Headers` from `req.rawHeaders` (the original\n * `[name, value, name, value, …]` wire array) to preserve case and\n * multi-value semantics. `@cloudflare/vite-plugin`'s `createHeaders()`\n * does exactly that — so mutating `req.headers` alone silently drops\n * the bearer token when the in-process Worker receives the request.\n * Treat any new injection in this file as obligated to touch both.\n */\nconst injectAuthorizationHeader = (\n req: {\n headers: Record<string, string | string[] | undefined>;\n rawHeaders?: string[];\n },\n value: string,\n): void => {\n req.headers[\"authorization\"] = value;\n const raw = req.rawHeaders;\n if (raw === undefined) {\n return;\n }\n for (let i = 0; i < raw.length; i += 2) {\n if (raw[i]!.toLowerCase() === \"authorization\") {\n raw[i + 1] = value;\n return;\n }\n }\n raw.push(\"Authorization\", value);\n};\n\nexport interface BaerlyDevAuthOptions {\n /** Bearer token to inject on matched paths. */\n readonly secret: string;\n /**\n * Pathname prefixes to match. Default `[\"/v1\", \"/api\"]` — the\n * baerly cascade lives at `/v1/*`, and `/api/*` is the canonical\n * namespace for custom Worker routes (the \"wrap `baerly.fetch!`\"\n * recipe in the scaffold's AGENTS.md). Covering both by default\n * closes a recurring \"added a custom route, browser silently 401s\"\n * trap: agents typically edit `src/server/index.ts` without touching\n * `vite.config.ts`, so a `\"/v1\"`-only default leaves their new route\n * unauthenticated in `vite dev` and `pnpm verify` is silent on it.\n *\n * Override when you mount under a different namespace, or pass\n * `prefix: \"/v1\"` to opt out of `/api/*` injection entirely (rare —\n * the bearer is a harmless extra header on unmatched routes).\n */\n readonly prefix?: string | readonly string[];\n}\n\nconst normalisePrefixes = (prefix: string | readonly string[] | undefined): readonly string[] => {\n if (prefix === undefined) {\n return [\"/v1\", \"/api\"];\n }\n if (typeof prefix === \"string\") {\n return [prefix];\n }\n return prefix;\n};\n\nconst matchesAnyPrefix = (url: string, prefixes: readonly string[]): boolean => {\n for (const prefix of prefixes) {\n if (url === prefix || url.startsWith(`${prefix}/`) || url.startsWith(`${prefix}?`)) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Vite dev plugin: inject `Authorization: Bearer ${secret}` on every\n * request whose URL starts with one of `prefix` (default\n * `[\"/v1\", \"/api\"]`). Use this to keep the bearer token out of the\n * SPA bundle — the browser sends the request, Vite's middleware adds\n * the header, and the upstream handler (in-process worker or proxied\n * Node server) sees an authenticated request.\n *\n * **Custom Worker routes.** `baerlyWorker` only sees `/v1/*`; the\n * default `prefix` also covers `/api/*` because that's the canonical\n * namespace for the \"wrap `baerly.fetch!`\" recipe (a server-side\n * endpoint the SPA client can't run on its own, e.g. an endpoint\n * that needs `db.transaction(...)`). If you mount under a different\n * namespace, override:\n *\n * ```ts\n * baerlyDevAuth({ secret, prefix: [\"/v1\", \"/internal\"] });\n * ```\n *\n * The bearer is dev-only convenience — production deploys put the\n * SPA, the baerly cascade, AND your custom routes behind the same\n * tenant boundary (CF Access, an upstream JWT, …), so this matters\n * exclusively while `vite dev` is the front door.\n *\n * @example\n * ```ts\n * import { baerlyDevAuth, loadDevVars } from \"@gusto/baerly-storage/dev/vite\";\n *\n * const { SHARED_SECRET } = loadDevVars(\".dev.vars\", \"SHARED_SECRET\");\n * export default defineConfig({\n * plugins: [\n * cloudflare(),\n * baerlyDevAuth({ secret: SHARED_SECRET ?? \"\" }),\n * ],\n * });\n * ```\n */\nexport function baerlyDevAuth(opts: BaerlyDevAuthOptions): Plugin {\n if (opts.secret === \"\") {\n throw new Error(\n \"baerlyDevAuth: secret must be non-empty. Set SHARED_SECRET in .dev.vars / .env.\",\n );\n }\n const prefixes: readonly string[] = normalisePrefixes(opts.prefix);\n return {\n name: \"baerly-dev-auth\",\n apply: \"serve\",\n configureServer(server) {\n server.middlewares.use((req, _res, next) => {\n const url = req.url ?? \"\";\n if (matchesAnyPrefix(url, prefixes)) {\n injectAuthorizationHeader(req, `Bearer ${opts.secret}`);\n }\n next();\n });\n },\n };\n}\n\n/**\n * Parse a `.dev.vars` / `.env` file and return the values for the\n * requested `keys`. Supports `KEY=value`, `# comments`, blank lines,\n * and single- or double-quoted values. Keys missing from the file\n * (or the whole file when it does not exist) come back as\n * `undefined` — fall back with `??` at the call site.\n *\n * The return type is `Record<K, string | undefined>` where `K` is\n * the union of literal key names you pass in, so property access\n * works under strict `noPropertyAccessFromIndexSignature`:\n *\n * ```ts\n * const { SHARED_SECRET } = loadDevVars(\".dev.vars\", \"SHARED_SECRET\");\n * // ^? string | undefined\n * ```\n */\nexport function loadDevVars<K extends string>(\n path: string,\n ...keys: readonly K[]\n): Record<K, string | undefined> {\n const out = {} as Record<K, string | undefined>;\n for (const key of keys) {\n out[key] = undefined;\n }\n if (!existsSync(path)) {\n return out;\n }\n const wanted = new Set<string>(keys);\n for (const rawLine of readFileSync(path, \"utf8\").split(\"\\n\")) {\n const line = rawLine.trim();\n if (line === \"\" || line.startsWith(\"#\")) {\n continue;\n }\n const eq = line.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n const key = line.slice(0, eq).trim();\n if (!wanted.has(key)) {\n continue;\n }\n let value = line.slice(eq + 1).trim();\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n out[key as K] = value;\n }\n return out;\n}\n\n/**\n * Resolution order for the in-process verifier (mirrors\n * `baerlyNode` / `baerlyWorker`):\n *\n * 1. `opts.verifier` set → use as-is.\n * 2. else `opts.config.auth === \"shared-secret\"` → require\n * `opts.secret`; build `sharedSecret({ secret, tenantPrefix:\n * config.tenant })`. Throws `BaerlyError(\"InvalidConfig\", ...)`\n * at Vite startup when `opts.secret` is empty/unset — same\n * locked wording the production adapter would emit.\n * 3. else `opts.config.auth === \"none\"` → pin every request to\n * `config.tenant`; no header check.\n *\n * Bearer injection on `/v1/*` only fires in branch 2 (and only when\n * branch 1 didn't win) — the dev convenience that lets the SPA call\n * the listener without putting the secret in the browser bundle.\n * Branch 3 leaves the `Authorization` header alone.\n *\n * Verifier resolution happens eagerly at factory time so a misconfig\n * fails Vite startup, not the first `/v1/*` round-trip.\n */\nexport function baerlyDev(opts: BaerlyDevOptions): Plugin {\n // Resolution order: opts.verifier → config.auth.shared-secret →\n // config.auth.none → throw. Mirrors `baerlyWorker` / `baerlyNode`.\n // The synthetic `readEnv` hoists `opts.secret` to `SHARED_SECRET`\n // so the same resolver works — `baerlyDev` takes the secret as a\n // typed option rather than reading `process.env` directly.\n const verifier = resolveVerifier({\n factoryVerifier: opts.verifier,\n config: opts.config,\n readEnv: (k) => (k === \"SHARED_SECRET\" ? opts.secret : process.env[k]),\n });\n\n // Bearer injection only matters in the shared-secret branch (and\n // only when no override owns auth). For \"none\" or any custom\n // verifier, the `Authorization` header reaches the listener\n // unchanged.\n const bearerForInjection: string | undefined =\n opts.verifier === undefined && opts.config.auth === \"shared-secret\" ? opts.secret : undefined;\n\n return {\n name: \"baerly-dev\",\n apply: \"serve\",\n configureServer(server) {\n // Mount in the configureServer body (not a post-hook) so the\n // middleware runs BEFORE Vite's internal SPA history fallback.\n // Otherwise /v1/* requests get caught by the SPA fallback and\n // served the index.html shell.\n const app = opts.config.app;\n const tenant = opts.config.tenant;\n const tables = Object.keys(opts.config.collections);\n const ready = (async () => {\n const storage = new LocalFsStorage({ root: opts.dataDir });\n for (const table of tables) {\n await ensureTable(storage, { app, tenant, table });\n }\n if (opts.seed !== undefined) {\n const db = Db.create({ storage, app, tenant, config: opts.config });\n await opts.seed(db);\n }\n const requestHandler = baerlyNode({\n config: opts.config,\n storage,\n verifier,\n }).fetch;\n return getRequestListener(requestHandler);\n })();\n\n // Surface setup failures eagerly; without this an unhandled\n // rejection would silently kill the dev server.\n ready.catch((error: unknown) => {\n console.error(\"[baerly-dev] setup failed:\", error);\n });\n\n server.middlewares.use((req, res, next) => {\n const url = req.url;\n if (url === undefined || !isV1Path(url)) {\n next();\n return;\n }\n // Inject the bearer token server-side so the SPA never sees\n // the secret. Only runs for `config.auth === \"shared-secret\"`\n // without a `verifier:` override — otherwise the header\n // reaches the listener unchanged. Mutates both `req.headers`\n // and `req.rawHeaders` — see `injectAuthorizationHeader`'s\n // JSDoc.\n if (bearerForInjection !== undefined) {\n injectAuthorizationHeader(req, `Bearer ${bearerForInjection}`);\n }\n ready.then(\n (listener) => {\n listener(req as never, res as never);\n },\n (error: unknown) => {\n res.statusCode = 503;\n res.setHeader(\"content-type\", \"application/json\");\n res.end(JSON.stringify({ error: \"baerly-dev setup failed\", message: String(error) }));\n },\n );\n });\n\n if (opts.banner !== false) {\n server.httpServer?.once(\"listening\", () => {\n const address = server.httpServer?.address();\n const port =\n typeof address === \"object\" && address !== null\n ? (address as AddressInfo).port\n : undefined;\n const url = port !== undefined ? `http://localhost:${port}/` : \"http://localhost/\";\n printDevBanner({\n name: opts.config.app,\n primaryUrl: { label: \"App\", url },\n ...(opts.hints !== undefined && { hints: opts.hints }),\n });\n });\n }\n },\n };\n}\n"],"mappings":";;;;;AAoDA,MAAM,YAAY,QAChB,QAAQ,SAAS,IAAI,WAAW,MAAM,KAAK,IAAI,WAAW,MAAM;;;;;;;;;;;;;;;AAgBlE,MAAM,6BACJ,KAIA,UACS;CACT,IAAI,QAAQ,mBAAmB;CAC/B,MAAM,MAAM,IAAI;CAChB,IAAI,QAAQ,KAAA,GACV;CAEF,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,GACnC,IAAI,IAAI,GAAI,YAAY,MAAM,iBAAiB;EAC7C,IAAI,IAAI,KAAK;EACb;CACF;CAEF,IAAI,KAAK,iBAAiB,KAAK;AACjC;AAsBA,MAAM,qBAAqB,WAAsE;CAC/F,IAAI,WAAW,KAAA,GACb,OAAO,CAAC,OAAO,MAAM;CAEvB,IAAI,OAAO,WAAW,UACpB,OAAO,CAAC,MAAM;CAEhB,OAAO;AACT;AAEA,MAAM,oBAAoB,KAAa,aAAyC;CAC9E,KAAK,MAAM,UAAU,UACnB,IAAI,QAAQ,UAAU,IAAI,WAAW,GAAG,OAAO,EAAE,KAAK,IAAI,WAAW,GAAG,OAAO,EAAE,GAC/E,OAAO;CAGX,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,cAAc,MAAoC;CAChE,IAAI,KAAK,WAAW,IAClB,MAAM,IAAI,MACR,iFACF;CAEF,MAAM,WAA8B,kBAAkB,KAAK,MAAM;CACjE,OAAO;EACL,MAAM;EACN,OAAO;EACP,gBAAgB,QAAQ;GACtB,OAAO,YAAY,KAAK,KAAK,MAAM,SAAS;IAE1C,IAAI,iBADQ,IAAI,OAAO,IACG,QAAQ,GAChC,0BAA0B,KAAK,UAAU,KAAK,QAAQ;IAExD,KAAK;GACP,CAAC;EACH;CACF;AACF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AK,MAAM;IACtD,CAAC;GACH,CAAC;EAEL;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"dev-vite.js","names":[],"sources":["../packages/dev/src/vite-plugin.ts"],"sourcesContent":["import type { AddressInfo } from \"node:net\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport type { Plugin } from \"vite\";\nimport { baerlyNode } from \"@baerly/adapter-node\";\nimport type { BaerlyAppConfig, Verifier } from \"@baerly/protocol\";\nimport { Db, resolveVerifier } from \"@baerly/server\";\nimport { type DevBannerHint, printDevBanner } from \"./dev-banner.ts\";\nimport { ensureTable } from \"./ensure-table.ts\";\nimport { LocalFsStorage } from \"./local-fs.ts\";\n\nexport interface BaerlyDevOptions {\n /**\n * The project's `baerly.config.ts`. `app`, `tenant`, `auth`, and the\n * table set (`Object.keys(config.collections)`) are derived from it.\n * Per-collection schemas/indexes flow through to the in-process\n * listener the same way `baerlyNode` / `baerlyWorker` pipe them.\n */\n readonly config: BaerlyAppConfig;\n /**\n * Shared-secret token. **Optional.** Required only when\n * `config.auth === \"shared-secret\"` and `verifier` is unset — in\n * that branch, clients must send `Authorization: Bearer <secret>`\n * AND the middleware injects the same bearer server-side before\n * forwarding to the in-process listener.\n *\n * Ignored when `config.auth === \"none\"` (no bearer to inject) or\n * when `verifier` is supplied (the operator owns the auth seam).\n *\n * Throwing the symmetric `InvalidConfig` on a misconfig matches\n * production behaviour: forgetting `SHARED_SECRET` in dev fails\n * fast at `vite dev` startup with the same locked wording the\n * adapter would emit.\n */\n readonly secret?: string;\n /**\n * Per-request `Verifier`. **Optional.** When set, overrides both\n * `config.auth` and `secret` (same precedence as the production\n * adapter factories). Use for dev-mode JWT validation against a\n * staging IdP, or any custom auth shape.\n */\n readonly verifier?: Verifier;\n /**\n * Absolute path to the data directory for LocalFsStorage.\n * **Optional** — defaults to `<vite root>/.baerly-data`, so the dev\n * server runs zero-config.\n */\n readonly dataDir?: string;\n /** Optional async seed callback, invoked after ensureTable, before mount. */\n readonly seed?: (db: Db) => Promise<void>;\n /** Extra hints appended to the dev banner. */\n readonly hints?: readonly DevBannerHint[];\n /** Set to false to suppress the dev banner. Default: true. */\n readonly banner?: boolean;\n}\n\nconst isV1Path = (url: string): boolean =>\n url === \"/v1\" || url.startsWith(\"/v1/\") || url.startsWith(\"/v1?\");\n\n/**\n * Inject `Authorization: ${value}` into a Node `IncomingMessage` such\n * that BOTH the parsed (`req.headers`) and the wire-form (`req.rawHeaders`)\n * views agree.\n *\n * Why both: `req.headers` is the parsed-and-lowercased JS map most\n * connect-style middleware reads, but Node→Fetch bridges typically\n * rebuild the Fetch `Headers` from `req.rawHeaders` (the original\n * `[name, value, name, value, …]` wire array) to preserve case and\n * multi-value semantics. `@cloudflare/vite-plugin`'s `createHeaders()`\n * does exactly that — so mutating `req.headers` alone silently drops\n * the bearer token when the in-process Worker receives the request.\n * Treat any new injection in this file as obligated to touch both.\n */\nconst injectAuthorizationHeader = (\n req: {\n headers: Record<string, string | string[] | undefined>;\n rawHeaders?: string[];\n },\n value: string,\n): void => {\n req.headers[\"authorization\"] = value;\n const raw = req.rawHeaders;\n if (raw === undefined) {\n return;\n }\n for (let i = 0; i < raw.length; i += 2) {\n if (raw[i]!.toLowerCase() === \"authorization\") {\n raw[i + 1] = value;\n return;\n }\n }\n raw.push(\"Authorization\", value);\n};\n\nexport interface BaerlyDevAuthOptions {\n /** Bearer token to inject on matched paths. */\n readonly secret: string;\n /**\n * Pathname prefixes to match. Default `[\"/v1\", \"/api\"]` — the\n * baerly cascade lives at `/v1/*`, and `/api/*` is the canonical\n * namespace for custom Worker routes (the \"wrap `baerly.fetch!`\"\n * recipe in the scaffold's AGENTS.md). Covering both by default\n * closes a recurring \"added a custom route, browser silently 401s\"\n * trap: agents typically edit `src/server/index.ts` without touching\n * `vite.config.ts`, so a `\"/v1\"`-only default leaves their new route\n * unauthenticated in `vite dev` and `pnpm verify` is silent on it.\n *\n * Override when you mount under a different namespace, or pass\n * `prefix: \"/v1\"` to opt out of `/api/*` injection entirely (rare —\n * the bearer is a harmless extra header on unmatched routes).\n */\n readonly prefix?: string | readonly string[];\n}\n\nconst normalisePrefixes = (prefix: string | readonly string[] | undefined): readonly string[] => {\n if (prefix === undefined) {\n return [\"/v1\", \"/api\"];\n }\n if (typeof prefix === \"string\") {\n return [prefix];\n }\n return prefix;\n};\n\nconst matchesAnyPrefix = (url: string, prefixes: readonly string[]): boolean => {\n for (const prefix of prefixes) {\n if (url === prefix || url.startsWith(`${prefix}/`) || url.startsWith(`${prefix}?`)) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Vite dev plugin: inject `Authorization: Bearer ${secret}` on every\n * request whose URL starts with one of `prefix` (default\n * `[\"/v1\", \"/api\"]`). Use this to keep the bearer token out of the\n * SPA bundle — the browser sends the request, Vite's middleware adds\n * the header, and the upstream handler (in-process worker or proxied\n * Node server) sees an authenticated request.\n *\n * **Custom Worker routes.** `baerlyWorker` only sees `/v1/*`; the\n * default `prefix` also covers `/api/*` because that's the canonical\n * namespace for the \"wrap `baerly.fetch!`\" recipe (a server-side\n * endpoint the SPA client can't run on its own, e.g. an endpoint\n * that fans a write across several documents server-side). If you\n * mount under a different namespace, override:\n *\n * ```ts\n * baerlyDevAuth({ secret, prefix: [\"/v1\", \"/internal\"] });\n * ```\n *\n * The bearer is dev-only convenience — production deploys put the\n * SPA, the baerly cascade, AND your custom routes behind the same\n * tenant boundary (CF Access, an upstream JWT, …), so this matters\n * exclusively while `vite dev` is the front door.\n *\n * @example\n * ```ts\n * import { baerlyDevAuth, loadDevVars } from \"@gusto/baerly-storage/dev/vite\";\n *\n * const { SHARED_SECRET } = loadDevVars(\".dev.vars\", \"SHARED_SECRET\");\n * export default defineConfig({\n * plugins: [\n * cloudflare(),\n * baerlyDevAuth({ secret: SHARED_SECRET ?? \"\" }),\n * ],\n * });\n * ```\n */\nexport function baerlyDevAuth(opts: BaerlyDevAuthOptions): Plugin {\n if (opts.secret === \"\") {\n throw new Error(\n \"baerlyDevAuth: secret must be non-empty. Set SHARED_SECRET in .dev.vars / .env.\",\n );\n }\n const prefixes: readonly string[] = normalisePrefixes(opts.prefix);\n return {\n name: \"baerly-dev-auth\",\n apply: \"serve\",\n configureServer(server) {\n server.middlewares.use((req, _res, next) => {\n const url = req.url ?? \"\";\n if (matchesAnyPrefix(url, prefixes)) {\n injectAuthorizationHeader(req, `Bearer ${opts.secret}`);\n }\n next();\n });\n },\n };\n}\n\n/**\n * Parse a `.dev.vars` / `.env` file and return the values for the\n * requested `keys`. Supports `KEY=value`, `# comments`, blank lines,\n * and single- or double-quoted values. Keys missing from the file\n * (or the whole file when it does not exist) come back as\n * `undefined` — fall back with `??` at the call site.\n *\n * The return type is `Record<K, string | undefined>` where `K` is\n * the union of literal key names you pass in, so property access\n * works under strict `noPropertyAccessFromIndexSignature`:\n *\n * ```ts\n * const { SHARED_SECRET } = loadDevVars(\".dev.vars\", \"SHARED_SECRET\");\n * // ^? string | undefined\n * ```\n */\nexport function loadDevVars<K extends string>(\n path: string,\n ...keys: readonly K[]\n): Record<K, string | undefined> {\n const out = {} as Record<K, string | undefined>;\n for (const key of keys) {\n out[key] = undefined;\n }\n if (!existsSync(path)) {\n return out;\n }\n const wanted = new Set<string>(keys);\n for (const rawLine of readFileSync(path, \"utf8\").split(\"\\n\")) {\n const line = rawLine.trim();\n if (line === \"\" || line.startsWith(\"#\")) {\n continue;\n }\n const eq = line.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n const key = line.slice(0, eq).trim();\n if (!wanted.has(key)) {\n continue;\n }\n let value = line.slice(eq + 1).trim();\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n out[key as K] = value;\n }\n return out;\n}\n\n/**\n * Resolution order for the in-process verifier (mirrors\n * `baerlyNode` / `baerlyWorker`):\n *\n * 1. `opts.verifier` set → use as-is.\n * 2. else `opts.config.auth === \"shared-secret\"` → require\n * `opts.secret`; build `sharedSecret({ secret, tenantPrefix:\n * config.tenant })`. Throws `BaerlyError(\"InvalidConfig\", ...)`\n * at Vite startup when `opts.secret` is empty/unset — same\n * locked wording the production adapter would emit.\n * 3. else `opts.config.auth === \"none\"` → pin every request to\n * `config.tenant`; no header check.\n *\n * Bearer injection on `/v1/*` only fires in branch 2 (and only when\n * branch 1 didn't win) — the dev convenience that lets the SPA call\n * the listener without putting the secret in the browser bundle.\n * Branch 3 leaves the `Authorization` header alone.\n *\n * Verifier resolution happens eagerly at factory time so a misconfig\n * fails Vite startup, not the first `/v1/*` round-trip.\n */\nexport function baerlyDev(opts: BaerlyDevOptions): Plugin {\n // Resolution order: opts.verifier → config.auth.shared-secret →\n // config.auth.none → throw. Mirrors `baerlyWorker` / `baerlyNode`.\n // The synthetic `readEnv` hoists `opts.secret` to `SHARED_SECRET`\n // so the same resolver works — `baerlyDev` takes the secret as a\n // typed option rather than reading `process.env` directly.\n const verifier = resolveVerifier({\n factoryVerifier: opts.verifier,\n config: opts.config,\n readEnv: (k) => (k === \"SHARED_SECRET\" ? opts.secret : process.env[k]),\n });\n\n // Bearer injection only matters in the shared-secret branch (and\n // only when no override owns auth). For \"none\" or any custom\n // verifier, the `Authorization` header reaches the listener\n // unchanged.\n const bearerForInjection: string | undefined =\n opts.verifier === undefined && opts.config.auth === \"shared-secret\" ? opts.secret : undefined;\n\n return {\n name: \"baerly-dev\",\n apply: \"serve\",\n configureServer(server) {\n // Mount in the configureServer body (not a post-hook) so the\n // middleware runs BEFORE Vite's internal SPA history fallback.\n // Otherwise /v1/* requests get caught by the SPA fallback and\n // served the index.html shell.\n const app = opts.config.app;\n const tenant = opts.config.tenant;\n const tables = Object.keys(opts.config.collections);\n const ready = (async () => {\n const storage = new LocalFsStorage({\n root: opts.dataDir ?? resolve(server.config.root, \".baerly-data\"),\n });\n for (const table of tables) {\n await ensureTable(storage, { app, tenant, table });\n }\n if (opts.seed !== undefined) {\n const db = Db.create({ storage, app, tenant, config: opts.config });\n await opts.seed(db);\n }\n const requestHandler = baerlyNode({\n config: opts.config,\n storage,\n verifier,\n }).fetch;\n return getRequestListener(requestHandler);\n })();\n\n // Surface setup failures eagerly; without this an unhandled\n // rejection would silently kill the dev server.\n ready.catch((error: unknown) => {\n console.error(\"[baerly-dev] setup failed:\", error);\n });\n\n server.middlewares.use((req, res, next) => {\n const url = req.url;\n if (url === undefined || !isV1Path(url)) {\n next();\n return;\n }\n // Inject the bearer token server-side so the SPA never sees\n // the secret. Only runs for `config.auth === \"shared-secret\"`\n // without a `verifier:` override — otherwise the header\n // reaches the listener unchanged. Mutates both `req.headers`\n // and `req.rawHeaders` — see `injectAuthorizationHeader`'s\n // JSDoc.\n if (bearerForInjection !== undefined) {\n injectAuthorizationHeader(req, `Bearer ${bearerForInjection}`);\n }\n ready.then(\n (listener) => {\n listener(req as never, res as never);\n },\n (error: unknown) => {\n res.statusCode = 503;\n res.setHeader(\"content-type\", \"application/json\");\n res.end(JSON.stringify({ error: \"baerly-dev setup failed\", message: String(error) }));\n },\n );\n });\n\n if (opts.banner !== false) {\n server.httpServer?.once(\"listening\", () => {\n const address = server.httpServer?.address();\n const port =\n typeof address === \"object\" && address !== null\n ? (address as AddressInfo).port\n : undefined;\n const url = port !== undefined ? `http://localhost:${port}/` : \"http://localhost/\";\n printDevBanner({\n name: opts.config.app,\n primaryUrl: { label: \"App\", url },\n ...(opts.hints !== undefined && { hints: opts.hints }),\n });\n });\n }\n },\n };\n}\n"],"mappings":";;;;;;AAyDA,MAAM,YAAY,QAChB,QAAQ,SAAS,IAAI,WAAW,MAAM,KAAK,IAAI,WAAW,MAAM;;;;;;;;;;;;;;;AAgBlE,MAAM,6BACJ,KAIA,UACS;CACT,IAAI,QAAQ,mBAAmB;CAC/B,MAAM,MAAM,IAAI;CAChB,IAAI,QAAQ,KAAA,GACV;CAEF,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,GACnC,I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C,CAAC;IACH,OAAO,mBAAmB,cAAc;GAC1C,EAAA,CAAG;GAIH,MAAM,OAAO,UAAmB;IAC9B,QAAQ,MAAM,8BAA8B,KAAK;GACnD,CAAC;GAED,OAAO,YAAY,KAAK,KAAK,KAAK,SAAS;IACzC,MAAM,MAAM,IAAI;IAChB,IAAI,QAAQ,KAAA,KAAa,CAAC,SAAS,GAAG,GAAG;KACvC,KAAK;KACL;IACF;IAOA,IAAI,uBAAuB,KAAA,GACzB,0BAA0B,KAAK,UAAU,oBAAoB;IAE/D,MAAM,MACH,aAAa;KACZ,SAAS,KAAc,GAAY;IACrC,IACC,UAAmB;KAClB,IAAI,aAAa;KACjB,IAAI,UAAU,gBAAgB,kBAAkB;KAChD,IAAI,IAAI,KAAK,UAAU;MAAE,OAAO;MAA2B,SAAS,OAAO,KAAK;KAAE,CAAC,CAAC;IACtF,CACF;GACF,CAAC;GAED,IAAI,KAAK,WAAW,OAClB,OAAO,YAAY,KAAK,mBAAmB;IACzC,MAAM,UAAU,OAAO,YAAY,QAAQ;IAC3C,MAAM,OACJ,OAAO,YAAY,YAAY,YAAY,OACtC,QAAwB,OACzB,KAAA;IACN,MAAM,MAAM,SAAS,KAAA,IAAY,oBAAoB,KAAK,KAAK;IAC/D,eAAe;KACb,MAAM,KAAK,OAAO;KAClB,YAAY;MAAE,OAAO;MAAO;KAAI;KAChC,GAAI,KAAK,UAAU,KAAA,KAAa,EAAE,OAAO,KAAK,MAAM;IACtD,CAAC;GACH,CAAC;EAEL;CACF;AACF"}
|
package/dist/dev.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { n as DevBannerOpts, r as printDevBanner, t as DevBannerHint } from "./dev-banner-CWHIk8tH.js";
|
|
2
|
-
import { a as renderDevLanding, i as DevLandingOptions, n as LocalFsStorageOptions, r as ensureTable, t as LocalFsStorage } from "./index-
|
|
2
|
+
import { a as renderDevLanding, i as DevLandingOptions, n as LocalFsStorageOptions, r as ensureTable, t as LocalFsStorage } from "./index-0rZcMBwy.js";
|
|
3
3
|
export { type DevBannerHint, type DevBannerOpts, type DevLandingOptions, LocalFsStorage, LocalFsStorageOptions, ensureTable, printDevBanner, renderDevLanding };
|
package/dist/dev.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as printDevBanner, n as ensureTable, r as renderDevLanding, t as LocalFsStorage } from "./src-
|
|
1
|
+
import { i as printDevBanner, n as ensureTable, r as renderDevLanding, t as LocalFsStorage } from "./src-DYZ4H1aF.js";
|
|
2
2
|
export { LocalFsStorage, ensureTable, printDevBanner, renderDevLanding };
|
|
@@ -1,129 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as
|
|
1
|
+
import { _ as SHARED_SECRET_MISSING_MESSAGE, r as parseBucketUri, t as loadAppConfig } from "./config-1tv0-Yzm.js";
|
|
2
|
+
import { a as defaultRunner, i as parse, n as ensureBindings, o as doctorCas, r as parseR2Bindings } from "./cloudflare-DzKBrUlg.js";
|
|
3
3
|
import { i as isJsonMode, o as BaerlyError, t as color } from "./baerly.js";
|
|
4
|
-
import {
|
|
4
|
+
import { i as JSON_ARG, s as defineBaerlySubcommand } from "./subcommand-DoDA-K7d.js";
|
|
5
5
|
import { resolve } from "node:path";
|
|
6
6
|
import { existsSync, readFileSync } from "node:fs";
|
|
7
|
-
//#region ../protocol/src/storage/probe-cas.ts
|
|
8
|
-
const isConflict = (error) => error instanceof BaerlyError && error.code === "Conflict";
|
|
9
|
-
/**
|
|
10
|
-
* Runtime probe that a live `Storage` backend honours the conditional
|
|
11
|
-
* writes the protocol depends on. The storage conformance suite asserts
|
|
12
|
-
* the same semantics in CI for every shipped adapter, but a deployment
|
|
13
|
-
* may point baerly at an arbitrary S3-compatible store; a backend that
|
|
14
|
-
* silently *ignores* `If-Match` (returns 200 instead of rejecting a
|
|
15
|
-
* stale write) causes silent lost-update corruption — every commit
|
|
16
|
-
* CAS-advances `current.json`, and the no-lease maintenance fold relies
|
|
17
|
-
* on the same fence. This is the fail-loud, deploy-time analogue of the
|
|
18
|
-
* conformance CAS block.
|
|
19
|
-
*
|
|
20
|
-
* Writes a single throwaway sentinel under `keyPrefix` and deletes it on
|
|
21
|
-
* the way out (even on failure). Two checks, mirroring the conformance
|
|
22
|
-
* suite:
|
|
23
|
-
* - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (Conflict).
|
|
24
|
-
* - `ifNoneMatch-exists`: a PUT with `ifNoneMatch:"*"` over an existing
|
|
25
|
-
* key must reject (Conflict).
|
|
26
|
-
*
|
|
27
|
-
* A rejected write surfaces as a `BaerlyError` with `code === "Conflict"`
|
|
28
|
-
* (the contract `Storage.put` documents); anything else — a resolved
|
|
29
|
-
* promise, or a non-Conflict error — means the backend does not honour
|
|
30
|
-
* the condition and is reported as a failed check rather than thrown.
|
|
31
|
-
*/
|
|
32
|
-
const probeCas = async (storage, opts) => {
|
|
33
|
-
const key = `${opts?.keyPrefix ?? ""}__baerly_cas_probe__/${uuid()}`;
|
|
34
|
-
const enc = new TextEncoder();
|
|
35
|
-
const signal = opts?.signal;
|
|
36
|
-
const checks = [];
|
|
37
|
-
try {
|
|
38
|
-
await storage.put(key, enc.encode("v1"), { signal });
|
|
39
|
-
try {
|
|
40
|
-
await storage.put(key, enc.encode("v2"), {
|
|
41
|
-
ifMatch: "\"baerly-cas-probe-stale\"",
|
|
42
|
-
signal
|
|
43
|
-
});
|
|
44
|
-
checks.push({
|
|
45
|
-
name: "ifMatch-stale",
|
|
46
|
-
ok: false,
|
|
47
|
-
detail: "PUT with a stale If-Match was ACCEPTED — backend ignores If-Match (silent lost-update risk)."
|
|
48
|
-
});
|
|
49
|
-
} catch (error) {
|
|
50
|
-
checks.push(isConflict(error) ? {
|
|
51
|
-
name: "ifMatch-stale",
|
|
52
|
-
ok: true,
|
|
53
|
-
detail: "stale If-Match rejected (Conflict), as required."
|
|
54
|
-
} : {
|
|
55
|
-
name: "ifMatch-stale",
|
|
56
|
-
ok: false,
|
|
57
|
-
detail: `stale If-Match raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
try {
|
|
61
|
-
await storage.put(key, enc.encode("v3"), {
|
|
62
|
-
ifNoneMatch: "*",
|
|
63
|
-
signal
|
|
64
|
-
});
|
|
65
|
-
checks.push({
|
|
66
|
-
name: "ifNoneMatch-exists",
|
|
67
|
-
ok: false,
|
|
68
|
-
detail: "PUT with If-None-Match:\"*\" over an existing key was ACCEPTED — backend ignores If-None-Match (create-only writes unsafe)."
|
|
69
|
-
});
|
|
70
|
-
} catch (error) {
|
|
71
|
-
checks.push(isConflict(error) ? {
|
|
72
|
-
name: "ifNoneMatch-exists",
|
|
73
|
-
ok: true,
|
|
74
|
-
detail: "If-None-Match:\"*\" over an existing key rejected (Conflict), as required."
|
|
75
|
-
} : {
|
|
76
|
-
name: "ifNoneMatch-exists",
|
|
77
|
-
ok: false,
|
|
78
|
-
detail: `If-None-Match:"*" raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
} finally {
|
|
82
|
-
try {
|
|
83
|
-
await storage.delete(key, signal === void 0 ? void 0 : { signal });
|
|
84
|
-
} catch {}
|
|
85
|
-
}
|
|
86
|
-
return {
|
|
87
|
-
ok: checks.every((c) => c.ok),
|
|
88
|
-
checks
|
|
89
|
-
};
|
|
90
|
-
};
|
|
91
|
-
//#endregion
|
|
92
|
-
//#region src/doctor/cas.ts
|
|
93
|
-
/**
|
|
94
|
-
* `baerly doctor --bucket <uri>` — live backend CAS probe.
|
|
95
|
-
*
|
|
96
|
-
* Unlike the cloudflare deploy-invariant walk (which only inspects
|
|
97
|
-
* config files), this mode connects to a real bucket and verifies it
|
|
98
|
-
* honours the conditional writes the protocol depends on: every commit
|
|
99
|
-
* CAS-advances `current.json` with `If-Match`, and the no-lease
|
|
100
|
-
* maintenance fold relies on the same fence. A store that silently
|
|
101
|
-
* ignores `If-Match` (returns 200 instead of rejecting a stale write)
|
|
102
|
-
* causes silent lost-update corruption — this is the fail-loud,
|
|
103
|
-
* deploy-time analogue of the conformance CAS block.
|
|
104
|
-
*
|
|
105
|
-
* Writes a single throwaway sentinel and deletes it; see
|
|
106
|
-
* {@link probeCas}.
|
|
107
|
-
*/
|
|
108
|
-
const CAS_FIX = "Point baerly at an S3-compatible store that honours conditional writes (If-Match + If-None-Match). Real AWS S3, Cloudflare R2, and GCS do; a custom gateway / proxy may be stripping conditional headers — check it returns 412 on a stale If-Match.";
|
|
109
|
-
/**
|
|
110
|
-
* Run the live CAS round-trip against `storage` and shape the result
|
|
111
|
-
* as a {@link DoctorReport}. Status is `error` iff any sub-check failed
|
|
112
|
-
* (a non-conformant backend is a hard blocker, not a warning).
|
|
113
|
-
*/
|
|
114
|
-
const doctorCas = async (storage, keyPrefix) => {
|
|
115
|
-
const result = await probeCas(storage, { keyPrefix });
|
|
116
|
-
return {
|
|
117
|
-
findings: result.checks.map((c) => ({
|
|
118
|
-
severity: c.ok ? "ok" : "error",
|
|
119
|
-
check: `cas-${c.name}`,
|
|
120
|
-
message: c.detail,
|
|
121
|
-
...c.ok ? {} : { fix: CAS_FIX }
|
|
122
|
-
})),
|
|
123
|
-
status: result.ok ? "ok" : "error"
|
|
124
|
-
};
|
|
125
|
-
};
|
|
126
|
-
//#endregion
|
|
127
7
|
//#region src/doctor/cloudflare.ts
|
|
128
8
|
/**
|
|
129
9
|
* `baerly doctor --target=cloudflare` — walks the Cloudflare
|
|
@@ -140,8 +20,9 @@ const doctorCas = async (storage, keyPrefix) => {
|
|
|
140
20
|
* 4. If `cloudflareAccess` is set in `baerly.config.ts`,
|
|
141
21
|
* `audienceTag` is 64 lowercase-hex chars and `teamDomain`
|
|
142
22
|
* is non-empty.
|
|
143
|
-
* 5.
|
|
144
|
-
*
|
|
23
|
+
* 5. Report `triggers.crons` as optional. In-band write-triggered
|
|
24
|
+
* maintenance is the default; cron only drives an explicit
|
|
25
|
+
* `runScheduledMaintenance` sweep when the operator opts in.
|
|
145
26
|
* 6. If `baerly.config.ts:domain` is set but `wrangler.jsonc`
|
|
146
27
|
* doesn't declare a matching `routes` entry, warn.
|
|
147
28
|
*
|
|
@@ -159,7 +40,8 @@ const rollupStatus = (findings) => {
|
|
|
159
40
|
};
|
|
160
41
|
/**
|
|
161
42
|
* Read the declared cron schedule from `wrangler.jsonc`. Returns
|
|
162
|
-
* `[]` when missing — caller treats empty as
|
|
43
|
+
* `[]` when missing — caller treats empty as ok; in-band
|
|
44
|
+
* write-triggered maintenance is the default and needs no cron.
|
|
163
45
|
*/
|
|
164
46
|
const readDeclaredCrons = (wranglerPath) => {
|
|
165
47
|
const text = readFileSync(wranglerPath, "utf8");
|
|
@@ -342,15 +224,14 @@ const doctorCloudflare = async (config, opts = {}) => {
|
|
|
342
224
|
}
|
|
343
225
|
const crons = readDeclaredCrons(wranglerPath);
|
|
344
226
|
if (crons.length === 0) findings.push({
|
|
345
|
-
severity: "
|
|
227
|
+
severity: "ok",
|
|
346
228
|
check: "triggers.crons",
|
|
347
|
-
message: "no cron triggers declared;
|
|
348
|
-
fix: `Add "triggers": { "crons": ["* * * * *"] } to ${wranglerPath}.`
|
|
229
|
+
message: "no cron triggers declared; in-band write-triggered maintenance is the default."
|
|
349
230
|
});
|
|
350
231
|
else findings.push({
|
|
351
|
-
severity: "
|
|
232
|
+
severity: "info",
|
|
352
233
|
check: "triggers.crons",
|
|
353
|
-
message: `cron trigger${crons.length === 1 ? "" : "s"} ${crons.map((c) => JSON.stringify(c)).join(", ")} declared.`
|
|
234
|
+
message: `cron trigger${crons.length === 1 ? "" : "s"} ${crons.map((c) => JSON.stringify(c)).join(", ")} declared for opt-in scheduled maintenance; write-triggered maintenance still runs by default.`
|
|
354
235
|
});
|
|
355
236
|
if (config.domain !== void 0 && config.domain.length > 0) {
|
|
356
237
|
const patterns = readDeclaredRoutePatterns(wranglerPath);
|
|
@@ -389,10 +270,7 @@ const DOCTOR_ARGS = {
|
|
|
389
270
|
type: "boolean",
|
|
390
271
|
description: "Remediate auto-fixable findings (R2 bucket creation; secret prompts stay manual)."
|
|
391
272
|
},
|
|
392
|
-
json:
|
|
393
|
-
type: "boolean",
|
|
394
|
-
description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
|
|
395
|
-
}
|
|
273
|
+
json: JSON_ARG
|
|
396
274
|
};
|
|
397
275
|
const SEVERITY_GLYPH = {
|
|
398
276
|
ok: "✓",
|
|
@@ -465,4 +343,4 @@ bundle.run;
|
|
|
465
343
|
//#endregion
|
|
466
344
|
export { doctor };
|
|
467
345
|
|
|
468
|
-
//# sourceMappingURL=doctor-
|
|
346
|
+
//# sourceMappingURL=doctor-DSIyCDg_.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"doctor-DSIyCDg_.js","names":[],"sources":["../packages/cli/src/doctor/cloudflare.ts","../packages/cli/src/doctor.ts"],"sourcesContent":["/**\n * `baerly doctor --target=cloudflare` — walks the Cloudflare\n * deploy invariants and reports. With `--fix`, remediates what\n * can be safely auto-fixed (R2 bucket creation; secret prompts\n * are still user-driven because `wrangler secret put` reads\n * stdin interactively).\n *\n * Checks (each emitting one {@link DoctorFinding}):\n * 1. `wrangler.jsonc` exists at the package root.\n * 2. Each declared R2 binding exists in CF\n * (`wrangler r2 bucket info`).\n * 3. Each `requiredSecrets` entry is in `wrangler secret list`.\n * 4. If `cloudflareAccess` is set in `baerly.config.ts`,\n * `audienceTag` is 64 lowercase-hex chars and `teamDomain`\n * is non-empty.\n * 5. Report `triggers.crons` as optional. In-band write-triggered\n * maintenance is the default; cron only drives an explicit\n * `runScheduledMaintenance` sweep when the operator opts in.\n * 6. If `baerly.config.ts:domain` is set but `wrangler.jsonc`\n * doesn't declare a matching `routes` entry, warn.\n *\n * Output is a structured {@link DoctorReport} that\n * `packages/cli/src/doctor.ts` renders as either a checklist\n * (text mode) or a JSON envelope (`--json` mode).\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { parse, type ParseError } from \"jsonc-parser\";\nimport { BaerlyError, SHARED_SECRET_MISSING_MESSAGE } from \"@baerly/protocol\";\nimport type { AppConfig } from \"../config.ts\";\nimport { ensureBindings, parseR2Bindings, type ProcessRunner } from \"../deploy/cloudflare.ts\";\n\n/** One finding from a `baerly doctor` walk. */\nexport interface DoctorFinding {\n /** Severity. `ok` / `info` don't move the overall status. */\n readonly severity: \"ok\" | \"info\" | \"warning\" | \"error\";\n /** Short check name — stable, machine-readable. */\n readonly check: string;\n /** Human-friendly description. */\n readonly message: string;\n /** Optional remediation hint. */\n readonly fix?: string;\n}\n\n/** Result of a `baerly doctor` walk. */\nexport interface DoctorReport {\n readonly findings: readonly DoctorFinding[];\n /**\n * Overall: `ok` only when every finding has severity `ok` or\n * `info`. `warning` when the worst finding is a warning. `error`\n * when any finding is an error.\n */\n readonly status: \"ok\" | \"warning\" | \"error\";\n}\n\nconst rollupStatus = (findings: readonly DoctorFinding[]): DoctorReport[\"status\"] => {\n let worst: DoctorReport[\"status\"] = \"ok\";\n for (const f of findings) {\n if (f.severity === \"error\") {\n return \"error\";\n }\n if (f.severity === \"warning\") {\n worst = \"warning\";\n }\n }\n return worst;\n};\n\n/**\n * Read the declared cron schedule from `wrangler.jsonc`. Returns\n * `[]` when missing — caller treats empty as ok; in-band\n * write-triggered maintenance is the default and needs no cron.\n */\nconst readDeclaredCrons = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { triggers?: { crons?: unknown } }\n | undefined;\n if (errors.length > 0 || obj === undefined) {\n return [];\n }\n const crons = obj.triggers?.crons;\n if (!Array.isArray(crons)) {\n return [];\n }\n return crons.filter((c): c is string => typeof c === \"string\");\n};\n\n/** Read declared `routes[].pattern` array from `wrangler.jsonc`. */\nconst readDeclaredRoutePatterns = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { routes?: unknown }\n | undefined;\n if (errors.length > 0 || obj === undefined) {\n return [];\n }\n const routes = obj.routes;\n if (!Array.isArray(routes)) {\n return [];\n }\n return routes\n .map((r) =>\n r !== null && typeof r === \"object\" ? (r as { pattern?: unknown }).pattern : undefined,\n )\n .filter((p): p is string => typeof p === \"string\");\n};\n\n/** Read declared `vars` keys from `wrangler.jsonc`. */\nconst readDeclaredVarKeys = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { vars?: Record<string, unknown> }\n | undefined;\n if (errors.length > 0 || obj === undefined || obj.vars === undefined) {\n return [];\n }\n return Object.keys(obj.vars);\n};\n\n/**\n * Walk the Cloudflare deploy invariants. With `opts.fix === true`,\n * remediate the auto-fixable issues (bucket creation). Secret\n * prompts stay user-driven.\n */\nexport const doctorCloudflare = async (\n config: AppConfig,\n opts: {\n readonly runner?: ProcessRunner;\n readonly fix?: boolean;\n readonly cwd?: string;\n } = {},\n): Promise<DoctorReport> => {\n const repoRoot = opts.cwd ?? config.repoRoot;\n const wranglerPath = resolve(repoRoot, \"wrangler.jsonc\");\n const findings: DoctorFinding[] = [];\n\n // 1. wrangler.jsonc presence.\n if (!existsSync(wranglerPath)) {\n findings.push({\n severity: \"error\",\n check: \"wrangler.jsonc\",\n message: `Expected wrangler.jsonc at the package root: ${wranglerPath}.`,\n fix: \"Re-scaffold (npm create baerly@latest) or restore the file from git.\",\n });\n return { findings, status: rollupStatus(findings) };\n }\n findings.push({\n severity: \"ok\",\n check: \"wrangler.jsonc\",\n message: `${wranglerPath} found.`,\n });\n\n // 2. R2 bindings — parse first, then probe each.\n let declared: readonly { binding: string; bucket_name: string }[];\n try {\n declared = parseR2Bindings(wranglerPath);\n } catch (error) {\n if (error instanceof BaerlyError && error.code === \"InvalidConfig\") {\n findings.push({\n severity: \"error\",\n check: \"wrangler.jsonc.parse\",\n message: error.message,\n });\n return { findings, status: rollupStatus(findings) };\n }\n throw error;\n }\n\n if (opts.fix === true && opts.runner !== undefined) {\n // Run the same provisioning path the deploy fallback uses.\n // Any failure here surfaces as an error finding rather than\n // throwing — doctor's job is to report.\n try {\n await ensureBindings(opts.runner, repoRoot, wranglerPath);\n } catch (error) {\n findings.push({\n severity: \"error\",\n check: \"r2.fix\",\n message: error instanceof Error ? error.message : \"unknown error during ensureBindings\",\n });\n }\n }\n\n if (opts.runner !== undefined) {\n for (const { bucket_name } of declared) {\n const info = await opts.runner.run(\n \"wrangler\",\n [\"r2\", \"bucket\", \"info\", bucket_name],\n repoRoot,\n );\n if (info.code === 0) {\n findings.push({\n severity: \"ok\",\n check: `r2.${bucket_name}`,\n message: `R2 bucket \"${bucket_name}\" exists.`,\n });\n } else {\n findings.push({\n severity: \"error\",\n check: `r2.${bucket_name}`,\n message: `R2 bucket \"${bucket_name}\" not found.`,\n fix: `wrangler r2 bucket create ${bucket_name} (or re-run with --fix)`,\n });\n }\n }\n } else {\n findings.push({\n severity: \"info\",\n check: \"r2.skip\",\n message: \"no runner supplied; skipped R2 bucket probes.\",\n });\n }\n\n // 3. requiredSecrets — best-effort.\n //\n // `configured` is lifted to the outer scope so the auth-posture\n // block below can read the deployed secret set without re-running\n // `wrangler secret list`. Empty when the runner is absent or the\n // listing call failed.\n const required = config.requiredSecrets ?? [\"SHARED_SECRET\"];\n let configured: readonly string[] = [];\n if (opts.runner !== undefined && required.length > 0) {\n const r = await opts.runner.run(\"wrangler\", [\"secret\", \"list\"], repoRoot);\n if (r.code !== 0) {\n findings.push({\n severity: \"warning\",\n check: \"secrets\",\n message: \"could not list secrets (wrangler exit non-zero); skipping check.\",\n });\n } else {\n try {\n const parsed = JSON.parse(r.stdout) as unknown;\n if (Array.isArray(parsed)) {\n configured = parsed\n .map((s) =>\n s !== null && typeof s === \"object\" ? (s as { name?: unknown }).name : undefined,\n )\n .filter((n): n is string => typeof n === \"string\");\n }\n } catch {\n // fall through with empty configured set\n }\n for (const name of required) {\n if (configured.includes(name)) {\n findings.push({\n severity: \"ok\",\n check: `secret.${name}`,\n message: `secret ${name} is set.`,\n });\n } else {\n findings.push({\n severity: \"warning\",\n check: `secret.${name}`,\n message: `secret ${name} is required but unset.`,\n fix: `wrangler secret put ${name}`,\n });\n }\n }\n }\n } else if (required.length > 0) {\n findings.push({\n severity: \"info\",\n check: \"secrets.skip\",\n message: \"no runner supplied; skipped secret checks.\",\n });\n }\n\n // 7. config.auth — graduated-auth posture. Walks the typed `auth`\n // field added in `packages/protocol/src/app-config.ts`.\n // FAIL: shared-secret without SHARED_SECRET set on the worker.\n // WARN: auth: \"none\" + deploy target (operator may have a\n // network gate in front; surface it so they confirm).\n // INFO: CF Access vars present + adapter uses config.auth (auth\n // is using config.auth, CF Access env is inert).\n //\n // The presence of the typed field is guaranteed by the loader\n // (config.ts throws on omission), so we walk every loaded config\n // without an existence guard.\n if (config.auth === \"none\") {\n // Deploy-target check: \"cloudflare\" / \"node\" are the only valid\n // values, and both ship to a network-reachable runtime. We warn\n // unconditionally — the doctor's job is to surface the choice,\n // not to second-guess whether the operator's network seam (CF\n // Access, intranet ACL, Tunnel) is upstream.\n findings.push({\n severity: \"warning\",\n check: \"auth.none-on-deploy\",\n message:\n `baerly.config.ts has auth: \"none\" and ships to target=${JSON.stringify(config.target)}. ` +\n \"Every request will resolve to config.tenant with no header check. \" +\n \"Put a network gate in front (CF Access, an upstream JWT, Cloudflare Tunnel, intranet ACL, …) \" +\n 'or change `auth` to \"shared-secret\" or pass a custom `verifier:` on the adapter factory.',\n fix:\n 'Edit baerly.config.ts: set `auth: \"shared-secret\"` and run `wrangler secret put SHARED_SECRET`; ' +\n 'or keep `auth: \"none\"` and wire CF Access in `wrangler.jsonc:vars` + pass a `verifier:` override in `src/server/index.ts`.',\n });\n }\n\n if (config.auth === \"shared-secret\" && opts.runner !== undefined) {\n // Mirror the FAIL message wording from the adapter's runtime\n // throw. Locked via `SHARED_SECRET_MISSING_MESSAGE` so doctor +\n // adapter stay in sync.\n //\n // If `configured` is still empty here, the `wrangler secret list`\n // invocation either failed (we already warned with the \"secrets\"\n // finding above) or really lists no secrets. Either way the\n // operator-facing remediation is the same.\n const requiredSecret = \"SHARED_SECRET\";\n if (!configured.includes(requiredSecret)) {\n findings.push({\n severity: \"error\",\n check: \"auth.shared-secret-missing\",\n message: SHARED_SECRET_MISSING_MESSAGE,\n fix:\n \"wrangler secret put SHARED_SECRET (for production) \" +\n \"or add SHARED_SECRET=<value> to .dev.vars (for `wrangler dev`).\",\n });\n }\n }\n\n // INFO: CF Access env vars in wrangler.jsonc:vars but the adapter\n // is using `config.auth` for the verifier (so the env values are\n // inert). We can't statically parse the user's worker source —\n // surface the heuristic.\n const varKeys = new Set(readDeclaredVarKeys(wranglerPath));\n if (varKeys.has(\"CF_ACCESS_TEAM_DOMAIN\") && varKeys.has(\"CF_ACCESS_AUDIENCE_TAG\")) {\n findings.push({\n severity: \"info\",\n check: \"auth.cf-access-inert\",\n message:\n `CF Access env vars (CF_ACCESS_TEAM_DOMAIN, CF_ACCESS_AUDIENCE_TAG) are set in ${wranglerPath} ` +\n `but the adapter uses config.auth=${JSON.stringify(config.auth)}. ` +\n `To wire CF Access, pass \\`verifier: cloudflareAccess({ teamDomain, audienceTag })\\` on the baerlyWorker factory.`,\n });\n }\n\n // 4. cloudflareAccess — when configured, audience tag must be\n // 64 lowercase-hex chars.\n if (config.cloudflareAccess !== undefined) {\n const { teamDomain, audienceTag } = config.cloudflareAccess;\n if (teamDomain.length === 0) {\n findings.push({\n severity: \"error\",\n check: \"cloudflareAccess.teamDomain\",\n message: \"cloudflareAccess.teamDomain in baerly.config.ts is empty.\",\n });\n }\n if (!/^[0-9a-f]{64}$/.test(audienceTag)) {\n findings.push({\n severity: \"error\",\n check: \"cloudflareAccess.audienceTag\",\n message: `cloudflareAccess.audienceTag must be 64 lowercase-hex chars (got ${JSON.stringify(audienceTag)}).`,\n fix: \"Copy the AUD tag from the Cloudflare Access app's configuration tab.\",\n });\n } else if (teamDomain.length > 0) {\n findings.push({\n severity: \"ok\",\n check: \"cloudflareAccess\",\n message: `cloudflareAccess audience tag is well-formed; team domain \"${teamDomain}\".`,\n });\n }\n }\n\n // 5. Cron triggers — optional. In-band write-tick maintenance is\n // the default; cron only exists for an explicit out-of-band sweep.\n const crons = readDeclaredCrons(wranglerPath);\n if (crons.length === 0) {\n findings.push({\n severity: \"ok\",\n check: \"triggers.crons\",\n message: \"no cron triggers declared; in-band write-triggered maintenance is the default.\",\n });\n } else {\n findings.push({\n severity: \"info\",\n check: \"triggers.crons\",\n message:\n `cron trigger${crons.length === 1 ? \"\" : \"s\"} ${crons.map((c) => JSON.stringify(c)).join(\", \")} declared ` +\n \"for opt-in scheduled maintenance; write-triggered maintenance still runs by default.\",\n });\n }\n\n // 6. domain ↔ routes coherence.\n if (config.domain !== undefined && config.domain.length > 0) {\n const patterns = readDeclaredRoutePatterns(wranglerPath);\n const expectedPrefix = `${config.domain}/`;\n const hasMatch = patterns.some(\n (p) => p === config.domain || p === expectedPrefix || p.startsWith(expectedPrefix),\n );\n if (!hasMatch) {\n findings.push({\n severity: \"warning\",\n check: \"routes.domain\",\n message: `baerly.config.ts declares domain ${JSON.stringify(config.domain)} but ${wranglerPath} has no matching routes[].pattern.`,\n fix: `Add { \"pattern\": \"${config.domain}/*\", \"custom_domain\": true } to wrangler.jsonc:routes.`,\n });\n } else {\n findings.push({\n severity: \"ok\",\n check: \"routes.domain\",\n message: `routes[].pattern matches domain ${JSON.stringify(config.domain)}.`,\n });\n }\n }\n\n return { findings, status: rollupStatus(findings) };\n};\n","/**\n * `baerly doctor` — citty dispatcher for deploy-invariant checks.\n *\n * Two modes:\n * - `--bucket <uri>` — connect to a live bucket and probe its CAS\n * support (the protocol's load-bearing backend prerequisite). This\n * mode WRITES + deletes one throwaway sentinel; see\n * {@link doctorCas}. Independent of `baerly.config.ts` / `--target`.\n * - otherwise — reads `baerly.config.ts:target` and routes to\n * {@link doctorCloudflare} (read-only deploy-invariant checks). The\n * Node target self-validates at scaffold time — the example IS the\n * contract — so it has no doctor backend.\n *\n * Drift detection, index rebuilds, and writes/min health are separate\n * verbs:\n * - `baerly admin fsck --indexes [--fix]` — index drift.\n * - `baerly admin usage` — writes/min M-size graduation.\n * - `baerly admin rebuild-index` — single-index reconciliation.\n *\n * Renders the returned {@link DoctorReport} into either a\n * stdout checklist (text mode) or a JSON envelope (`--json`\n * mode).\n *\n * Exit-code contract (mirrors `baerly deploy`):\n * - 0 success — report status is `ok` or `warning`.\n * - 1 user error (InvalidConfig, unknown target, missing config).\n * - 2 storage / external error.\n * - 3 protocol invariant.\n *\n * A `warning` status returns exit 0 (the user can deploy; we just\n * flagged a maintenance / coherence issue). An `error` status\n * returns exit 2 unless the underlying cause was an InvalidConfig\n * (which already returned 1 via a thrown BaerlyError).\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { doctorCas } from \"./doctor/cas.ts\";\nimport { doctorCloudflare, type DoctorReport } from \"./doctor/cloudflare.ts\";\nimport { defaultRunner } from \"./runner.ts\";\nimport { color, isJsonMode } from \"./output.ts\";\nimport { defineBaerlySubcommand, JSON_ARG } from \"./subcommand.ts\";\n\nconst DOCTOR_ARGS = {\n target: {\n type: \"string\",\n description:\n 'Override `baerly.config.ts:target`. Only \"cloudflare\" supported (Node variants self-validate at scaffold time).',\n valueHint: \"cloudflare\",\n },\n bucket: {\n type: \"string\",\n description:\n \"Live-probe a bucket's CAS support (writes + deletes one sentinel; verifies If-Match / If-None-Match are honoured). s3://, file:///, or memory:// URI. Independent of --target.\",\n valueHint: \"s3://bucket/prefix\",\n },\n fix: {\n type: \"boolean\",\n description:\n \"Remediate auto-fixable findings (R2 bucket creation; secret prompts stay manual).\",\n },\n json: JSON_ARG,\n} as const satisfies ArgsDef;\n\nconst SEVERITY_GLYPH: Record<string, string> = {\n ok: \"✓\",\n info: \"•\",\n warning: \"⚠\",\n error: \"✗\",\n};\n\nconst colorize = (severity: string, glyph: string): string => {\n if (severity === \"error\") {\n return color.red(glyph);\n }\n if (severity === \"warning\") {\n return color.yellow(glyph);\n }\n if (severity === \"info\") {\n return color.dim(glyph);\n }\n return glyph;\n};\n\nconst renderReport = (\n label: { kind: \"target\" | \"bucket\"; value: string },\n report: DoctorReport,\n): void => {\n if (isJsonMode()) {\n process.stdout.write(\n `${JSON.stringify({ result: { command: \"doctor\", [label.kind]: label.value, ...report } })}\\n`,\n );\n return;\n }\n process.stdout.write(`baerly doctor --${label.kind}=${label.value}\\n\\n`);\n let okCount = 0;\n let warningCount = 0;\n let errorCount = 0;\n for (const f of report.findings) {\n const glyph = SEVERITY_GLYPH[f.severity] ?? \"•\";\n process.stdout.write(` ${colorize(f.severity, glyph)} ${f.message}\\n`);\n if (f.fix !== undefined) {\n process.stdout.write(` fix: ${f.fix}\\n`);\n }\n if (f.severity === \"ok\") {\n okCount += 1;\n } else if (f.severity === \"warning\") {\n warningCount += 1;\n } else if (f.severity === \"error\") {\n errorCount += 1;\n }\n }\n process.stdout.write(\n `\\nStatus: ${errorCount} error${errorCount === 1 ? \"\" : \"s\"}, ${warningCount} warning${warningCount === 1 ? \"\" : \"s\"}, ${okCount} ok.\\n`,\n );\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"doctor\",\n meta: {\n description:\n \"Walk the deploy invariants and report findings. Dispatches by baerly.config.ts:target.\",\n },\n args: DOCTOR_ARGS,\n handler: async (args) => {\n // --bucket is a standalone live-probe mode: it connects to a real\n // bucket and checks CAS, independent of baerly.config.ts / --target.\n if (args.bucket !== undefined) {\n const { storage, keyPrefix } = await parseBucketUri(args.bucket);\n const report = await doctorCas(storage, keyPrefix);\n renderReport({ kind: \"bucket\", value: args.bucket }, report);\n return report.status === \"error\" ? 2 : 0;\n }\n const config = await loadAppConfig();\n const target = args.target ?? config.target;\n if (target === \"cloudflare\") {\n const report = await doctorCloudflare(config, {\n runner: defaultRunner(),\n ...(args.fix === true && { fix: true }),\n });\n renderReport({ kind: \"target\", value: target }, report);\n return report.status === \"error\" ? 2 : 0;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly doctor: target ${JSON.stringify(target)} has no doctor backend. ` +\n `(Node variants self-validate at scaffold time; the example IS the contract.)`,\n );\n },\n});\n\n/** citty `defineCommand` block for `baerly doctor`. */\nexport const doctor = 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 runDoctor = bundle.run;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,gBAAgB,aAA+D;CACnF,IAAI,QAAgC;CACpC,KAAK,MAAM,KAAK,UAAU;EACxB,IAAI,EAAE,aAAa,SACjB,OAAO;EAET,IAAI,EAAE,aAAa,WACjB,QAAQ;CAEZ;CACA,OAAO;AACT;;;;;;AAOA,MAAM,qBAAqB,iBAA4C;CACrE,MAAM,OAAO,aAAa,cAAc,MAAM;CAC9C,MAAM,SAAuB,CAAC;CAC9B,MAAM,MAAM,MAAM,MAAM,QAAQ;EAAE,oBAAoB;EAAM,kBAAkB;CAAM,CAAC;CAGrF,IAAI,OAAO,SAAS,KAAK,QAAQ,KAAA,GAC/B,OAAO,CAAC;CAEV,MAAM,QAAQ,IAAI,UAAU;CAC5B,IAAI,CAAC,MAAM,QAAQ,KAAK,GACtB,OAAO,CAAC;CAEV,OAAO,MAAM,QAAQ,MAAmB,OAAO,MAAM,QAAQ;AAC/D;;AAGA,MAAM,6BAA6B,iBAA4C;CAC7E,MAAM,OAAO,aAAa,cAAc,MAAM;CAC9C,MAAM,SAAuB,CAAC;CAC9B,MAAM,MAAM,MAAM,MAAM,QAAQ;EAAE,oBAAoB;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EACA,MAAM,SAAS,MAAM,cAAc;EACnC,MAAM,SAAS,KAAK,UAAU,OAAO;EACrC,IAAI,WAAW,cAAc;GAC3B,MAAM,SAAS,MAAM,iBAAiB,QAAQ;IAC5C,QAAQ,cAAc;IACtB,GAAI,KAAK,QAAQ,QAAQ,EAAE,KAAK,KAAK;GACvC,CAAC;GACD,aAAa;IAAE,MAAM;IAAU,OAAO;GAAO,GAAG,MAAM;GACtD,OAAO,OAAO,WAAW,UAAU,IAAI;EACzC;EACA,MAAM,IAAI,YACR,iBACA,yBAAyB,KAAK,UAAU,MAAM,EAAE,qGAElD;CACF;AACF,CAAC;;AAGD,MAAa,SAAS,OAAO;AAOJ,OAAO"}
|
|
@@ -1,37 +1,15 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { r as parseBucketUri } from "./config-1tv0-Yzm.js";
|
|
2
2
|
import { o as BaerlyError, r as emitSuccess } from "./baerly.js";
|
|
3
|
-
import { n as loadMaterialisedView } from "./plan-
|
|
3
|
+
import { n as loadMaterialisedView } from "./plan-a7PJHBCy.js";
|
|
4
|
+
import { a as TENANT_ARG, i as JSON_ARG, n as BUCKET_ARG, o as assertCollectionArg, r as COLLECTION_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-DoDA-K7d.js";
|
|
4
5
|
import "node:stream";
|
|
5
6
|
//#region src/admin/dump.ts
|
|
6
7
|
const DUMP_ARGS = {
|
|
7
|
-
bucket:
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
},
|
|
13
|
-
app: {
|
|
14
|
-
type: "string",
|
|
15
|
-
required: false,
|
|
16
|
-
description: "Application name segment (defaults to baerly.config.ts).",
|
|
17
|
-
valueHint: "app"
|
|
18
|
-
},
|
|
19
|
-
tenant: {
|
|
20
|
-
type: "string",
|
|
21
|
-
required: false,
|
|
22
|
-
description: "Tenant name segment (defaults to baerly.config.ts).",
|
|
23
|
-
valueHint: "tenant"
|
|
24
|
-
},
|
|
25
|
-
collection: {
|
|
26
|
-
type: "string",
|
|
27
|
-
required: true,
|
|
28
|
-
description: "Collection name.",
|
|
29
|
-
valueHint: "name"
|
|
30
|
-
},
|
|
31
|
-
json: {
|
|
32
|
-
type: "boolean",
|
|
33
|
-
description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
|
|
34
|
-
}
|
|
8
|
+
bucket: BUCKET_ARG,
|
|
9
|
+
app: APP_ARG,
|
|
10
|
+
tenant: TENANT_ARG,
|
|
11
|
+
collection: COLLECTION_ARG,
|
|
12
|
+
json: JSON_ARG
|
|
35
13
|
};
|
|
36
14
|
/**
|
|
37
15
|
* Recursive byte-stable JSON stringifier. Object keys at every nesting
|
|
@@ -89,6 +67,7 @@ const bundle = defineBaerlySubcommand({
|
|
|
89
67
|
app: args.app,
|
|
90
68
|
tenant: args.tenant
|
|
91
69
|
});
|
|
70
|
+
assertCollectionArg(args.collection, "baerly admin dump");
|
|
92
71
|
const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;
|
|
93
72
|
const view = await loadMaterialisedView({
|
|
94
73
|
storage: bucket.storage,
|
|
@@ -112,4 +91,4 @@ bundle.run;
|
|
|
112
91
|
//#endregion
|
|
113
92
|
export { dumpCmd };
|
|
114
93
|
|
|
115
|
-
//# sourceMappingURL=dump-
|
|
94
|
+
//# sourceMappingURL=dump-Bh5k26VQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dump-Bh5k26VQ.js","names":[],"sources":["../packages/cli/src/admin/dump.ts"],"sourcesContent":["/**\n * `baerly admin dump` — canonical NDJSON of the materialised view.\n *\n * Writes one row per line to stdout, in a strict byte-stable shape so\n * two semantically-equal collections produce byte-equal output. Tests\n * and other programmatic callers can divert the NDJSON output to a\n * file or buffer by passing `{ streams: { stdout } }` to {@link runDump}.\n *\n * Canonical NDJSON dump format:\n *\n * 1. Each row is `{\"_id\":\"<id>\",…}` (no spaces).\n * 2. Row order = ASCII-lex sort on `_id`.\n * 3. Within each row, object keys are sorted ASCII-lex\n * RECURSIVELY — every nested object's keys are sorted too.\n * 4. Numbers as their canonical `JSON.stringify` output.\n * Finite-only (the protocol forbids NaN / Infinity).\n * 5. Strings as `JSON.stringify` output (escape sequences\n * identical to `\\uXXXX` for control codes).\n * 6. One trailing newline at EOF (`\\n`, not `\\r\\n`).\n * 7. No BOM.\n *\n * The round-trip ticket (73) gates byte-equality on this format. A\n * change to any of (1)–(7) is a BREAKING change requiring a\n * round-trip schema-version bump.\n *\n * Empty collection → empty file (no trailing newline) — disambiguates\n * \"zero rows\" from \"one row with empty body\".\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --json JSON envelope (on stdout). Programmatic callers can\n * divert the NDJSON body to a separate writable via the\n * `streams.stdout` option on {@link runDump}.\n *\n * Exit codes:\n * 0 — dump completed.\n * 1 — InvalidConfig (bad bucket URI, missing args).\n * 2 — Storage / Network / Internal protocol violation.\n * 3 — Protocol invariant (Conflict / Internal / InvalidResponse).\n */\n\nimport { type Writable } from \"node:stream\";\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, type DocumentValue, type DocumentData } from \"@baerly/protocol\";\nimport { loadMaterialisedView } from \"../export/index.ts\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess } from \"../output.ts\";\nimport {\n APP_ARG,\n assertCollectionArg,\n BUCKET_ARG,\n COLLECTION_ARG,\n defineBaerlySubcommand,\n JSON_ARG,\n TENANT_ARG,\n} from \"../subcommand.ts\";\n\nconst DUMP_ARGS = {\n bucket: BUCKET_ARG,\n app: APP_ARG,\n tenant: TENANT_ARG,\n collection: COLLECTION_ARG,\n json: JSON_ARG,\n} as const satisfies ArgsDef;\n\n/**\n * Recursive byte-stable JSON stringifier. Object keys at every nesting\n * level are sorted ASCII-lex; array element order is preserved as-is.\n * Numbers must be finite (protocol forbids NaN / Infinity in bodies).\n */\nexport const canonicalStringify = (value: DocumentValue): string => {\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `baerly admin dump: non-finite number in row body (${String(value)}); protocol violation`,\n );\n }\n return JSON.stringify(value);\n }\n if (typeof value === \"string\" || typeof value === \"boolean\") {\n return JSON.stringify(value);\n }\n if (value === null) {\n // DocumentValue excludes null at the type level, but `unknown` may\n // sneak in via the snapshot fold — be defensive.\n return \"null\";\n }\n if (Array.isArray(value)) {\n const parts = value.map((v) => canonicalStringify(v));\n return `[${parts.join(\",\")}]`;\n }\n if (typeof value === \"object\") {\n const keys = Object.keys(value).toSorted();\n const parts: string[] = [];\n for (const k of keys) {\n const v = (value as Record<string, DocumentValue>)[k];\n if (v === undefined) {\n continue;\n }\n parts.push(`${JSON.stringify(k)}:${canonicalStringify(v)}`);\n }\n return `{${parts.join(\",\")}}`;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `baerly admin dump: unsupported value type ${typeof value}`,\n );\n};\n\n/**\n * Drain rows to the supplied writable, applying back-pressure on every\n * line. We don't `end()` the stream — the caller owns its lifecycle\n * (`process.stdout` shouldn't be closed; a test-supplied\n * `createWriteStream` flushes on its own `end()`).\n */\nconst writeToSink = async (\n sink: Writable,\n rows: ReadonlyMap<string, DocumentData>,\n): Promise<number> => {\n const ids = [...rows.keys()].toSorted();\n let count = 0;\n for (const id of ids) {\n const body = rows.get(id);\n if (body === undefined) {\n continue;\n }\n // Merge `_id` into the body so the row literal carries it. The\n // map key is authoritative; if a stale `_id` field disagrees, we\n // overwrite it.\n const row: DocumentData = { ...body, _id: id };\n const line = `${canonicalStringify(row)}\\n`;\n if (!sink.write(line)) {\n await new Promise<void>((resolve) => sink.once(\"drain\", resolve));\n }\n count++;\n }\n return count;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.dump\",\n meta: {\n description: \"Canonical NDJSON of the materialised view of one collection.\",\n },\n args: DUMP_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n assertCollectionArg(args.collection, \"baerly admin dump\");\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n const view = await loadMaterialisedView({\n storage: bucket.storage,\n currentJsonKey,\n collection: args.collection,\n });\n if (view === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin dump: current.json not found at ${currentJsonKey}`,\n );\n }\n const sink: Writable = ctx.streams?.stdout ?? process.stdout;\n const count = await writeToSink(sink, view);\n emitSuccess({\n command: \"admin.dump\",\n status: \"ok\",\n collection: args.collection,\n dumped: count,\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin dump`. */\nexport const dumpCmd = 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 runDump = bundle.run;\n"],"mappings":";;;;;;AA4DA,MAAM,YAAY;CAChB,QAAQ;CACR,KAAK;CACL,QAAQ;CACR,YAAY;CACZ,MAAM;AACR;;;;;;AAOA,MAAa,sBAAsB,UAAiC;CAClE,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,CAAC,OAAO,SAAS,KAAK,GACxB,MAAM,IAAI,YACR,mBACA,qDAAqD,OAAO,KAAK,EAAE,sBACrE;EAEF,OAAO,KAAK,UAAU,KAAK;CAC7B;CACA,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,WAChD,OAAO,KAAK,UAAU,KAAK;CAE7B,IAAI,UAAU,MAGZ,OAAO;CAET,IAAI,MAAM,QAAQ,KAAK,GAErB,OAAO,IADO,MAAM,KAAK,MAAM,mBAAmB,CAAC,CACpC,CAAC,CAAC,KAAK,GAAG,EAAE;CAE7B,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,OAAO,OAAO,KAAK,KAAK,CA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gBAClD;EAGF,MAAM,QAAQ,MAAM,YADG,IAAI,SAAS,UAAU,QAAQ,QAChB,IAAI;EAC1C,YAAY;GACV,SAAS;GACT,QAAQ;GACR,YAAY,KAAK;GACjB,QAAQ;EACV,CAAC;EACD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,UAAU,OAAO;AAOP,OAAO"}
|
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
//#region packages/protocol/src/errors.ts
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* Codes whose default failure class is resolved by retrying with a fresh read.
|
|
4
|
+
* Throw sites may override this when the same code is context-sensitive
|
|
5
|
+
* (notably caller-supplied `_id` collisions, which also use `Conflict`).
|
|
6
|
+
*/
|
|
7
|
+
const RETRIABLE_CODES = /* @__PURE__ */ new Set(["NetworkError", "Conflict"]);
|
|
8
|
+
/** True iff this error code's default failure class is retriable. */
|
|
9
|
+
const isRetriableCode = (code) => RETRIABLE_CODES.has(code);
|
|
10
|
+
/**
|
|
11
|
+
* The single error class thrown by baerly-storage. Discriminate by `code`, not
|
|
4
12
|
* `instanceof`: the code string survives `JSON.stringify` round-trips
|
|
5
13
|
* across Worker / iframe / postMessage realm boundaries, where each
|
|
6
14
|
* realm has its own `BaerlyError` constructor identity. IDB-restored
|
|
@@ -13,7 +21,7 @@
|
|
|
13
21
|
* await db.collection("tickets").insert({ title: "hi" });
|
|
14
22
|
* } catch (err) {
|
|
15
23
|
* if (err instanceof BaerlyError && err.code === "Conflict") {
|
|
16
|
-
* //
|
|
24
|
+
* // Check err.retriable; CAS can retry, duplicate _id cannot.
|
|
17
25
|
* }
|
|
18
26
|
* throw err;
|
|
19
27
|
* }
|
|
@@ -43,16 +51,28 @@ var BaerlyError = class extends Error {
|
|
|
43
51
|
* you genuinely need the wire value.
|
|
44
52
|
*/
|
|
45
53
|
status;
|
|
46
|
-
|
|
54
|
+
/** Canonical corrective action; crosses the wire via `HttpErrorEnvelope.error.resolution`. */
|
|
55
|
+
resolution;
|
|
56
|
+
retriableOverride;
|
|
57
|
+
/**
|
|
58
|
+
* Whether this error instance is retriable. Defaults from `code`, but
|
|
59
|
+
* context-sensitive throw sites can override it.
|
|
60
|
+
*/
|
|
61
|
+
get retriable() {
|
|
62
|
+
return this.retriableOverride ?? isRetriableCode(this.code);
|
|
63
|
+
}
|
|
64
|
+
constructor(code, message, cause, issues, status, resolution, retriableOverride) {
|
|
47
65
|
super(message);
|
|
48
66
|
this.name = "BaerlyError";
|
|
49
67
|
this.code = code;
|
|
50
68
|
this.cause = cause;
|
|
69
|
+
this.retriableOverride = retriableOverride;
|
|
51
70
|
if (issues !== void 0) this.issues = issues;
|
|
52
71
|
if (status !== void 0) this.status = status;
|
|
72
|
+
if (resolution !== void 0) this.resolution = resolution;
|
|
53
73
|
}
|
|
54
74
|
};
|
|
55
75
|
//#endregion
|
|
56
|
-
export { BaerlyError as t };
|
|
76
|
+
export { isRetriableCode as n, BaerlyError as t };
|
|
57
77
|
|
|
58
|
-
//# sourceMappingURL=errors-
|
|
78
|
+
//# sourceMappingURL=errors-Dfa3p78c.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-Dfa3p78c.js","names":[],"sources":["../packages/protocol/src/errors.ts"],"sourcesContent":["/**\n * Discriminator for {@link BaerlyError}. Strings (not subclasses) so they\n * survive cross-realm boundaries (e.g. a Web Worker) and so callers can\n * pattern-match with grep-friendly equality.\n */\nexport type BaerlyErrorCode =\n /** Caller-provided config or input is invalid (bad bucket, unsupported credential type, malformed URL, bucket not version-enabled when versioning was requested). */\n | \"InvalidConfig\"\n /** Generic S3/HTTP transport failure (5xx, unexpected status, retries exhausted). */\n | \"NetworkError\"\n /** S3 returned 403. Either credentials are wrong or the bucket policy denies the operation. */\n | \"AccessDenied\"\n /** Server returned data that didn't parse (malformed XML, non-JSON body where JSON expected). */\n | \"InvalidResponse\"\n /** Internal invariant violation — should not be reachable. File a bug. */\n | \"Internal\"\n /**\n * Document body failed schema validation. Emitted by the table-API\n * write verbs (`Collection.insert`, `Query.update`, `Collection.replace`) when\n * the body is not valid JSON or contains an array where\n * `DocumentValue` is required; also emitted when a collection has a\n * declared `SchemaValidator` (via `Db.create({ collections })`) and\n * the bound schema rejects the doc. In the schema-rejection case the\n * error carries an `issues` array describing each failure. HTTP layer\n * maps this to 400.\n */\n | \"SchemaError\"\n /**\n * Write conflicted with current state: CAS retry budget exhausted,\n * duplicate caller-supplied `_id`, or an already-existing guarded\n * storage key. Check `BaerlyError.retriable` to decide whether the\n * same logical operation should be retried.\n */\n | \"Conflict\"\n /**\n * `Verifier` returned no identity. HTTP server maps to 401.\n * Code is reserved here so the union locks.\n */\n | \"Unauthorized\"\n /**\n * The addressed resource does not exist. HTTP server maps to 404.\n * Emitted by the row-by-id read / update / delete handlers in\n * `packages/server/src/http/router.ts` when the predicate\n * `{ _id }` matches zero rows. Not a protocol invariant —\n * callers may retry after creating the resource or treat as a\n * miss depending on intent. The CLI maps this to the generic\n * exit-2 \"storage error\" bucket, not the exit-3 \"protocol\n * invariant\" bucket.\n */\n | \"NotFound\"\n /**\n * Request body exceeded the server's size cap. HTTP server maps\n * to 413. Cap is `MAX_BODY_BYTES` (1 MiB today; exported from\n * `packages/server/src/http/router.ts`). The Node adapter\n * enforces during the `node:http` stream pump so the process\n * never materializes a multi-MiB body; Workers also rely on\n * platform-side caps (16 MB free / 100 MB paid).\n */\n | \"PayloadTooLarge\"\n /**\n * A predicate is structurally well-formed but contradicts itself —\n * no document can match. Emitted by `validateWire` and\n * `mergePredicateWires`. Triggers:\n * - `{ clauses: [{op:\"in\", field:\"priority\", value:[]}] }` (empty `in` set)\n * - an `eq` clause with a value outside the residual interval\n * established by range clauses on the same field\n * - merging `{op:\"gt\", value:10}` with `{op:\"lt\", value:5}` on the\n * same field (empty interval)\n * - merging two `in` clauses on the same field with empty intersection\n *\n * Conflicting equality across clauses (`eq:\"open\"` + `eq:\"closed\"` on\n * the same field) surfaces as `InvalidConfig` rather than this code —\n * the merger treats it as a caller-side configuration bug, not an\n * algebraic contradiction.\n *\n * The HTTP layer treats this as a 400 (caller error). The distinct\n * code lets downstream code short-circuit empty-by-construction\n * without re-running the validator or parsing messages.\n */\n | \"UnsatisfiablePredicate\"\n /**\n * A `useQuery` callback awaited a recorder terminal\n * (`.get`/`.first`/`.all`/`.count`). The recorder runs once per\n * render to capture the chain shape; it cannot survive an `await`\n * because the proxy doesn't proxy across microtask boundaries. The\n * recorder's terminal returns a thenable whose `.then` throws this\n * error synchronously, converting what would otherwise be a silent\n * spinner-hang into a render-time error the hook surfaces as\n * `status: \"error\"`. Companion `baerly/no-await-in-use-query` lint\n * flags the pattern at edit time. For compound reads, use\n * `Promise.all` (parallel) or compose two `useQuery` calls with\n * `useQuery.skip` (dependent).\n */\n | \"UseQueryAwaitedRecorder\"\n /**\n * A write method (`.insert`/`.update`/`.replace`/`.delete`) was\n * called on the recorder inside a `useQuery` callback. Writes\n * inside reads are a programming error; the recorder rejects them\n * synchronously from the discovery pass, before any I/O fires. Use\n * `useMutation()` instead.\n */\n | \"UnexpectedWriteInQuery\"\n /**\n * A `useMutation()` callback rejected with a non-`BaerlyError`\n * throwable. The hook wraps the original throw under this code so\n * the `error` slot is always a `BaerlyError`; the original value\n * is preserved on `.cause`.\n */\n | \"MutationFailed\";\n\n/**\n * Runtime enumeration of every {@link BaerlyErrorCode}. The spec\n * generator and the drift gate iterate this to assert the IR lists\n * each code; the type guard in `spec/ir-schema.test.ts` fails tsgo if\n * this tuple and the union diverge. Keep order stable for deterministic\n * artifact diffs. This is the canonical code list — do not re-list\n * codes elsewhere (see RETRIABLE_CODES, the sibling retriable subset).\n */\nexport const ERROR_CODES = [\n \"InvalidConfig\",\n \"NetworkError\",\n \"AccessDenied\",\n \"InvalidResponse\",\n \"Internal\",\n \"SchemaError\",\n \"Conflict\",\n \"Unauthorized\",\n \"NotFound\",\n \"PayloadTooLarge\",\n \"UnsatisfiablePredicate\",\n \"UseQueryAwaitedRecorder\",\n \"UnexpectedWriteInQuery\",\n \"MutationFailed\",\n] as const satisfies readonly BaerlyErrorCode[];\n\n// Exhaustiveness guard: every union member must appear in ERROR_CODES.\n// If a code is added to BaerlyErrorCode without a tuple entry, this\n// errors at tsgo time (the union is not assignable to the tuple's union).\ntype _ErrorCodesExhaustive = [BaerlyErrorCode] extends [(typeof ERROR_CODES)[number]]\n ? true\n : [\"missing code in ERROR_CODES\", Exclude<BaerlyErrorCode, (typeof ERROR_CODES)[number]>];\n// eslint-disable-next-line no-underscore-dangle\nconst _errorCodesExhaustive: _ErrorCodesExhaustive = true;\nvoid _errorCodesExhaustive;\n\n/**\n * Codes whose default failure class is resolved by retrying with a fresh read.\n * Throw sites may override this when the same code is context-sensitive\n * (notably caller-supplied `_id` collisions, which also use `Conflict`).\n */\nexport const RETRIABLE_CODES: ReadonlySet<BaerlyErrorCode> = new Set<BaerlyErrorCode>([\n \"NetworkError\",\n \"Conflict\",\n]);\n\n/** True iff this error code's default failure class is retriable. */\nexport const isRetriableCode = (code: BaerlyErrorCode): boolean => RETRIABLE_CODES.has(code);\n\n/**\n * Codes raised only inside the client-side React runtime\n * (`useQuery` / `useMutation`); they never travel the HTTP wire, so the\n * machine-contract IR reports `httpStatus: null` for them — distinct\n * from a real `500` (a server-side transport/internal failure the HTTP\n * layer maps to a status). Sibling of {@link RETRIABLE_CODES}; add a\n * code here when a new client-only failure mode joins the union.\n */\nexport const CLIENT_RUNTIME_CODES: ReadonlySet<BaerlyErrorCode> = new Set<BaerlyErrorCode>([\n \"UseQueryAwaitedRecorder\",\n \"UnexpectedWriteInQuery\",\n \"MutationFailed\",\n]);\n\n/**\n * The single error class thrown by baerly-storage. Discriminate by `code`, not\n * `instanceof`: the code string survives `JSON.stringify` round-trips\n * across Worker / iframe / postMessage realm boundaries, where each\n * realm has its own `BaerlyError` constructor identity. IDB-restored\n * writes can replay across realms, so `instanceof` would spuriously\n * fail on a structurally-identical error from another realm.\n *\n * @example\n * ```ts\n * try {\n * await db.collection(\"tickets\").insert({ title: \"hi\" });\n * } catch (err) {\n * if (err instanceof BaerlyError && err.code === \"Conflict\") {\n * // Check err.retriable; CAS can retry, duplicate _id cannot.\n * }\n * throw err;\n * }\n * ```\n */\nexport class BaerlyError extends Error {\n readonly code: BaerlyErrorCode;\n override readonly cause?: unknown;\n /**\n * Structured field-path issues, set only when `code === \"SchemaError\"`.\n * Each entry's `path` is a dotted-key list (e.g. `[\"assignee\", \"team\"]`\n * or `[\"items\", 3, \"qty\"]`) that targets the offending field on the\n * input document. `message` is the validator-emitted human string.\n *\n * The HTTP layer's `mapError` renders these into the 400 body via\n * the existing `HttpErrorEnvelope`; older callers that don't know\n * about `issues` see a plain message-only error and stay correct.\n */\n readonly issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>;\n /**\n * Raw HTTP status, set only by the client-side wire decoder when\n * inflating an `HttpErrorEnvelope` into this class. Server-side\n * throws never set it (the HTTP layer's `mapError` derives the\n * outbound status from `code`). Useful for diagnostics — e.g. to\n * distinguish 404-as-\"no such row\" from 404-as-\"route not found\".\n * Discriminate by `code` for behavior; reach for `status` only when\n * you genuinely need the wire value.\n */\n readonly status?: number;\n /** Canonical corrective action; crosses the wire via `HttpErrorEnvelope.error.resolution`. */\n readonly resolution?: string;\n private readonly retriableOverride: boolean | undefined;\n\n /**\n * Whether this error instance is retriable. Defaults from `code`, but\n * context-sensitive throw sites can override it.\n */\n get retriable(): boolean {\n return this.retriableOverride ?? isRetriableCode(this.code);\n }\n\n constructor(\n code: BaerlyErrorCode,\n message: string,\n cause?: unknown,\n issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>,\n status?: number,\n resolution?: string,\n retriableOverride?: boolean,\n ) {\n super(message);\n this.name = \"BaerlyError\";\n this.code = code;\n this.cause = cause;\n this.retriableOverride = retriableOverride;\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (issues !== undefined) {\n this.issues = issues;\n }\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (status !== undefined) {\n this.status = status;\n }\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (resolution !== undefined) {\n this.resolution = resolution;\n }\n }\n}\n"],"mappings":";;;;;;AAsJA,MAAa,kCAAgD,IAAI,IAAqB,CACpF,gBACA,UACF,CAAC;;AAGD,MAAa,mBAAmB,SAAmC,gBAAgB,IAAI,IAAI;;;;;;;;;;;;;;;;;;;;;AAoC3F,IAAa,cAAb,cAAiC,MAAM;CACrC;CACA;;;;;;;;;;;CAWA;;;;;;;;;;CAaA;;CAEA;CACA;;;;;CAMA,IAAI,YAAqB;EACvB,OAAO,KAAK,qBAAqB,gBAAgB,KAAK,IAAI;CAC5D;CAEA,YACE,MACA,SACA,OACA,QAIA,QACA,YACA,mBACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,QAAQ;EACb,KAAK,oBAAoB;EAEzB,IAAI,WAAW,KAAA,GACb,KAAK,SAAS;EAGhB,IAAI,WAAW,KAAA,GACb,KAAK,SAAS;EAGhB,IAAI,eAAe,KAAA,GACjB,KAAK,aAAa;CAEtB;AACF"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as
|
|
1
|
+
import { r as parseBucketUri } from "./config-1tv0-Yzm.js";
|
|
2
|
+
import { n as matchesWire, t as validateWire } from "./validate-DtljsCh1.js";
|
|
3
3
|
import { o as BaerlyError, r as emitSuccess } from "./baerly.js";
|
|
4
|
-
import { n as loadMaterialisedView, r as quoteValue, t as inferPlanForCollection } from "./plan-
|
|
4
|
+
import { n as loadMaterialisedView, r as quoteValue, t as inferPlanForCollection } from "./plan-a7PJHBCy.js";
|
|
5
|
+
import { a as TENANT_ARG, i as JSON_ARG, n as BUCKET_ARG, o as assertCollectionArg, r as COLLECTION_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-DoDA-K7d.js";
|
|
5
6
|
import { writeFile } from "node:fs/promises";
|
|
6
7
|
//#region src/export/ddl.ts
|
|
7
8
|
/**
|
|
@@ -266,30 +267,10 @@ const serializeExportPlan = (plan) => {
|
|
|
266
267
|
* 3 — Protocol invariant (Internal / InvalidResponse / Conflict).
|
|
267
268
|
*/
|
|
268
269
|
const EXPORT_ARGS = {
|
|
269
|
-
bucket:
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
valueHint: "bucket-uri"
|
|
274
|
-
},
|
|
275
|
-
app: {
|
|
276
|
-
type: "string",
|
|
277
|
-
required: false,
|
|
278
|
-
description: "Application name segment (defaults to baerly.config.ts).",
|
|
279
|
-
valueHint: "app"
|
|
280
|
-
},
|
|
281
|
-
tenant: {
|
|
282
|
-
type: "string",
|
|
283
|
-
required: false,
|
|
284
|
-
description: "Tenant name segment (defaults to baerly.config.ts).",
|
|
285
|
-
valueHint: "tenant"
|
|
286
|
-
},
|
|
287
|
-
collection: {
|
|
288
|
-
type: "string",
|
|
289
|
-
required: true,
|
|
290
|
-
description: "Collection name.",
|
|
291
|
-
valueHint: "name"
|
|
292
|
-
},
|
|
270
|
+
bucket: BUCKET_ARG,
|
|
271
|
+
app: APP_ARG,
|
|
272
|
+
tenant: TENANT_ARG,
|
|
273
|
+
collection: COLLECTION_ARG,
|
|
293
274
|
target: {
|
|
294
275
|
type: "enum",
|
|
295
276
|
options: [
|
|
@@ -323,10 +304,7 @@ const EXPORT_ARGS = {
|
|
|
323
304
|
default: true,
|
|
324
305
|
description: "Emit a <output>.plan.json sidecar (default true; pass --no-sidecar to skip)."
|
|
325
306
|
},
|
|
326
|
-
json:
|
|
327
|
-
type: "boolean",
|
|
328
|
-
description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
|
|
329
|
-
}
|
|
307
|
+
json: JSON_ARG
|
|
330
308
|
};
|
|
331
309
|
const parseWherePredicate = (raw) => {
|
|
332
310
|
let parsed;
|
|
@@ -367,6 +345,7 @@ const bundle = defineBaerlySubcommand({
|
|
|
367
345
|
app: args.app,
|
|
368
346
|
tenant: args.tenant
|
|
369
347
|
});
|
|
348
|
+
assertCollectionArg(args.collection, "baerly export");
|
|
370
349
|
const bucket = await parseBucketUri(args.bucket);
|
|
371
350
|
const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;
|
|
372
351
|
const view = await loadMaterialisedView({
|
|
@@ -419,4 +398,4 @@ const describeNonObject = (v) => {
|
|
|
419
398
|
//#endregion
|
|
420
399
|
export { exportCmd };
|
|
421
400
|
|
|
422
|
-
//# sourceMappingURL=export-
|
|
401
|
+
//# sourceMappingURL=export-DtF5tDIM.js.map
|