@gusto/baerly-storage 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +97 -0
- package/dist/API.md +850 -0
- package/dist/app-config-Cb5dO2s9.d.ts +480 -0
- package/dist/app-config.d.ts +2 -0
- package/dist/app-config.js +8 -0
- package/dist/app-config.js.map +1 -0
- package/dist/auth.d.ts +237 -0
- package/dist/auth.js +1335 -0
- package/dist/auth.js.map +1 -0
- package/dist/baerly.js +761 -0
- package/dist/baerly.js.map +1 -0
- package/dist/bucket-uri-BrDEYvzy.js +4922 -0
- package/dist/bucket-uri-BrDEYvzy.js.map +1 -0
- package/dist/chunk-EAsCxrDo.js +14 -0
- package/dist/client-BLf3Ae5s.d.ts +233 -0
- package/dist/client-react.d.ts +131 -0
- package/dist/client-react.js +559 -0
- package/dist/client-react.js.map +1 -0
- package/dist/client.d.ts +4 -0
- package/dist/client.js +160 -0
- package/dist/client.js.map +1 -0
- package/dist/cloudflare-CINJPKCW.js +911 -0
- package/dist/cloudflare-CINJPKCW.js.map +1 -0
- package/dist/cloudflare.d.ts +211 -0
- package/dist/cloudflare.js +445 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/config-Bsg8wgwo.js +198 -0
- package/dist/config-Bsg8wgwo.js.map +1 -0
- package/dist/context-Oj7ffwD-.js +187 -0
- package/dist/context-Oj7ffwD-.js.map +1 -0
- package/dist/cost-B1WiZxlf.js +203 -0
- package/dist/cost-B1WiZxlf.js.map +1 -0
- package/dist/current-json-BkatBzF7.js +252 -0
- package/dist/current-json-BkatBzF7.js.map +1 -0
- package/dist/db-D62JguBc.d.ts +336 -0
- package/dist/deploy-BB-wqbhf.js +83 -0
- package/dist/deploy-BB-wqbhf.js.map +1 -0
- package/dist/dev-banner-CWHIk8tH.d.ts +26 -0
- package/dist/dev-vite.d.ts +146 -0
- package/dist/dev-vite.js +223 -0
- package/dist/dev-vite.js.map +1 -0
- package/dist/dev.d.ts +3 -0
- package/dist/dev.js +2 -0
- package/dist/doctor-B8h9GCN9.js +331 -0
- package/dist/doctor-B8h9GCN9.js.map +1 -0
- package/dist/dump-BHo_sIMZ.js +116 -0
- package/dist/dump-BHo_sIMZ.js.map +1 -0
- package/dist/errors-DOdL95kK.js +58 -0
- package/dist/errors-DOdL95kK.js.map +1 -0
- package/dist/export-Dz2PZKSR.js +423 -0
- package/dist/export-Dz2PZKSR.js.map +1 -0
- package/dist/fsck-DEz9lyCy.js +293 -0
- package/dist/fsck-DEz9lyCy.js.map +1 -0
- package/dist/http-CjUO1Bec.js +1756 -0
- package/dist/http-CjUO1Bec.js.map +1 -0
- package/dist/http.d.ts +1619 -0
- package/dist/http.js +2 -0
- package/dist/index-BGC-ENnj.d.ts +1065 -0
- package/dist/index-BYv0hb8M.d.ts +1457 -0
- package/dist/index-BquQkhJi.d.ts +112 -0
- package/dist/index-COsQ-Mlz.d.ts +146 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/indexes-BXn7a06a.js +297 -0
- package/dist/indexes-BXn7a06a.js.map +1 -0
- package/dist/indexes-DwOXkn1Y.d.ts +22 -0
- package/dist/inspect-x02aFWnh.js +149 -0
- package/dist/inspect-x02aFWnh.js.map +1 -0
- package/dist/log-walk-DIru96UT.js +260 -0
- package/dist/log-walk-DIru96UT.js.map +1 -0
- package/dist/maintenance-Bn6ul9aV.js +758 -0
- package/dist/maintenance-Bn6ul9aV.js.map +1 -0
- package/dist/maintenance.d.ts +323 -0
- package/dist/maintenance.js +2 -0
- package/dist/node.d.ts +422 -0
- package/dist/node.js +2 -0
- package/dist/normalize-XWY25_sG.js +133 -0
- package/dist/normalize-XWY25_sG.js.map +1 -0
- package/dist/observability-2IDYRuZK.js +2333 -0
- package/dist/observability-2IDYRuZK.js.map +1 -0
- package/dist/observability.d.ts +3 -0
- package/dist/observability.js +3 -0
- package/dist/plan-Cs17VqjU.js +224 -0
- package/dist/plan-Cs17VqjU.js.map +1 -0
- package/dist/query-DcSbFLJt.js +1880 -0
- package/dist/query-DcSbFLJt.js.map +1 -0
- package/dist/rebuild-index-C5gTXryd.js +119 -0
- package/dist/rebuild-index-C5gTXryd.js.map +1 -0
- package/dist/rebuild-index-DwXM0WfA.js +104 -0
- package/dist/rebuild-index-DwXM0WfA.js.map +1 -0
- package/dist/request-BEF_OvMh.js +72 -0
- package/dist/request-BEF_OvMh.js.map +1 -0
- package/dist/restore-CbKVMMpm.js +847 -0
- package/dist/restore-CbKVMMpm.js.map +1 -0
- package/dist/shared-secret-BJdSwpgw.js +71 -0
- package/dist/shared-secret-BJdSwpgw.js.map +1 -0
- package/dist/snapshot-D7C4_FSl.js +71 -0
- package/dist/snapshot-D7C4_FSl.js.map +1 -0
- package/dist/snapshot-z_N9hpTe.js +917 -0
- package/dist/snapshot-z_N9hpTe.js.map +1 -0
- package/dist/src-Chafbw8r.js +522 -0
- package/dist/src-Chafbw8r.js.map +1 -0
- package/dist/src-DyET_VPP.js +6199 -0
- package/dist/src-DyET_VPP.js.map +1 -0
- package/dist/src-n0Te1r98.js +352 -0
- package/dist/src-n0Te1r98.js.map +1 -0
- package/dist/subcommand-BWs6K7zb.js +110 -0
- package/dist/subcommand-BWs6K7zb.js.map +1 -0
- package/dist/usage-RVUQMLop.js +339 -0
- package/dist/usage-RVUQMLop.js.map +1 -0
- package/dist/validate-DhH1lO8I.js +377 -0
- package/dist/validate-DhH1lO8I.js.map +1 -0
- package/dist/wire-izfGZDvr.js +7 -0
- package/dist/wire-izfGZDvr.js.map +1 -0
- package/package.json +189 -0
package/dist/dev-vite.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { n as resolveVerifier, t as Db } from "./src-Chafbw8r.js";
|
|
2
|
+
import { i as printDevBanner, n as ensureTable, t as LocalFsStorage } from "./src-n0Te1r98.js";
|
|
3
|
+
import { n as getRequestListener, t as baerlyNode } from "./src-DyET_VPP.js";
|
|
4
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
5
|
+
//#region packages/dev/src/vite-plugin.ts
|
|
6
|
+
const isV1Path = (url) => url === "/v1" || url.startsWith("/v1/") || url.startsWith("/v1?");
|
|
7
|
+
/**
|
|
8
|
+
* Inject `Authorization: ${value}` into a Node `IncomingMessage` such
|
|
9
|
+
* that BOTH the parsed (`req.headers`) and the wire-form (`req.rawHeaders`)
|
|
10
|
+
* views agree.
|
|
11
|
+
*
|
|
12
|
+
* Why both: `req.headers` is the parsed-and-lowercased JS map most
|
|
13
|
+
* connect-style middleware reads, but Node→Fetch bridges typically
|
|
14
|
+
* rebuild the Fetch `Headers` from `req.rawHeaders` (the original
|
|
15
|
+
* `[name, value, name, value, …]` wire array) to preserve case and
|
|
16
|
+
* multi-value semantics. `@cloudflare/vite-plugin`'s `createHeaders()`
|
|
17
|
+
* does exactly that — so mutating `req.headers` alone silently drops
|
|
18
|
+
* the bearer token when the in-process Worker receives the request.
|
|
19
|
+
* Treat any new injection in this file as obligated to touch both.
|
|
20
|
+
*/
|
|
21
|
+
const injectAuthorizationHeader = (req, value) => {
|
|
22
|
+
req.headers["authorization"] = value;
|
|
23
|
+
const raw = req.rawHeaders;
|
|
24
|
+
if (raw === void 0) return;
|
|
25
|
+
for (let i = 0; i < raw.length; i += 2) if (raw[i].toLowerCase() === "authorization") {
|
|
26
|
+
raw[i + 1] = value;
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
raw.push("Authorization", value);
|
|
30
|
+
};
|
|
31
|
+
const normalisePrefixes = (prefix) => {
|
|
32
|
+
if (prefix === void 0) return ["/v1", "/api"];
|
|
33
|
+
if (typeof prefix === "string") return [prefix];
|
|
34
|
+
return prefix;
|
|
35
|
+
};
|
|
36
|
+
const matchesAnyPrefix = (url, prefixes) => {
|
|
37
|
+
for (const prefix of prefixes) if (url === prefix || url.startsWith(`${prefix}/`) || url.startsWith(`${prefix}?`)) return true;
|
|
38
|
+
return false;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Vite dev plugin: inject `Authorization: Bearer ${secret}` on every
|
|
42
|
+
* request whose URL starts with one of `prefix` (default
|
|
43
|
+
* `["/v1", "/api"]`). Use this to keep the bearer token out of the
|
|
44
|
+
* SPA bundle — the browser sends the request, Vite's middleware adds
|
|
45
|
+
* the header, and the upstream handler (in-process worker or proxied
|
|
46
|
+
* Node server) sees an authenticated request.
|
|
47
|
+
*
|
|
48
|
+
* **Custom Worker routes.** `baerlyWorker` only sees `/v1/*`; the
|
|
49
|
+
* default `prefix` also covers `/api/*` because that's the canonical
|
|
50
|
+
* namespace for the "wrap `baerly.fetch!`" recipe (a server-side
|
|
51
|
+
* endpoint the SPA client can't run on its own, e.g. an endpoint
|
|
52
|
+
* that needs `db.transaction(...)`). If you mount under a different
|
|
53
|
+
* namespace, override:
|
|
54
|
+
*
|
|
55
|
+
* ```ts
|
|
56
|
+
* baerlyDevAuth({ secret, prefix: ["/v1", "/internal"] });
|
|
57
|
+
* ```
|
|
58
|
+
*
|
|
59
|
+
* The bearer is dev-only convenience — production deploys put the
|
|
60
|
+
* SPA, the baerly cascade, AND your custom routes behind the same
|
|
61
|
+
* tenant boundary (CF Access, an upstream JWT, …), so this matters
|
|
62
|
+
* exclusively while `vite dev` is the front door.
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```ts
|
|
66
|
+
* import { baerlyDevAuth, loadDevVars } from "@gusto/baerly-storage/dev/vite";
|
|
67
|
+
*
|
|
68
|
+
* const { SHARED_SECRET } = loadDevVars(".dev.vars", "SHARED_SECRET");
|
|
69
|
+
* export default defineConfig({
|
|
70
|
+
* plugins: [
|
|
71
|
+
* cloudflare(),
|
|
72
|
+
* baerlyDevAuth({ secret: SHARED_SECRET ?? "" }),
|
|
73
|
+
* ],
|
|
74
|
+
* });
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
function baerlyDevAuth(opts) {
|
|
78
|
+
if (opts.secret === "") throw new Error("baerlyDevAuth: secret must be non-empty. Set SHARED_SECRET in .dev.vars / .env.");
|
|
79
|
+
const prefixes = normalisePrefixes(opts.prefix);
|
|
80
|
+
return {
|
|
81
|
+
name: "baerly-dev-auth",
|
|
82
|
+
apply: "serve",
|
|
83
|
+
configureServer(server) {
|
|
84
|
+
server.middlewares.use((req, _res, next) => {
|
|
85
|
+
if (matchesAnyPrefix(req.url ?? "", prefixes)) injectAuthorizationHeader(req, `Bearer ${opts.secret}`);
|
|
86
|
+
next();
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Parse a `.dev.vars` / `.env` file and return the values for the
|
|
93
|
+
* requested `keys`. Supports `KEY=value`, `# comments`, blank lines,
|
|
94
|
+
* and single- or double-quoted values. Keys missing from the file
|
|
95
|
+
* (or the whole file when it does not exist) come back as
|
|
96
|
+
* `undefined` — fall back with `??` at the call site.
|
|
97
|
+
*
|
|
98
|
+
* The return type is `Record<K, string | undefined>` where `K` is
|
|
99
|
+
* the union of literal key names you pass in, so property access
|
|
100
|
+
* works under strict `noPropertyAccessFromIndexSignature`:
|
|
101
|
+
*
|
|
102
|
+
* ```ts
|
|
103
|
+
* const { SHARED_SECRET } = loadDevVars(".dev.vars", "SHARED_SECRET");
|
|
104
|
+
* // ^? string | undefined
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
function loadDevVars(path, ...keys) {
|
|
108
|
+
const out = {};
|
|
109
|
+
for (const key of keys) out[key] = void 0;
|
|
110
|
+
if (!existsSync(path)) return out;
|
|
111
|
+
const wanted = new Set(keys);
|
|
112
|
+
for (const rawLine of readFileSync(path, "utf8").split("\n")) {
|
|
113
|
+
const line = rawLine.trim();
|
|
114
|
+
if (line === "" || line.startsWith("#")) continue;
|
|
115
|
+
const eq = line.indexOf("=");
|
|
116
|
+
if (eq === -1) continue;
|
|
117
|
+
const key = line.slice(0, eq).trim();
|
|
118
|
+
if (!wanted.has(key)) continue;
|
|
119
|
+
let value = line.slice(eq + 1).trim();
|
|
120
|
+
if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
|
|
121
|
+
out[key] = value;
|
|
122
|
+
}
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Resolution order for the in-process verifier (mirrors
|
|
127
|
+
* `baerlyNode` / `baerlyWorker`):
|
|
128
|
+
*
|
|
129
|
+
* 1. `opts.verifier` set → use as-is.
|
|
130
|
+
* 2. else `opts.config.auth === "shared-secret"` → require
|
|
131
|
+
* `opts.secret`; build `sharedSecret({ secret, tenantPrefix:
|
|
132
|
+
* config.tenant })`. Throws `BaerlyError("InvalidConfig", ...)`
|
|
133
|
+
* at Vite startup when `opts.secret` is empty/unset — same
|
|
134
|
+
* locked wording the production adapter would emit.
|
|
135
|
+
* 3. else `opts.config.auth === "none"` → pin every request to
|
|
136
|
+
* `config.tenant`; no header check.
|
|
137
|
+
*
|
|
138
|
+
* Bearer injection on `/v1/*` only fires in branch 2 (and only when
|
|
139
|
+
* branch 1 didn't win) — the dev convenience that lets the SPA call
|
|
140
|
+
* the listener without putting the secret in the browser bundle.
|
|
141
|
+
* Branch 3 leaves the `Authorization` header alone.
|
|
142
|
+
*
|
|
143
|
+
* Verifier resolution happens eagerly at factory time so a misconfig
|
|
144
|
+
* fails Vite startup, not the first `/v1/*` round-trip.
|
|
145
|
+
*/
|
|
146
|
+
function baerlyDev(opts) {
|
|
147
|
+
const verifier = resolveVerifier({
|
|
148
|
+
factoryVerifier: opts.verifier,
|
|
149
|
+
config: opts.config,
|
|
150
|
+
readEnv: (k) => k === "SHARED_SECRET" ? opts.secret : process.env[k]
|
|
151
|
+
});
|
|
152
|
+
const bearerForInjection = opts.verifier === void 0 && opts.config.auth === "shared-secret" ? opts.secret : void 0;
|
|
153
|
+
return {
|
|
154
|
+
name: "baerly-dev",
|
|
155
|
+
apply: "serve",
|
|
156
|
+
configureServer(server) {
|
|
157
|
+
const app = opts.config.app;
|
|
158
|
+
const tenant = opts.config.tenant;
|
|
159
|
+
const tables = Object.keys(opts.config.collections);
|
|
160
|
+
const ready = (async () => {
|
|
161
|
+
const storage = new LocalFsStorage({ root: opts.dataDir });
|
|
162
|
+
for (const table of tables) await ensureTable(storage, {
|
|
163
|
+
app,
|
|
164
|
+
tenant,
|
|
165
|
+
table
|
|
166
|
+
});
|
|
167
|
+
if (opts.seed !== void 0) {
|
|
168
|
+
const db = Db.create({
|
|
169
|
+
storage,
|
|
170
|
+
app,
|
|
171
|
+
tenant,
|
|
172
|
+
config: opts.config
|
|
173
|
+
});
|
|
174
|
+
await opts.seed(db);
|
|
175
|
+
}
|
|
176
|
+
const requestHandler = baerlyNode({
|
|
177
|
+
config: opts.config,
|
|
178
|
+
storage,
|
|
179
|
+
verifier
|
|
180
|
+
}).fetch;
|
|
181
|
+
return getRequestListener(requestHandler);
|
|
182
|
+
})();
|
|
183
|
+
ready.catch((error) => {
|
|
184
|
+
console.error("[baerly-dev] setup failed:", error);
|
|
185
|
+
});
|
|
186
|
+
server.middlewares.use((req, res, next) => {
|
|
187
|
+
const url = req.url;
|
|
188
|
+
if (url === void 0 || !isV1Path(url)) {
|
|
189
|
+
next();
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (bearerForInjection !== void 0) injectAuthorizationHeader(req, `Bearer ${bearerForInjection}`);
|
|
193
|
+
ready.then((listener) => {
|
|
194
|
+
listener(req, res);
|
|
195
|
+
}, (error) => {
|
|
196
|
+
res.statusCode = 503;
|
|
197
|
+
res.setHeader("content-type", "application/json");
|
|
198
|
+
res.end(JSON.stringify({
|
|
199
|
+
error: "baerly-dev setup failed",
|
|
200
|
+
message: String(error)
|
|
201
|
+
}));
|
|
202
|
+
});
|
|
203
|
+
});
|
|
204
|
+
if (opts.banner !== false) server.httpServer?.once("listening", () => {
|
|
205
|
+
const address = server.httpServer?.address();
|
|
206
|
+
const port = typeof address === "object" && address !== null ? address.port : void 0;
|
|
207
|
+
const url = port !== void 0 ? `http://localhost:${port}/` : "http://localhost/";
|
|
208
|
+
printDevBanner({
|
|
209
|
+
name: opts.config.app,
|
|
210
|
+
primaryUrl: {
|
|
211
|
+
label: "App",
|
|
212
|
+
url
|
|
213
|
+
},
|
|
214
|
+
...opts.hints !== void 0 && { hints: opts.hints }
|
|
215
|
+
});
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
//#endregion
|
|
221
|
+
export { baerlyDev, baerlyDevAuth, loadDevVars };
|
|
222
|
+
|
|
223
|
+
//# sourceMappingURL=dev-vite.js.map
|
|
@@ -0,0 +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,WA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|
+
import { a as renderDevLanding, i as DevLandingOptions, n as LocalFsStorageOptions, r as ensureTable, t as LocalFsStorage } from "./index-BquQkhJi.js";
|
|
3
|
+
export { type DevBannerHint, type DevBannerOpts, type DevLandingOptions, LocalFsStorage, LocalFsStorageOptions, ensureTable, printDevBanner, renderDevLanding };
|
package/dist/dev.js
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { a as SHARED_SECRET_MISSING_MESSAGE, t as loadAppConfig } from "./config-Bsg8wgwo.js";
|
|
2
|
+
import { i as isJsonMode, o as BaerlyError, t as color } from "./baerly.js";
|
|
3
|
+
import { t as defineBaerlySubcommand } from "./subcommand-BWs6K7zb.js";
|
|
4
|
+
import { a as defaultRunner, i as parse, n as ensureBindings, r as parseR2Bindings } from "./cloudflare-CINJPKCW.js";
|
|
5
|
+
import { resolve } from "node:path";
|
|
6
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
7
|
+
//#region src/doctor/cloudflare.ts
|
|
8
|
+
/**
|
|
9
|
+
* `baerly doctor --target=cloudflare` — walks the Cloudflare
|
|
10
|
+
* deploy invariants and reports. With `--fix`, remediates what
|
|
11
|
+
* can be safely auto-fixed (R2 bucket creation; secret prompts
|
|
12
|
+
* are still user-driven because `wrangler secret put` reads
|
|
13
|
+
* stdin interactively).
|
|
14
|
+
*
|
|
15
|
+
* Checks (each emitting one {@link DoctorFinding}):
|
|
16
|
+
* 1. `wrangler.jsonc` exists at the package root.
|
|
17
|
+
* 2. Each declared R2 binding exists in CF
|
|
18
|
+
* (`wrangler r2 bucket info`).
|
|
19
|
+
* 3. Each `requiredSecrets` entry is in `wrangler secret list`.
|
|
20
|
+
* 4. If `cloudflareAccess` is set in `baerly.config.ts`,
|
|
21
|
+
* `audienceTag` is 64 lowercase-hex chars and `teamDomain`
|
|
22
|
+
* is non-empty.
|
|
23
|
+
* 5. If `triggers.crons` is empty, warn that the maintenance
|
|
24
|
+
* loop won't run.
|
|
25
|
+
* 6. If `baerly.config.ts:domain` is set but `wrangler.jsonc`
|
|
26
|
+
* doesn't declare a matching `routes` entry, warn.
|
|
27
|
+
*
|
|
28
|
+
* Output is a structured {@link DoctorReport} that
|
|
29
|
+
* `packages/cli/src/doctor.ts` renders as either a checklist
|
|
30
|
+
* (text mode) or a JSON envelope (`--json` mode).
|
|
31
|
+
*/
|
|
32
|
+
const rollupStatus = (findings) => {
|
|
33
|
+
let worst = "ok";
|
|
34
|
+
for (const f of findings) {
|
|
35
|
+
if (f.severity === "error") return "error";
|
|
36
|
+
if (f.severity === "warning") worst = "warning";
|
|
37
|
+
}
|
|
38
|
+
return worst;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Read the declared cron schedule from `wrangler.jsonc`. Returns
|
|
42
|
+
* `[]` when missing — caller treats empty as a warning.
|
|
43
|
+
*/
|
|
44
|
+
const readDeclaredCrons = (wranglerPath) => {
|
|
45
|
+
const text = readFileSync(wranglerPath, "utf8");
|
|
46
|
+
const errors = [];
|
|
47
|
+
const obj = parse(text, errors, {
|
|
48
|
+
allowTrailingComma: true,
|
|
49
|
+
disallowComments: false
|
|
50
|
+
});
|
|
51
|
+
if (errors.length > 0 || obj === void 0) return [];
|
|
52
|
+
const crons = obj.triggers?.crons;
|
|
53
|
+
if (!Array.isArray(crons)) return [];
|
|
54
|
+
return crons.filter((c) => typeof c === "string");
|
|
55
|
+
};
|
|
56
|
+
/** Read declared `routes[].pattern` array from `wrangler.jsonc`. */
|
|
57
|
+
const readDeclaredRoutePatterns = (wranglerPath) => {
|
|
58
|
+
const text = readFileSync(wranglerPath, "utf8");
|
|
59
|
+
const errors = [];
|
|
60
|
+
const obj = parse(text, errors, {
|
|
61
|
+
allowTrailingComma: true,
|
|
62
|
+
disallowComments: false
|
|
63
|
+
});
|
|
64
|
+
if (errors.length > 0 || obj === void 0) return [];
|
|
65
|
+
const routes = obj.routes;
|
|
66
|
+
if (!Array.isArray(routes)) return [];
|
|
67
|
+
return routes.map((r) => r !== null && typeof r === "object" ? r.pattern : void 0).filter((p) => typeof p === "string");
|
|
68
|
+
};
|
|
69
|
+
/** Read declared `vars` keys from `wrangler.jsonc`. */
|
|
70
|
+
const readDeclaredVarKeys = (wranglerPath) => {
|
|
71
|
+
const text = readFileSync(wranglerPath, "utf8");
|
|
72
|
+
const errors = [];
|
|
73
|
+
const obj = parse(text, errors, {
|
|
74
|
+
allowTrailingComma: true,
|
|
75
|
+
disallowComments: false
|
|
76
|
+
});
|
|
77
|
+
if (errors.length > 0 || obj === void 0 || obj.vars === void 0) return [];
|
|
78
|
+
return Object.keys(obj.vars);
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* Walk the Cloudflare deploy invariants. With `opts.fix === true`,
|
|
82
|
+
* remediate the auto-fixable issues (bucket creation). Secret
|
|
83
|
+
* prompts stay user-driven.
|
|
84
|
+
*/
|
|
85
|
+
const doctorCloudflare = async (config, opts = {}) => {
|
|
86
|
+
const repoRoot = opts.cwd ?? config.repoRoot;
|
|
87
|
+
const wranglerPath = resolve(repoRoot, "wrangler.jsonc");
|
|
88
|
+
const findings = [];
|
|
89
|
+
if (!existsSync(wranglerPath)) {
|
|
90
|
+
findings.push({
|
|
91
|
+
severity: "error",
|
|
92
|
+
check: "wrangler.jsonc",
|
|
93
|
+
message: `Expected wrangler.jsonc at the package root: ${wranglerPath}.`,
|
|
94
|
+
fix: "Re-scaffold (npm create baerly@latest) or restore the file from git."
|
|
95
|
+
});
|
|
96
|
+
return {
|
|
97
|
+
findings,
|
|
98
|
+
status: rollupStatus(findings)
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
findings.push({
|
|
102
|
+
severity: "ok",
|
|
103
|
+
check: "wrangler.jsonc",
|
|
104
|
+
message: `${wranglerPath} found.`
|
|
105
|
+
});
|
|
106
|
+
let declared;
|
|
107
|
+
try {
|
|
108
|
+
declared = parseR2Bindings(wranglerPath);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (error instanceof BaerlyError && error.code === "InvalidConfig") {
|
|
111
|
+
findings.push({
|
|
112
|
+
severity: "error",
|
|
113
|
+
check: "wrangler.jsonc.parse",
|
|
114
|
+
message: error.message
|
|
115
|
+
});
|
|
116
|
+
return {
|
|
117
|
+
findings,
|
|
118
|
+
status: rollupStatus(findings)
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
if (opts.fix === true && opts.runner !== void 0) try {
|
|
124
|
+
await ensureBindings(opts.runner, repoRoot, wranglerPath);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
findings.push({
|
|
127
|
+
severity: "error",
|
|
128
|
+
check: "r2.fix",
|
|
129
|
+
message: error instanceof Error ? error.message : "unknown error during ensureBindings"
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
if (opts.runner !== void 0) for (const { bucket_name } of declared) if ((await opts.runner.run("wrangler", [
|
|
133
|
+
"r2",
|
|
134
|
+
"bucket",
|
|
135
|
+
"info",
|
|
136
|
+
bucket_name
|
|
137
|
+
], repoRoot)).code === 0) findings.push({
|
|
138
|
+
severity: "ok",
|
|
139
|
+
check: `r2.${bucket_name}`,
|
|
140
|
+
message: `R2 bucket "${bucket_name}" exists.`
|
|
141
|
+
});
|
|
142
|
+
else findings.push({
|
|
143
|
+
severity: "error",
|
|
144
|
+
check: `r2.${bucket_name}`,
|
|
145
|
+
message: `R2 bucket "${bucket_name}" not found.`,
|
|
146
|
+
fix: `wrangler r2 bucket create ${bucket_name} (or re-run with --fix)`
|
|
147
|
+
});
|
|
148
|
+
else findings.push({
|
|
149
|
+
severity: "info",
|
|
150
|
+
check: "r2.skip",
|
|
151
|
+
message: "no runner supplied; skipped R2 bucket probes."
|
|
152
|
+
});
|
|
153
|
+
const required = config.requiredSecrets ?? ["SHARED_SECRET"];
|
|
154
|
+
let configured = [];
|
|
155
|
+
if (opts.runner !== void 0 && required.length > 0) {
|
|
156
|
+
const r = await opts.runner.run("wrangler", ["secret", "list"], repoRoot);
|
|
157
|
+
if (r.code !== 0) findings.push({
|
|
158
|
+
severity: "warning",
|
|
159
|
+
check: "secrets",
|
|
160
|
+
message: "could not list secrets (wrangler exit non-zero); skipping check."
|
|
161
|
+
});
|
|
162
|
+
else {
|
|
163
|
+
try {
|
|
164
|
+
const parsed = JSON.parse(r.stdout);
|
|
165
|
+
if (Array.isArray(parsed)) configured = parsed.map((s) => s !== null && typeof s === "object" ? s.name : void 0).filter((n) => typeof n === "string");
|
|
166
|
+
} catch {}
|
|
167
|
+
for (const name of required) if (configured.includes(name)) findings.push({
|
|
168
|
+
severity: "ok",
|
|
169
|
+
check: `secret.${name}`,
|
|
170
|
+
message: `secret ${name} is set.`
|
|
171
|
+
});
|
|
172
|
+
else findings.push({
|
|
173
|
+
severity: "warning",
|
|
174
|
+
check: `secret.${name}`,
|
|
175
|
+
message: `secret ${name} is required but unset.`,
|
|
176
|
+
fix: `wrangler secret put ${name}`
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
} else if (required.length > 0) findings.push({
|
|
180
|
+
severity: "info",
|
|
181
|
+
check: "secrets.skip",
|
|
182
|
+
message: "no runner supplied; skipped secret checks."
|
|
183
|
+
});
|
|
184
|
+
if (config.auth === "none") findings.push({
|
|
185
|
+
severity: "warning",
|
|
186
|
+
check: "auth.none-on-deploy",
|
|
187
|
+
message: `baerly.config.ts has auth: "none" and ships to target=${JSON.stringify(config.target)}. Every request will resolve to config.tenant with no header check. Put a network gate in front (CF Access, an upstream JWT, Cloudflare Tunnel, intranet ACL, …) or change \`auth\` to "shared-secret" or pass a custom \`verifier:\` on the adapter factory.`,
|
|
188
|
+
fix: "Edit baerly.config.ts: set `auth: \"shared-secret\"` and run `wrangler secret put SHARED_SECRET`; or keep `auth: \"none\"` and wire CF Access in `wrangler.jsonc:vars` + pass a `verifier:` override in `src/server/index.ts`."
|
|
189
|
+
});
|
|
190
|
+
if (config.auth === "shared-secret" && opts.runner !== void 0) {
|
|
191
|
+
if (!configured.includes("SHARED_SECRET")) findings.push({
|
|
192
|
+
severity: "error",
|
|
193
|
+
check: "auth.shared-secret-missing",
|
|
194
|
+
message: SHARED_SECRET_MISSING_MESSAGE,
|
|
195
|
+
fix: "wrangler secret put SHARED_SECRET (for production) or add SHARED_SECRET=<value> to .dev.vars (for `wrangler dev`)."
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
const varKeys = new Set(readDeclaredVarKeys(wranglerPath));
|
|
199
|
+
if (varKeys.has("CF_ACCESS_TEAM_DOMAIN") && varKeys.has("CF_ACCESS_AUDIENCE_TAG")) findings.push({
|
|
200
|
+
severity: "info",
|
|
201
|
+
check: "auth.cf-access-inert",
|
|
202
|
+
message: `CF Access env vars (CF_ACCESS_TEAM_DOMAIN, CF_ACCESS_AUDIENCE_TAG) are set in ${wranglerPath} but the adapter uses config.auth=${JSON.stringify(config.auth)}. To wire CF Access, pass \`verifier: cloudflareAccess({ teamDomain, audienceTag })\` on the baerlyWorker factory.`
|
|
203
|
+
});
|
|
204
|
+
if (config.cloudflareAccess !== void 0) {
|
|
205
|
+
const { teamDomain, audienceTag } = config.cloudflareAccess;
|
|
206
|
+
if (teamDomain.length === 0) findings.push({
|
|
207
|
+
severity: "error",
|
|
208
|
+
check: "cloudflareAccess.teamDomain",
|
|
209
|
+
message: "cloudflareAccess.teamDomain in baerly.config.ts is empty."
|
|
210
|
+
});
|
|
211
|
+
if (!/^[0-9a-f]{64}$/.test(audienceTag)) findings.push({
|
|
212
|
+
severity: "error",
|
|
213
|
+
check: "cloudflareAccess.audienceTag",
|
|
214
|
+
message: `cloudflareAccess.audienceTag must be 64 lowercase-hex chars (got ${JSON.stringify(audienceTag)}).`,
|
|
215
|
+
fix: "Copy the AUD tag from the Cloudflare Access app's configuration tab."
|
|
216
|
+
});
|
|
217
|
+
else if (teamDomain.length > 0) findings.push({
|
|
218
|
+
severity: "ok",
|
|
219
|
+
check: "cloudflareAccess",
|
|
220
|
+
message: `cloudflareAccess audience tag is well-formed; team domain "${teamDomain}".`
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
const crons = readDeclaredCrons(wranglerPath);
|
|
224
|
+
if (crons.length === 0) findings.push({
|
|
225
|
+
severity: "warning",
|
|
226
|
+
check: "triggers.crons",
|
|
227
|
+
message: "no cron triggers declared; the maintenance loop will not run automatically.",
|
|
228
|
+
fix: `Add "triggers": { "crons": ["* * * * *"] } to ${wranglerPath}.`
|
|
229
|
+
});
|
|
230
|
+
else findings.push({
|
|
231
|
+
severity: "ok",
|
|
232
|
+
check: "triggers.crons",
|
|
233
|
+
message: `cron trigger${crons.length === 1 ? "" : "s"} ${crons.map((c) => JSON.stringify(c)).join(", ")} declared.`
|
|
234
|
+
});
|
|
235
|
+
if (config.domain !== void 0 && config.domain.length > 0) {
|
|
236
|
+
const patterns = readDeclaredRoutePatterns(wranglerPath);
|
|
237
|
+
const expectedPrefix = `${config.domain}/`;
|
|
238
|
+
if (!patterns.some((p) => p === config.domain || p === expectedPrefix || p.startsWith(expectedPrefix))) findings.push({
|
|
239
|
+
severity: "warning",
|
|
240
|
+
check: "routes.domain",
|
|
241
|
+
message: `baerly.config.ts declares domain ${JSON.stringify(config.domain)} but ${wranglerPath} has no matching routes[].pattern.`,
|
|
242
|
+
fix: `Add { "pattern": "${config.domain}/*", "custom_domain": true } to wrangler.jsonc:routes.`
|
|
243
|
+
});
|
|
244
|
+
else findings.push({
|
|
245
|
+
severity: "ok",
|
|
246
|
+
check: "routes.domain",
|
|
247
|
+
message: `routes[].pattern matches domain ${JSON.stringify(config.domain)}.`
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
return {
|
|
251
|
+
findings,
|
|
252
|
+
status: rollupStatus(findings)
|
|
253
|
+
};
|
|
254
|
+
};
|
|
255
|
+
//#endregion
|
|
256
|
+
//#region src/doctor.ts
|
|
257
|
+
const DOCTOR_ARGS = {
|
|
258
|
+
target: {
|
|
259
|
+
type: "string",
|
|
260
|
+
description: "Override `baerly.config.ts:target`. Only \"cloudflare\" supported (Node variants self-validate at scaffold time).",
|
|
261
|
+
valueHint: "cloudflare"
|
|
262
|
+
},
|
|
263
|
+
fix: {
|
|
264
|
+
type: "boolean",
|
|
265
|
+
description: "Remediate auto-fixable findings (R2 bucket creation; secret prompts stay manual)."
|
|
266
|
+
},
|
|
267
|
+
json: {
|
|
268
|
+
type: "boolean",
|
|
269
|
+
description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
const SEVERITY_GLYPH = {
|
|
273
|
+
ok: "✓",
|
|
274
|
+
info: "•",
|
|
275
|
+
warning: "⚠",
|
|
276
|
+
error: "✗"
|
|
277
|
+
};
|
|
278
|
+
const colorize = (severity, glyph) => {
|
|
279
|
+
if (severity === "error") return color.red(glyph);
|
|
280
|
+
if (severity === "warning") return color.yellow(glyph);
|
|
281
|
+
if (severity === "info") return color.dim(glyph);
|
|
282
|
+
return glyph;
|
|
283
|
+
};
|
|
284
|
+
const renderReport = (target, report) => {
|
|
285
|
+
if (isJsonMode()) {
|
|
286
|
+
process.stdout.write(`${JSON.stringify({ result: {
|
|
287
|
+
command: "doctor",
|
|
288
|
+
target,
|
|
289
|
+
...report
|
|
290
|
+
} })}\n`);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
process.stdout.write(`baerly doctor --target=${target}\n\n`);
|
|
294
|
+
let okCount = 0;
|
|
295
|
+
let warningCount = 0;
|
|
296
|
+
let errorCount = 0;
|
|
297
|
+
for (const f of report.findings) {
|
|
298
|
+
const glyph = SEVERITY_GLYPH[f.severity] ?? "•";
|
|
299
|
+
process.stdout.write(` ${colorize(f.severity, glyph)} ${f.message}\n`);
|
|
300
|
+
if (f.fix !== void 0) process.stdout.write(` fix: ${f.fix}\n`);
|
|
301
|
+
if (f.severity === "ok") okCount += 1;
|
|
302
|
+
else if (f.severity === "warning") warningCount += 1;
|
|
303
|
+
else if (f.severity === "error") errorCount += 1;
|
|
304
|
+
}
|
|
305
|
+
process.stdout.write(`\nStatus: ${errorCount} error${errorCount === 1 ? "" : "s"}, ${warningCount} warning${warningCount === 1 ? "" : "s"}, ${okCount} ok.\n`);
|
|
306
|
+
};
|
|
307
|
+
const bundle = defineBaerlySubcommand({
|
|
308
|
+
name: "doctor",
|
|
309
|
+
meta: { description: "Walk the deploy invariants and report findings. Dispatches by baerly.config.ts:target." },
|
|
310
|
+
args: DOCTOR_ARGS,
|
|
311
|
+
handler: async (args) => {
|
|
312
|
+
const config = await loadAppConfig();
|
|
313
|
+
const target = args.target ?? config.target;
|
|
314
|
+
if (target === "cloudflare") {
|
|
315
|
+
const report = await doctorCloudflare(config, {
|
|
316
|
+
runner: defaultRunner(),
|
|
317
|
+
...args.fix === true && { fix: true }
|
|
318
|
+
});
|
|
319
|
+
renderReport(target, report);
|
|
320
|
+
return report.status === "error" ? 2 : 0;
|
|
321
|
+
}
|
|
322
|
+
throw new BaerlyError("InvalidConfig", `baerly doctor: target ${JSON.stringify(target)} has no doctor backend. (Node variants self-validate at scaffold time; the example IS the contract.)`);
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
/** citty `defineCommand` block for `baerly doctor`. */
|
|
326
|
+
const doctor = bundle.cmd;
|
|
327
|
+
bundle.run;
|
|
328
|
+
//#endregion
|
|
329
|
+
export { doctor };
|
|
330
|
+
|
|
331
|
+
//# sourceMappingURL=doctor-B8h9GCN9.js.map
|