@gusto/create-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.
Files changed (88) hide show
  1. package/dist/index.js +2737 -0
  2. package/dist/index.js.map +1 -0
  3. package/dist/templates/addons/docker/.dockerignore +13 -0
  4. package/dist/templates/addons/docker/Dockerfile +65 -0
  5. package/dist/templates/addons/docker/healthcheck.js +15 -0
  6. package/dist/templates/minimal-cloudflare/.baerly/scaffold.json +10 -0
  7. package/dist/templates/minimal-cloudflare/AGENTS.md +556 -0
  8. package/dist/templates/minimal-cloudflare/README.md +169 -0
  9. package/dist/templates/minimal-cloudflare/_gitignore +6 -0
  10. package/dist/templates/minimal-cloudflare/baerly.config.ts +20 -0
  11. package/dist/templates/minimal-cloudflare/index.html +12 -0
  12. package/dist/templates/minimal-cloudflare/package.json +28 -0
  13. package/dist/templates/minimal-cloudflare/pnpm-workspace.yaml +15 -0
  14. package/dist/templates/minimal-cloudflare/src/notes.test.ts +19 -0
  15. package/dist/templates/minimal-cloudflare/src/server/index.ts +11 -0
  16. package/dist/templates/minimal-cloudflare/src/web/main.ts +27 -0
  17. package/dist/templates/minimal-cloudflare/tsconfig.app.json +28 -0
  18. package/dist/templates/minimal-cloudflare/tsconfig.json +9 -0
  19. package/dist/templates/minimal-cloudflare/tsconfig.worker.json +28 -0
  20. package/dist/templates/minimal-cloudflare/types.ts +23 -0
  21. package/dist/templates/minimal-cloudflare/uint8array-base64.d.ts +16 -0
  22. package/dist/templates/minimal-cloudflare/vite.config.ts +6 -0
  23. package/dist/templates/minimal-cloudflare/vitest.config.ts +11 -0
  24. package/dist/templates/minimal-cloudflare/wrangler.jsonc +27 -0
  25. package/dist/templates/minimal-node/.baerly/scaffold.json +13 -0
  26. package/dist/templates/minimal-node/.env.example +14 -0
  27. package/dist/templates/minimal-node/AGENTS.md +488 -0
  28. package/dist/templates/minimal-node/README.md +180 -0
  29. package/dist/templates/minimal-node/_gitignore +7 -0
  30. package/dist/templates/minimal-node/baerly.config.ts +20 -0
  31. package/dist/templates/minimal-node/index.html +12 -0
  32. package/dist/templates/minimal-node/package.json +26 -0
  33. package/dist/templates/minimal-node/pnpm-workspace.yaml +9 -0
  34. package/dist/templates/minimal-node/src/notes.test.ts +19 -0
  35. package/dist/templates/minimal-node/src/server/index.ts +46 -0
  36. package/dist/templates/minimal-node/src/web/main.ts +27 -0
  37. package/dist/templates/minimal-node/tsconfig.app.json +28 -0
  38. package/dist/templates/minimal-node/tsconfig.json +9 -0
  39. package/dist/templates/minimal-node/tsconfig.server.json +28 -0
  40. package/dist/templates/minimal-node/types.ts +23 -0
  41. package/dist/templates/minimal-node/uint8array-base64.d.ts +16 -0
  42. package/dist/templates/minimal-node/vite.config.ts +15 -0
  43. package/dist/templates/minimal-node/vitest.config.ts +12 -0
  44. package/dist/templates/react-cloudflare/.baerly/scaffold.json +10 -0
  45. package/dist/templates/react-cloudflare/AGENTS.md +715 -0
  46. package/dist/templates/react-cloudflare/README.md +115 -0
  47. package/dist/templates/react-cloudflare/_gitignore +6 -0
  48. package/dist/templates/react-cloudflare/baerly.config.ts +37 -0
  49. package/dist/templates/react-cloudflare/index.html +12 -0
  50. package/dist/templates/react-cloudflare/package.json +34 -0
  51. package/dist/templates/react-cloudflare/pnpm-workspace.yaml +15 -0
  52. package/dist/templates/react-cloudflare/src/notes.test.ts +19 -0
  53. package/dist/templates/react-cloudflare/src/server/index.ts +12 -0
  54. package/dist/templates/react-cloudflare/src/web/App.tsx +38 -0
  55. package/dist/templates/react-cloudflare/src/web/NoteList.tsx +93 -0
  56. package/dist/templates/react-cloudflare/src/web/client.ts +13 -0
  57. package/dist/templates/react-cloudflare/src/web/main.tsx +14 -0
  58. package/dist/templates/react-cloudflare/src/web/styles.css +57 -0
  59. package/dist/templates/react-cloudflare/tsconfig.app.json +29 -0
  60. package/dist/templates/react-cloudflare/tsconfig.json +9 -0
  61. package/dist/templates/react-cloudflare/tsconfig.worker.json +28 -0
  62. package/dist/templates/react-cloudflare/uint8array-base64.d.ts +16 -0
  63. package/dist/templates/react-cloudflare/vite.config.ts +7 -0
  64. package/dist/templates/react-cloudflare/vitest.config.ts +11 -0
  65. package/dist/templates/react-cloudflare/wrangler.jsonc +27 -0
  66. package/dist/templates/react-node/.baerly/scaffold.json +13 -0
  67. package/dist/templates/react-node/.env.example +14 -0
  68. package/dist/templates/react-node/AGENTS.md +662 -0
  69. package/dist/templates/react-node/README.md +187 -0
  70. package/dist/templates/react-node/_gitignore +7 -0
  71. package/dist/templates/react-node/baerly.config.ts +37 -0
  72. package/dist/templates/react-node/index.html +12 -0
  73. package/dist/templates/react-node/package.json +32 -0
  74. package/dist/templates/react-node/pnpm-workspace.yaml +9 -0
  75. package/dist/templates/react-node/src/notes.test.ts +19 -0
  76. package/dist/templates/react-node/src/server/index.ts +48 -0
  77. package/dist/templates/react-node/src/web/App.tsx +38 -0
  78. package/dist/templates/react-node/src/web/NoteList.tsx +93 -0
  79. package/dist/templates/react-node/src/web/client.ts +13 -0
  80. package/dist/templates/react-node/src/web/main.tsx +14 -0
  81. package/dist/templates/react-node/src/web/styles.css +57 -0
  82. package/dist/templates/react-node/tsconfig.app.json +29 -0
  83. package/dist/templates/react-node/tsconfig.json +9 -0
  84. package/dist/templates/react-node/tsconfig.server.json +28 -0
  85. package/dist/templates/react-node/uint8array-base64.d.ts +16 -0
  86. package/dist/templates/react-node/vite.config.ts +17 -0
  87. package/dist/templates/react-node/vitest.config.ts +12 -0
  88. package/package.json +41 -0
package/dist/index.js ADDED
@@ -0,0 +1,2737 @@
1
+ #!/usr/bin/env node
2
+ import { defineCommand, runCommand, showUsage } from "citty";
3
+ import pc from "picocolors";
4
+ import { cancel, confirm, intro, isCancel, note, outro, select, text } from "@clack/prompts";
5
+ import { constants, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
6
+ import { basename, dirname, join, resolve, sep } from "node:path";
7
+ import { spawn, spawnSync } from "node:child_process";
8
+ import { fileURLToPath } from "node:url";
9
+ import { access, appendFile, mkdir, readFile, stat, writeFile } from "node:fs/promises";
10
+ import { dirname as dirname$1, normalize, relative } from "node:path/posix";
11
+ //#region src/git.ts
12
+ /**
13
+ * Optional post-scaffold `git init` + initial commit. Mirrors what
14
+ * `create-vite`, `create-next-app`, and Cloudflare's `c3` already do
15
+ * — gives the user (and any subsequent diff-driven workflow, human
16
+ * or agent) a clean baseline-vs-HEAD diff for their first edits.
17
+ *
18
+ * Skips silently when:
19
+ * - `outDir` is already inside a git work tree (nested repos confuse
20
+ * more than they help; the user is scaffolding into an existing
21
+ * workspace and the host repo owns the history).
22
+ * - `git` is not installed (`git --version` fails).
23
+ * - No global `user.name` / `user.email` is configured (the commit
24
+ * would fail anyway; better to skip with a clear warning than to
25
+ * leave a half-initialised `.git/` behind).
26
+ *
27
+ * DI'd via `GitRunner` so tests can stub spawning. The default impl
28
+ * shells out via `spawnSync` (short calls; no need for the async
29
+ * pump). Mirrors the `Installer` DI seam in `install.ts`.
30
+ */
31
+ const defaultGitRunner = { run: (args, cwd) => {
32
+ const res = spawnSync("git", [...args], {
33
+ cwd,
34
+ encoding: "utf8"
35
+ });
36
+ if (res.error !== void 0) return {
37
+ code: 127,
38
+ stdout: "",
39
+ stderr: res.error.message
40
+ };
41
+ return {
42
+ code: res.status ?? 1,
43
+ stdout: res.stdout ?? "",
44
+ stderr: res.stderr ?? ""
45
+ };
46
+ } };
47
+ const trim = (s) => s.trim();
48
+ const isInsideGitWorkTree = (cwd, runner) => {
49
+ const res = runner.run(["rev-parse", "--is-inside-work-tree"], cwd);
50
+ return res.code === 0 && trim(res.stdout) === "true";
51
+ };
52
+ const probeGitVersion = (cwd, runner) => {
53
+ const res = runner.run(["--version"], cwd);
54
+ if (res.code !== 0) return;
55
+ const m = /^git version (\S+)/.exec(trim(res.stdout));
56
+ return m === null ? trim(res.stdout) : m[1];
57
+ };
58
+ const hasIdentity = (cwd, runner) => {
59
+ const name = runner.run(["config", "user.name"], cwd);
60
+ const email = runner.run(["config", "user.email"], cwd);
61
+ return name.code === 0 && email.code === 0 && trim(name.stdout).length > 0 && trim(email.stdout).length > 0;
62
+ };
63
+ const commitMessage = (details, gitVersion) => {
64
+ const pmLine = details.pmVersion === void 0 ? details.pm : `${details.pm}@${details.pmVersion}`;
65
+ return [
66
+ "Initial commit (by create-baerly-storage)",
67
+ "",
68
+ "Details:",
69
+ ` create-baerly-storage = ${details.cliVersion}`,
70
+ ` project name = ${details.appName}`,
71
+ ` target = ${details.target}`,
72
+ ` starter = ${details.starter}`,
73
+ ` package mgr = ${pmLine}`,
74
+ ` git = ${gitVersion}`,
75
+ ""
76
+ ].join("\n");
77
+ };
78
+ /**
79
+ * `git init --initial-branch=main` is rejected by gits older than
80
+ * 2.28 (released 2020). Fall back to plain `git init` followed by
81
+ * `symbolic-ref HEAD refs/heads/main` so the resulting branch is the
82
+ * same regardless of which git the user has on PATH.
83
+ */
84
+ const initWithMainBranch = (outDir, runner) => {
85
+ const first = runner.run(["init", "--initial-branch=main"], outDir);
86
+ if (first.code === 0) return {
87
+ code: 0,
88
+ message: trim(first.stdout)
89
+ };
90
+ const fallback = runner.run(["init"], outDir);
91
+ if (fallback.code !== 0) return {
92
+ code: fallback.code,
93
+ message: trim(fallback.stderr)
94
+ };
95
+ const setBranch = runner.run([
96
+ "symbolic-ref",
97
+ "HEAD",
98
+ "refs/heads/main"
99
+ ], outDir);
100
+ return {
101
+ code: setBranch.code,
102
+ message: trim(setBranch.stderr)
103
+ };
104
+ };
105
+ /**
106
+ * `outDir` must already exist on disk (scaffold has written into it).
107
+ * Probes are all DI'd through the runner, so a test stub controls the
108
+ * whole flow — including the "is this dir inside a repo?" question.
109
+ */
110
+ const initRepoAndCommit = (details, runner = defaultGitRunner) => {
111
+ const gitVersion = probeGitVersion(details.outDir, runner);
112
+ if (gitVersion === void 0) return {
113
+ initialized: false,
114
+ reason: "git-not-available"
115
+ };
116
+ if (isInsideGitWorkTree(details.outDir, runner)) return {
117
+ initialized: false,
118
+ reason: "already-in-repo"
119
+ };
120
+ if (!hasIdentity(details.outDir, runner)) return {
121
+ initialized: false,
122
+ reason: "no-identity"
123
+ };
124
+ const init = initWithMainBranch(details.outDir, runner);
125
+ if (init.code !== 0) return {
126
+ initialized: false,
127
+ reason: "init-failed",
128
+ message: init.message
129
+ };
130
+ const add = runner.run(["add", "."], details.outDir);
131
+ if (add.code !== 0) return {
132
+ initialized: false,
133
+ reason: "add-failed",
134
+ message: trim(add.stderr)
135
+ };
136
+ const commit = runner.run([
137
+ "commit",
138
+ "-m",
139
+ commitMessage(details, gitVersion),
140
+ "--no-verify"
141
+ ], details.outDir);
142
+ if (commit.code !== 0) return {
143
+ initialized: false,
144
+ reason: "commit-failed",
145
+ message: trim(commit.stderr)
146
+ };
147
+ return {
148
+ initialized: true,
149
+ branch: "main"
150
+ };
151
+ };
152
+ //#endregion
153
+ //#region src/prompts.ts
154
+ /**
155
+ * Interactive wizard for `create-baerly-storage`. Invoked only when the
156
+ * process is attached to a real TTY and at least one required arg
157
+ * (`projectName` / `target`) is missing. Non-TTY callers (CI, agents,
158
+ * piped stdin) and `--json` callers retain the flag-driven path and
159
+ * unchanged JSON envelope — see `index.ts`.
160
+ *
161
+ * API surface (`@clack/prompts` v1+): `intro`, `text`, `select`,
162
+ * `confirm`, `outro`, `isCancel`, `cancel`. `isCancel(value)` returns
163
+ * `true` when the user hits Ctrl+C; in that case we call `cancel()`
164
+ * and `process.exit(1)` (same exit code as a user error).
165
+ */
166
+ const TARGETS = [{
167
+ value: "cloudflare",
168
+ label: "Cloudflare Workers",
169
+ hint: "R2 + Workers, deploy via wrangler"
170
+ }, {
171
+ value: "node",
172
+ label: "Node",
173
+ hint: "Any host that runs `node server.js` (Railway, Render, Fly without Docker, Heroku, a VM)"
174
+ }];
175
+ const STARTERS = [{
176
+ value: "minimal",
177
+ label: "Minimal",
178
+ hint: "Server only — no UI framework"
179
+ }, {
180
+ value: "react",
181
+ label: "React",
182
+ hint: "React + Vite SPA over a sample notes collection"
183
+ }];
184
+ const runWizard = async (input, opts = {}) => {
185
+ intro(pc.bold(pc.cyan("create-baerly-storage")));
186
+ const projectName = input.projectName ?? await promptProjectName();
187
+ if (existsSync(resolve(projectName === "." ? process.cwd() : resolve(process.cwd(), projectName), "wrangler.jsonc"))) {
188
+ note("Detected existing Cloudflare Worker — bolting baerly on instead of scaffolding.");
189
+ const install = input.install ?? await promptInstall();
190
+ return {
191
+ mode: "bolt-on",
192
+ projectName,
193
+ tenant: input.tenant ?? "default",
194
+ install
195
+ };
196
+ }
197
+ const target = input.target ?? await promptTarget();
198
+ const starter = input.starter ?? await promptStarter();
199
+ let withAddons;
200
+ if (input.withAddons !== void 0) withAddons = input.withAddons;
201
+ else if (target === "node") withAddons = await promptDocker() ? ["docker"] : [];
202
+ else withAddons = [];
203
+ const install = input.install ?? await promptInstall();
204
+ let git;
205
+ if (input.git !== void 0) git = input.git;
206
+ else git = (opts.gitRunner ?? defaultGitRunner).run(["rev-parse", "--is-inside-work-tree"], process.cwd()).stdout.trim() === "true" ? false : await promptGit();
207
+ return {
208
+ mode: "scaffold",
209
+ projectName,
210
+ target,
211
+ starter,
212
+ withAddons,
213
+ install,
214
+ git
215
+ };
216
+ };
217
+ const promptProjectName = async () => {
218
+ const v = await text({
219
+ message: "Project name (use '.' for current directory)",
220
+ placeholder: "my-app",
221
+ validate: (raw = "") => {
222
+ if (raw.length === 0) return "name must be non-empty";
223
+ if (raw === ".") return;
224
+ if (!/^[a-z0-9][a-z0-9_-]*$/.test(raw)) return "lowercase, alphanumeric + - / _, starting with [a-z0-9] (or '.' for current directory)";
225
+ }
226
+ });
227
+ if (isCancel(v)) {
228
+ cancel("Cancelled.");
229
+ process.exit(1);
230
+ }
231
+ return v;
232
+ };
233
+ const promptTarget = async () => {
234
+ const v = await select({
235
+ message: "Deploy target",
236
+ options: [...TARGETS],
237
+ initialValue: "cloudflare"
238
+ });
239
+ if (isCancel(v)) {
240
+ cancel("Cancelled.");
241
+ process.exit(1);
242
+ }
243
+ return v;
244
+ };
245
+ const promptStarter = async () => {
246
+ const v = await select({
247
+ message: "Starter template",
248
+ options: [...STARTERS],
249
+ initialValue: "minimal"
250
+ });
251
+ if (isCancel(v)) {
252
+ cancel("Cancelled.");
253
+ process.exit(1);
254
+ }
255
+ return v;
256
+ };
257
+ const promptDocker = async () => {
258
+ const v = await confirm({
259
+ message: "Add a production Dockerfile?",
260
+ initialValue: false
261
+ });
262
+ if (isCancel(v)) {
263
+ cancel("Cancelled.");
264
+ process.exit(1);
265
+ }
266
+ return v;
267
+ };
268
+ const promptInstall = async () => {
269
+ const v = await confirm({
270
+ message: "Install dependencies?",
271
+ initialValue: true
272
+ });
273
+ if (isCancel(v)) {
274
+ cancel("Cancelled.");
275
+ process.exit(1);
276
+ }
277
+ return v;
278
+ };
279
+ const promptGit = async () => {
280
+ const v = await confirm({
281
+ message: "Initialise a git repo and create the initial commit?",
282
+ initialValue: true
283
+ });
284
+ if (isCancel(v)) {
285
+ cancel("Cancelled.");
286
+ process.exit(1);
287
+ }
288
+ return v;
289
+ };
290
+ //#endregion
291
+ //#region src/pm-detect.ts
292
+ /**
293
+ * Which package manager invoked us. Read from
294
+ * `npm_config_user_agent` — set by npm/pnpm/yarn when they run
295
+ * their `create` shorthand. Defaults to `"npm"` on any parse
296
+ * failure (most conservative — npm has the widest install base).
297
+ */
298
+ const detectPm = (userAgent = process.env["npm_config_user_agent"]) => {
299
+ if (userAgent === void 0) return "npm";
300
+ const m = /^(npm|pnpm|yarn)\//.exec(userAgent);
301
+ if (m === null) return "npm";
302
+ return m[1];
303
+ };
304
+ /**
305
+ * The install command for the detected PM. Used in the post-
306
+ * scaffold "next steps" output.
307
+ */
308
+ const installCommand = (pm) => {
309
+ if (pm === "npm") return "npm install";
310
+ if (pm === "pnpm") return "pnpm install";
311
+ return "yarn install";
312
+ };
313
+ /**
314
+ * The run-script invocation prefix. `pnpm dev` / `npm run dev` /
315
+ * `yarn dev`. The scaffolded `package.json` scripts assume this
316
+ * shape.
317
+ */
318
+ const runCommand$1 = (pm, script) => {
319
+ if (pm === "pnpm") return `pnpm ${script}`;
320
+ if (pm === "yarn") return `yarn ${script}`;
321
+ return `npm run ${script}`;
322
+ };
323
+ /**
324
+ * Best-effort `<pm> --version` probe. Returns the trimmed version
325
+ * string on success, or `undefined` if the pm binary can't be
326
+ * spawned or returns non-zero. Used by the `git init` commit-message
327
+ * body — a missing pm version is a stylistic loss, not a hard error,
328
+ * so callers should pass the result through unchecked.
329
+ */
330
+ const probePmVersion = (pm) => {
331
+ const res = spawnSync(pm, ["--version"], { encoding: "utf8" });
332
+ if (res.error !== void 0 || res.status !== 0) return;
333
+ const out = (res.stdout ?? "").trim();
334
+ return out.length > 0 ? out : void 0;
335
+ };
336
+ //#endregion
337
+ //#region src/substitute.ts
338
+ /**
339
+ * Rewrite text content (any non-JSON-aware file). Applies sentinel
340
+ * renames longest-first. Unknown `fromKey` values cause the rename to
341
+ * be skipped — that's a scaffolder authoring bug, not a user error,
342
+ * and silent empty-substitution would hide it.
343
+ */
344
+ const substituteText = (text, ctx) => {
345
+ const sorted = ctx.manifest.renames.toSorted((a, b) => b.from.length - a.from.length);
346
+ let out = text;
347
+ for (const r of sorted) {
348
+ if (!Object.hasOwn(ctx.vars, r.fromKey)) continue;
349
+ out = out.replaceAll(r.from, ctx.vars[r.fromKey]);
350
+ }
351
+ return out;
352
+ };
353
+ /**
354
+ * Rewrite a package.json's text content. Applies sentinel renames
355
+ * first (covers the `"name"` field and any other string), then pins
356
+ * `@gusto/baerly-storage` workspace deps to the CLI version, and drops
357
+ * listed devDependencies.
358
+ */
359
+ const substitutePackageJson = (text, ctx) => {
360
+ const renamed = substituteText(text, ctx);
361
+ const pkg = JSON.parse(renamed);
362
+ const pin = `^${ctx.cliVersion}`;
363
+ for (const block of [
364
+ "dependencies",
365
+ "devDependencies",
366
+ "peerDependencies"
367
+ ]) {
368
+ const deps = pkg[block];
369
+ if (deps === void 0) continue;
370
+ for (const [name, value] of Object.entries(deps)) {
371
+ if (value !== "workspace:*") continue;
372
+ if (name === "@gusto/baerly-storage") deps[name] = pin;
373
+ }
374
+ }
375
+ if (pkg.devDependencies !== void 0) {
376
+ for (const drop of ctx.manifest.dropDevDeps) delete pkg.devDependencies[drop];
377
+ if (Object.keys(pkg.devDependencies).length === 0) delete pkg.devDependencies;
378
+ }
379
+ return `${JSON.stringify(pkg, null, 2)}\n`;
380
+ };
381
+ //#endregion
382
+ //#region src/scaffold.ts
383
+ /**
384
+ * Optional add-ons that can be layered on top of a base template
385
+ * (`docker`) or on top of an existing wrangler project in bolt-on
386
+ * mode (`agent-rules`). Adding a new entry here is what makes
387
+ * `--with=<name>` recognised by both the flag parser and the wizard.
388
+ *
389
+ * - `docker` (scaffold-only, `--target=node`): copies the Dockerfile
390
+ * add-on under `templates/addons/docker/` on top of the scaffolded
391
+ * project.
392
+ * - `agent-rules` (bolt-on-only): drops a delimited block telling AI
393
+ * agents that `node_modules/@gusto/baerly-storage/dist/API.md` is the
394
+ * canonical API surface. Scaffolded apps already ship that
395
+ * guidance via the per-template `AGENTS.md`; this closes the gap
396
+ * for users adopting baerly into a repo that didn't start from a
397
+ * `create-baerly-storage` template.
398
+ */
399
+ const KNOWN_ADDONS = ["docker", "agent-rules"];
400
+ /**
401
+ * When `projectName === "."` (scaffold into the current directory),
402
+ * a pre-existing entry whose basename is in this set is always
403
+ * permitted — even if the scaffold also ships a file by the same
404
+ * name (the scaffold overwrites). Other names are checked against
405
+ * the precomputed "would-write" set (see `topLevelOutputs`); only
406
+ * actual collisions fail the guard, so a pre-existing `.npmrc` /
407
+ * `mise.toml` / `.tool-versions` (or any other top-level metadata
408
+ * the user already wrote) coexists with the scaffold.
409
+ */
410
+ const SCAFFOLD_HERE_ALLOWLIST = new Set([
411
+ ".git",
412
+ ".gitignore",
413
+ ".gitattributes",
414
+ "README.md",
415
+ "LICENSE",
416
+ "LICENSE.md",
417
+ "LICENSE.txt"
418
+ ]);
419
+ /**
420
+ * Compute the set of top-level basenames the scaffold will emit
421
+ * into `outDir`. Used by the `inPlace` guard to decide which
422
+ * pre-existing entries actually collide.
423
+ *
424
+ * Mirrors the logic in `walk()`: applies `excludePaths` /
425
+ * `excludeNames`, renames `_gitignore` → `.gitignore`, and folds
426
+ * in the top-level destination of each `manifest.copies` entry.
427
+ * Add-ons layer on top of the base template via the same walker,
428
+ * so their top-level basenames are included here too.
429
+ */
430
+ const topLevelOutputs = (templateDir, manifest, addonDirs) => {
431
+ const excluded = new Set(manifest.excludePaths.map((p) => p.split("/").join(sep)));
432
+ const { literals: excludeLiterals, suffixes: excludeSuffixes } = splitExcludeNames(manifest.excludeNames);
433
+ const matchesExcludeName = (name) => {
434
+ if (excludeLiterals.has(name)) return true;
435
+ for (const suffix of excludeSuffixes) if (name.endsWith(suffix)) return true;
436
+ return false;
437
+ };
438
+ const out = /* @__PURE__ */ new Set();
439
+ const addTopLevel = (sourceDir) => {
440
+ for (const ent of readdirSync(sourceDir)) {
441
+ if (excluded.has(ent) || matchesExcludeName(ent)) continue;
442
+ out.add(ent === "_gitignore" ? ".gitignore" : ent);
443
+ }
444
+ };
445
+ addTopLevel(templateDir);
446
+ for (const addonDir of addonDirs) addTopLevel(addonDir);
447
+ for (const copy of manifest.copies) {
448
+ const firstSeg = copy.to.split("/").join(sep).split(sep)[0];
449
+ if (firstSeg !== void 0 && firstSeg.length > 0) out.add(firstSeg);
450
+ }
451
+ return out;
452
+ };
453
+ const TEXT_EXTS = new Set([
454
+ ".ts",
455
+ ".tsx",
456
+ ".js",
457
+ ".cjs",
458
+ ".json",
459
+ ".jsonc",
460
+ ".md",
461
+ ".toml",
462
+ ".yaml",
463
+ ".yml",
464
+ ".html",
465
+ ".css",
466
+ ".gitignore",
467
+ ".dockerignore",
468
+ ".example",
469
+ ".service"
470
+ ]);
471
+ /**
472
+ * `${target}:${starter}` → example directory name (under `examples/`).
473
+ * Default starter is `"minimal"`. The compound key lets us add richer
474
+ * starters per target without renaming or duplicating maps.
475
+ */
476
+ const STARTER_TO_EXAMPLE = {
477
+ "cloudflare:minimal": "minimal-cloudflare",
478
+ "cloudflare:react": "react-cloudflare",
479
+ "node:minimal": "minimal-node",
480
+ "node:react": "react-node"
481
+ };
482
+ /**
483
+ * Resolve the templates root. In a built CLI, examples are copied
484
+ * to `dist/templates/<name>/` so the binary is self-contained
485
+ * (preserving today's `package.json:files` shape). In dev (running
486
+ * straight from `src/` via Node's strip-types) the same directory
487
+ * doesn't exist, so we fall back to `examples/` three levels up
488
+ * (`src/ → create-baerly-storage/ → packages/ → repo-root`).
489
+ */
490
+ const resolveTemplatesRoot = () => {
491
+ const here = dirname(fileURLToPath(import.meta.url));
492
+ const distSidecar = resolve(here, "templates");
493
+ if (existsSync(distSidecar)) return distSidecar;
494
+ return resolve(here, "..", "..", "..", "examples");
495
+ };
496
+ /**
497
+ * Resolve the add-ons root. In a built CLI, add-on trees are copied
498
+ * to `dist/templates/addons/<name>/` next to the example templates.
499
+ * In dev (running from `src/` via Node's strip-types) they live at
500
+ * `packages/create-baerly-storage/templates/addons/<name>/`, one level up
501
+ * from `src/`.
502
+ */
503
+ const resolveAddonsRoot = () => {
504
+ const here = dirname(fileURLToPath(import.meta.url));
505
+ const distSidecar = resolve(here, "templates", "addons");
506
+ if (existsSync(distSidecar)) return distSidecar;
507
+ return resolve(here, "..", "templates", "addons");
508
+ };
509
+ /**
510
+ * Read the CLI's own package.json:version. Used to rewrite
511
+ * `workspace:*` dep specs to `^X.Y.Z` at copy time, since
512
+ * `create-baerly-storage` ships in the same release train as `@baerly/*`.
513
+ */
514
+ const readCliVersion = () => {
515
+ const pkgPath = resolve(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
516
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
517
+ if (typeof pkg.version !== "string" || pkg.version.length === 0) throw new Error(`create-baerly-storage: could not read version from ${pkgPath}`);
518
+ return pkg.version;
519
+ };
520
+ const DEFAULT_MANIFEST = {
521
+ renames: [],
522
+ excludePaths: [".baerly/scaffold.json"],
523
+ excludeNames: [],
524
+ dropDevDeps: [],
525
+ copies: []
526
+ };
527
+ const loadManifest = (exampleRoot) => {
528
+ const p = join(exampleRoot, ".baerly", "scaffold.json");
529
+ if (!existsSync(p)) return DEFAULT_MANIFEST;
530
+ const raw = JSON.parse(readFileSync(p, "utf8"));
531
+ return {
532
+ renames: raw.renames ?? [],
533
+ excludePaths: raw.excludePaths ?? [".baerly/scaffold.json"],
534
+ excludeNames: raw.excludeNames ?? [],
535
+ dropDevDeps: raw.dropDevDeps ?? [],
536
+ copies: raw.copies ?? []
537
+ };
538
+ };
539
+ /**
540
+ * `excludeNames` supports both literal basenames (`node_modules`)
541
+ * and `*.<ext>` suffix globs (`*.tsbuildinfo`). Split once per
542
+ * scaffold; the walker calls `matchesExcludeName` per entry.
543
+ */
544
+ const splitExcludeNames = (names) => {
545
+ const literals = /* @__PURE__ */ new Set();
546
+ const suffixes = [];
547
+ for (const n of names) if (n.startsWith("*.")) suffixes.push(n.slice(1));
548
+ else literals.add(n);
549
+ return {
550
+ literals,
551
+ suffixes
552
+ };
553
+ };
554
+ /**
555
+ * Walk the source example tree, apply manifest-driven rewrites, and
556
+ * write to `outRoot/<projectName>/`. Returns the absolute output
557
+ * directory and the relative list of files written.
558
+ *
559
+ * Refuses to overwrite an existing non-empty directory — fails
560
+ * fast with a thrown Error. Callers catch and translate to the
561
+ * CLI's exit-code contract.
562
+ */
563
+ const scaffold = async (opts) => {
564
+ if (opts.projectName.length === 0) throw new Error("create-baerly-storage: projectName must be non-empty");
565
+ const inPlace = opts.projectName === ".";
566
+ if (!inPlace && !/^[a-z0-9][a-z0-9_-]*$/.test(opts.projectName)) throw new Error(`create-baerly-storage: projectName must be lowercase, alphanumeric + "_"/"-", starting with [a-z0-9] (got ${JSON.stringify(opts.projectName)})`);
567
+ const pm = opts.pm ?? detectPm();
568
+ const tenant = opts.tenant ?? "default";
569
+ const domain = opts.domain ?? "";
570
+ const templatesRoot = opts.templatesRoot ?? resolveTemplatesRoot();
571
+ const outRoot = opts.outRoot ?? process.cwd();
572
+ const outDir = inPlace ? resolve(outRoot) : resolve(outRoot, opts.projectName);
573
+ const appName = inPlace ? basename(outDir) : opts.projectName;
574
+ if (inPlace && !/^[a-z0-9][a-z0-9_-]*$/.test(appName)) throw new Error(`create-baerly-storage: appName must be lowercase, alphanumeric + "_"/"-", starting with [a-z0-9] (got ${JSON.stringify(appName)}) — derived from current directory ${JSON.stringify(outDir)}`);
575
+ const starter = opts.starter ?? "minimal";
576
+ const exampleName = STARTER_TO_EXAMPLE[`${opts.target}:${starter}`];
577
+ const templateDir = exampleName === void 0 ? "" : join(templatesRoot, exampleName);
578
+ if (exampleName === void 0 || !existsSync(templateDir)) throw new Error(`create-baerly-storage: template not found for target=${opts.target} starter=${starter}`);
579
+ const manifest = loadManifest(templateDir);
580
+ const addons = opts.withAddons ?? [];
581
+ const addonsRoot = addons.length > 0 ? opts.addonsRoot ?? resolveAddonsRoot() : "";
582
+ const addonDirs = [];
583
+ for (const addon of addons) {
584
+ const addonDir = join(addonsRoot, addon);
585
+ if (!existsSync(addonDir)) throw new Error(`create-baerly-storage: add-on directory not found: ${addonDir} (addon=${addon})`);
586
+ addonDirs.push(addonDir);
587
+ }
588
+ if (existsSync(outDir)) {
589
+ const entries = readdirSync(outDir);
590
+ if (inPlace) {
591
+ const wouldWrite = topLevelOutputs(templateDir, manifest, addonDirs);
592
+ const colliding = entries.filter((e) => !SCAFFOLD_HERE_ALLOWLIST.has(e) && wouldWrite.has(e));
593
+ if (colliding.length > 0) throw new Error(`create-baerly-storage: ${outDir} contains files that would be overwritten: ${colliding.join(", ")}. Move or remove these, then re-run.`);
594
+ } else if (entries.length > 0) throw new Error(`create-baerly-storage: ${outDir} exists and is non-empty`);
595
+ }
596
+ const ctx = {
597
+ manifest,
598
+ vars: {
599
+ appName,
600
+ tenant,
601
+ domain,
602
+ pm,
603
+ installCmd: installCommand(pm),
604
+ runDev: runCommand$1(pm, "dev"),
605
+ runTypecheck: runCommand$1(pm, "typecheck")
606
+ },
607
+ cliVersion: readCliVersion()
608
+ };
609
+ const excluded = new Set(manifest.excludePaths.map((p) => p.split("/").join(sep)));
610
+ const isExcluded = (rel) => excluded.has(rel);
611
+ const { literals: excludeLiterals, suffixes: excludeSuffixes } = splitExcludeNames(manifest.excludeNames);
612
+ const matchesExcludeName = (name) => {
613
+ if (excludeLiterals.has(name)) return true;
614
+ for (const suffix of excludeSuffixes) if (name.endsWith(suffix)) return true;
615
+ return false;
616
+ };
617
+ const copyByFrom = new Map(manifest.copies.map((c) => [c.from.split("/").join(sep), c.to.split("/").join(sep)]));
618
+ const filesWritten = [];
619
+ const walk = (sourceDir, rel) => {
620
+ const from = join(sourceDir, rel);
621
+ for (const ent of readdirSync(from)) {
622
+ const fromEnt = join(from, ent);
623
+ const relEnt = rel === "" ? ent : join(rel, ent);
624
+ if (isExcluded(relEnt) || matchesExcludeName(ent)) continue;
625
+ const outName = ent === "_gitignore" ? ".gitignore" : ent;
626
+ const relOut = rel === "" ? outName : join(rel, outName);
627
+ const toEnt = join(outDir, relOut);
628
+ if (statSync(fromEnt).isDirectory()) {
629
+ mkdirSync(toEnt, { recursive: true });
630
+ walk(sourceDir, relEnt);
631
+ } else {
632
+ const ext = ent.includes(".") ? ent.slice(ent.lastIndexOf(".")) : "";
633
+ const isText = TEXT_EXTS.has(ext) || ent === "Dockerfile" || ent === "_gitignore";
634
+ mkdirSync(dirname(toEnt), { recursive: true });
635
+ if (ent === "package.json") writeFileSync(toEnt, substitutePackageJson(readFileSync(fromEnt, "utf8"), ctx));
636
+ else if (isText) writeFileSync(toEnt, substituteText(readFileSync(fromEnt, "utf8"), ctx));
637
+ else writeFileSync(toEnt, readFileSync(fromEnt));
638
+ filesWritten.push(relOut);
639
+ const copyTo = copyByFrom.get(relEnt);
640
+ if (copyTo !== void 0) {
641
+ const copyDest = join(outDir, copyTo);
642
+ mkdirSync(dirname(copyDest), { recursive: true });
643
+ writeFileSync(copyDest, substituteText(readFileSync(fromEnt, "utf8"), ctx));
644
+ filesWritten.push(copyTo);
645
+ }
646
+ }
647
+ }
648
+ };
649
+ walk(templateDir, "");
650
+ for (const addonDir of addonDirs) walk(addonDir, "");
651
+ return {
652
+ outDir,
653
+ filesWritten,
654
+ nextSteps: inPlace ? [installCommand(pm), runCommand$1(pm, "dev")] : [
655
+ `cd ${opts.projectName}`,
656
+ installCommand(pm),
657
+ runCommand$1(pm, "dev")
658
+ ],
659
+ cliVersion: ctx.cliVersion,
660
+ appName
661
+ };
662
+ };
663
+ //#endregion
664
+ //#region ../protocol/src/errors.ts
665
+ /**
666
+ * The single error class thrown by Baerly. Discriminate by `code`, not
667
+ * `instanceof`: the code string survives `JSON.stringify` round-trips
668
+ * across Worker / iframe / postMessage realm boundaries, where each
669
+ * realm has its own `BaerlyError` constructor identity. IDB-restored
670
+ * writes can replay across realms, so `instanceof` would spuriously
671
+ * fail on a structurally-identical error from another realm.
672
+ *
673
+ * @example
674
+ * ```ts
675
+ * try {
676
+ * await db.collection("tickets").insert({ title: "hi" });
677
+ * } catch (err) {
678
+ * if (err instanceof BaerlyError && err.code === "Conflict") {
679
+ * // ... CAS lost; retry
680
+ * }
681
+ * throw err;
682
+ * }
683
+ * ```
684
+ */
685
+ var BaerlyError = class extends Error {
686
+ code;
687
+ cause;
688
+ /**
689
+ * Structured field-path issues, set only when `code === "SchemaError"`.
690
+ * Each entry's `path` is a dotted-key list (e.g. `["assignee", "team"]`
691
+ * or `["items", 3, "qty"]`) that targets the offending field on the
692
+ * input document. `message` is the validator-emitted human string.
693
+ *
694
+ * The HTTP layer's `mapError` renders these into the 400 body via
695
+ * the existing `HttpErrorEnvelope`; older callers that don't know
696
+ * about `issues` see a plain message-only error and stay correct.
697
+ */
698
+ issues;
699
+ /**
700
+ * Raw HTTP status, set only by the client-side wire decoder when
701
+ * inflating an `HttpErrorEnvelope` into this class. Server-side
702
+ * throws never set it (the HTTP layer's `mapError` derives the
703
+ * outbound status from `code`). Useful for diagnostics — e.g. to
704
+ * distinguish 404-as-"no such row" from 404-as-"route not found".
705
+ * Discriminate by `code` for behavior; reach for `status` only when
706
+ * you genuinely need the wire value.
707
+ */
708
+ status;
709
+ constructor(code, message, cause, issues, status) {
710
+ super(message);
711
+ this.name = "BaerlyError";
712
+ this.code = code;
713
+ this.cause = cause;
714
+ if (issues !== void 0) this.issues = issues;
715
+ if (status !== void 0) this.status = status;
716
+ }
717
+ };
718
+ //#endregion
719
+ //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js
720
+ /**
721
+ * Creates a JSON scanner on the given text.
722
+ * If ignoreTrivia is set, whitespaces or comments are ignored.
723
+ */
724
+ function createScanner(text, ignoreTrivia = false) {
725
+ const len = text.length;
726
+ let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
727
+ function scanHexDigits(count, exact) {
728
+ let digits = 0;
729
+ let value = 0;
730
+ while (digits < count || !exact) {
731
+ let ch = text.charCodeAt(pos);
732
+ if (ch >= 48 && ch <= 57) value = value * 16 + ch - 48;
733
+ else if (ch >= 65 && ch <= 70) value = value * 16 + ch - 65 + 10;
734
+ else if (ch >= 97 && ch <= 102) value = value * 16 + ch - 97 + 10;
735
+ else break;
736
+ pos++;
737
+ digits++;
738
+ }
739
+ if (digits < count) value = -1;
740
+ return value;
741
+ }
742
+ function setPosition(newPosition) {
743
+ pos = newPosition;
744
+ value = "";
745
+ tokenOffset = 0;
746
+ token = 16;
747
+ scanError = 0;
748
+ }
749
+ function scanNumber() {
750
+ let start = pos;
751
+ if (text.charCodeAt(pos) === 48) pos++;
752
+ else {
753
+ pos++;
754
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
755
+ }
756
+ if (pos < text.length && text.charCodeAt(pos) === 46) {
757
+ pos++;
758
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
759
+ pos++;
760
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
761
+ } else {
762
+ scanError = 3;
763
+ return text.substring(start, pos);
764
+ }
765
+ }
766
+ let end = pos;
767
+ if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
768
+ pos++;
769
+ if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) pos++;
770
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
771
+ pos++;
772
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
773
+ end = pos;
774
+ } else scanError = 3;
775
+ }
776
+ return text.substring(start, end);
777
+ }
778
+ function scanString() {
779
+ let result = "", start = pos;
780
+ while (true) {
781
+ if (pos >= len) {
782
+ result += text.substring(start, pos);
783
+ scanError = 2;
784
+ break;
785
+ }
786
+ const ch = text.charCodeAt(pos);
787
+ if (ch === 34) {
788
+ result += text.substring(start, pos);
789
+ pos++;
790
+ break;
791
+ }
792
+ if (ch === 92) {
793
+ result += text.substring(start, pos);
794
+ pos++;
795
+ if (pos >= len) {
796
+ scanError = 2;
797
+ break;
798
+ }
799
+ switch (text.charCodeAt(pos++)) {
800
+ case 34:
801
+ result += "\"";
802
+ break;
803
+ case 92:
804
+ result += "\\";
805
+ break;
806
+ case 47:
807
+ result += "/";
808
+ break;
809
+ case 98:
810
+ result += "\b";
811
+ break;
812
+ case 102:
813
+ result += "\f";
814
+ break;
815
+ case 110:
816
+ result += "\n";
817
+ break;
818
+ case 114:
819
+ result += "\r";
820
+ break;
821
+ case 116:
822
+ result += " ";
823
+ break;
824
+ case 117:
825
+ const ch3 = scanHexDigits(4, true);
826
+ if (ch3 >= 0) result += String.fromCharCode(ch3);
827
+ else scanError = 4;
828
+ break;
829
+ default: scanError = 5;
830
+ }
831
+ start = pos;
832
+ continue;
833
+ }
834
+ if (ch >= 0 && ch <= 31) if (isLineBreak(ch)) {
835
+ result += text.substring(start, pos);
836
+ scanError = 2;
837
+ break;
838
+ } else scanError = 6;
839
+ pos++;
840
+ }
841
+ return result;
842
+ }
843
+ function scanNext() {
844
+ value = "";
845
+ scanError = 0;
846
+ tokenOffset = pos;
847
+ lineStartOffset = lineNumber;
848
+ prevTokenLineStartOffset = tokenLineStartOffset;
849
+ if (pos >= len) {
850
+ tokenOffset = len;
851
+ return token = 17;
852
+ }
853
+ let code = text.charCodeAt(pos);
854
+ if (isWhiteSpace(code)) {
855
+ do {
856
+ pos++;
857
+ value += String.fromCharCode(code);
858
+ code = text.charCodeAt(pos);
859
+ } while (isWhiteSpace(code));
860
+ return token = 15;
861
+ }
862
+ if (isLineBreak(code)) {
863
+ pos++;
864
+ value += String.fromCharCode(code);
865
+ if (code === 13 && text.charCodeAt(pos) === 10) {
866
+ pos++;
867
+ value += "\n";
868
+ }
869
+ lineNumber++;
870
+ tokenLineStartOffset = pos;
871
+ return token = 14;
872
+ }
873
+ switch (code) {
874
+ case 123:
875
+ pos++;
876
+ return token = 1;
877
+ case 125:
878
+ pos++;
879
+ return token = 2;
880
+ case 91:
881
+ pos++;
882
+ return token = 3;
883
+ case 93:
884
+ pos++;
885
+ return token = 4;
886
+ case 58:
887
+ pos++;
888
+ return token = 6;
889
+ case 44:
890
+ pos++;
891
+ return token = 5;
892
+ case 34:
893
+ pos++;
894
+ value = scanString();
895
+ return token = 10;
896
+ case 47:
897
+ const start = pos - 1;
898
+ if (text.charCodeAt(pos + 1) === 47) {
899
+ pos += 2;
900
+ while (pos < len) {
901
+ if (isLineBreak(text.charCodeAt(pos))) break;
902
+ pos++;
903
+ }
904
+ value = text.substring(start, pos);
905
+ return token = 12;
906
+ }
907
+ if (text.charCodeAt(pos + 1) === 42) {
908
+ pos += 2;
909
+ const safeLength = len - 1;
910
+ let commentClosed = false;
911
+ while (pos < safeLength) {
912
+ const ch = text.charCodeAt(pos);
913
+ if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
914
+ pos += 2;
915
+ commentClosed = true;
916
+ break;
917
+ }
918
+ pos++;
919
+ if (isLineBreak(ch)) {
920
+ if (ch === 13 && text.charCodeAt(pos) === 10) pos++;
921
+ lineNumber++;
922
+ tokenLineStartOffset = pos;
923
+ }
924
+ }
925
+ if (!commentClosed) {
926
+ pos++;
927
+ scanError = 1;
928
+ }
929
+ value = text.substring(start, pos);
930
+ return token = 13;
931
+ }
932
+ value += String.fromCharCode(code);
933
+ pos++;
934
+ return token = 16;
935
+ case 45:
936
+ value += String.fromCharCode(code);
937
+ pos++;
938
+ if (pos === len || !isDigit(text.charCodeAt(pos))) return token = 16;
939
+ case 48:
940
+ case 49:
941
+ case 50:
942
+ case 51:
943
+ case 52:
944
+ case 53:
945
+ case 54:
946
+ case 55:
947
+ case 56:
948
+ case 57:
949
+ value += scanNumber();
950
+ return token = 11;
951
+ default:
952
+ while (pos < len && isUnknownContentCharacter(code)) {
953
+ pos++;
954
+ code = text.charCodeAt(pos);
955
+ }
956
+ if (tokenOffset !== pos) {
957
+ value = text.substring(tokenOffset, pos);
958
+ switch (value) {
959
+ case "true": return token = 8;
960
+ case "false": return token = 9;
961
+ case "null": return token = 7;
962
+ }
963
+ return token = 16;
964
+ }
965
+ value += String.fromCharCode(code);
966
+ pos++;
967
+ return token = 16;
968
+ }
969
+ }
970
+ function isUnknownContentCharacter(code) {
971
+ if (isWhiteSpace(code) || isLineBreak(code)) return false;
972
+ switch (code) {
973
+ case 125:
974
+ case 93:
975
+ case 123:
976
+ case 91:
977
+ case 34:
978
+ case 58:
979
+ case 44:
980
+ case 47: return false;
981
+ }
982
+ return true;
983
+ }
984
+ function scanNextNonTrivia() {
985
+ let result;
986
+ do
987
+ result = scanNext();
988
+ while (result >= 12 && result <= 15);
989
+ return result;
990
+ }
991
+ return {
992
+ setPosition,
993
+ getPosition: () => pos,
994
+ scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
995
+ getToken: () => token,
996
+ getTokenValue: () => value,
997
+ getTokenOffset: () => tokenOffset,
998
+ getTokenLength: () => pos - tokenOffset,
999
+ getTokenStartLine: () => lineStartOffset,
1000
+ getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,
1001
+ getTokenError: () => scanError
1002
+ };
1003
+ }
1004
+ function isWhiteSpace(ch) {
1005
+ return ch === 32 || ch === 9;
1006
+ }
1007
+ function isLineBreak(ch) {
1008
+ return ch === 10 || ch === 13;
1009
+ }
1010
+ function isDigit(ch) {
1011
+ return ch >= 48 && ch <= 57;
1012
+ }
1013
+ var CharacterCodes;
1014
+ (function(CharacterCodes) {
1015
+ CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
1016
+ CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
1017
+ CharacterCodes[CharacterCodes["space"] = 32] = "space";
1018
+ CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
1019
+ CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
1020
+ CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
1021
+ CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
1022
+ CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
1023
+ CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
1024
+ CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
1025
+ CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
1026
+ CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
1027
+ CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
1028
+ CharacterCodes[CharacterCodes["a"] = 97] = "a";
1029
+ CharacterCodes[CharacterCodes["b"] = 98] = "b";
1030
+ CharacterCodes[CharacterCodes["c"] = 99] = "c";
1031
+ CharacterCodes[CharacterCodes["d"] = 100] = "d";
1032
+ CharacterCodes[CharacterCodes["e"] = 101] = "e";
1033
+ CharacterCodes[CharacterCodes["f"] = 102] = "f";
1034
+ CharacterCodes[CharacterCodes["g"] = 103] = "g";
1035
+ CharacterCodes[CharacterCodes["h"] = 104] = "h";
1036
+ CharacterCodes[CharacterCodes["i"] = 105] = "i";
1037
+ CharacterCodes[CharacterCodes["j"] = 106] = "j";
1038
+ CharacterCodes[CharacterCodes["k"] = 107] = "k";
1039
+ CharacterCodes[CharacterCodes["l"] = 108] = "l";
1040
+ CharacterCodes[CharacterCodes["m"] = 109] = "m";
1041
+ CharacterCodes[CharacterCodes["n"] = 110] = "n";
1042
+ CharacterCodes[CharacterCodes["o"] = 111] = "o";
1043
+ CharacterCodes[CharacterCodes["p"] = 112] = "p";
1044
+ CharacterCodes[CharacterCodes["q"] = 113] = "q";
1045
+ CharacterCodes[CharacterCodes["r"] = 114] = "r";
1046
+ CharacterCodes[CharacterCodes["s"] = 115] = "s";
1047
+ CharacterCodes[CharacterCodes["t"] = 116] = "t";
1048
+ CharacterCodes[CharacterCodes["u"] = 117] = "u";
1049
+ CharacterCodes[CharacterCodes["v"] = 118] = "v";
1050
+ CharacterCodes[CharacterCodes["w"] = 119] = "w";
1051
+ CharacterCodes[CharacterCodes["x"] = 120] = "x";
1052
+ CharacterCodes[CharacterCodes["y"] = 121] = "y";
1053
+ CharacterCodes[CharacterCodes["z"] = 122] = "z";
1054
+ CharacterCodes[CharacterCodes["A"] = 65] = "A";
1055
+ CharacterCodes[CharacterCodes["B"] = 66] = "B";
1056
+ CharacterCodes[CharacterCodes["C"] = 67] = "C";
1057
+ CharacterCodes[CharacterCodes["D"] = 68] = "D";
1058
+ CharacterCodes[CharacterCodes["E"] = 69] = "E";
1059
+ CharacterCodes[CharacterCodes["F"] = 70] = "F";
1060
+ CharacterCodes[CharacterCodes["G"] = 71] = "G";
1061
+ CharacterCodes[CharacterCodes["H"] = 72] = "H";
1062
+ CharacterCodes[CharacterCodes["I"] = 73] = "I";
1063
+ CharacterCodes[CharacterCodes["J"] = 74] = "J";
1064
+ CharacterCodes[CharacterCodes["K"] = 75] = "K";
1065
+ CharacterCodes[CharacterCodes["L"] = 76] = "L";
1066
+ CharacterCodes[CharacterCodes["M"] = 77] = "M";
1067
+ CharacterCodes[CharacterCodes["N"] = 78] = "N";
1068
+ CharacterCodes[CharacterCodes["O"] = 79] = "O";
1069
+ CharacterCodes[CharacterCodes["P"] = 80] = "P";
1070
+ CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
1071
+ CharacterCodes[CharacterCodes["R"] = 82] = "R";
1072
+ CharacterCodes[CharacterCodes["S"] = 83] = "S";
1073
+ CharacterCodes[CharacterCodes["T"] = 84] = "T";
1074
+ CharacterCodes[CharacterCodes["U"] = 85] = "U";
1075
+ CharacterCodes[CharacterCodes["V"] = 86] = "V";
1076
+ CharacterCodes[CharacterCodes["W"] = 87] = "W";
1077
+ CharacterCodes[CharacterCodes["X"] = 88] = "X";
1078
+ CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
1079
+ CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
1080
+ CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
1081
+ CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
1082
+ CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
1083
+ CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
1084
+ CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
1085
+ CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
1086
+ CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
1087
+ CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
1088
+ CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
1089
+ CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
1090
+ CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
1091
+ CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
1092
+ CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
1093
+ CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
1094
+ CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
1095
+ })(CharacterCodes || (CharacterCodes = {}));
1096
+ //#endregion
1097
+ //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js
1098
+ const cachedSpaces = new Array(20).fill(0).map((_, index) => {
1099
+ return " ".repeat(index);
1100
+ });
1101
+ const maxCachedValues = 200;
1102
+ const cachedBreakLinesWithSpaces = {
1103
+ " ": {
1104
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
1105
+ return "\n" + " ".repeat(index);
1106
+ }),
1107
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
1108
+ return "\r" + " ".repeat(index);
1109
+ }),
1110
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
1111
+ return "\r\n" + " ".repeat(index);
1112
+ })
1113
+ },
1114
+ " ": {
1115
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
1116
+ return "\n" + " ".repeat(index);
1117
+ }),
1118
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
1119
+ return "\r" + " ".repeat(index);
1120
+ }),
1121
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
1122
+ return "\r\n" + " ".repeat(index);
1123
+ })
1124
+ }
1125
+ };
1126
+ const supportedEols = [
1127
+ "\n",
1128
+ "\r",
1129
+ "\r\n"
1130
+ ];
1131
+ //#endregion
1132
+ //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/format.js
1133
+ function format(documentText, range, options) {
1134
+ let initialIndentLevel;
1135
+ let formatText;
1136
+ let formatTextStart;
1137
+ let rangeStart;
1138
+ let rangeEnd;
1139
+ if (range) {
1140
+ rangeStart = range.offset;
1141
+ rangeEnd = rangeStart + range.length;
1142
+ formatTextStart = rangeStart;
1143
+ while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) formatTextStart--;
1144
+ let endOffset = rangeEnd;
1145
+ while (endOffset < documentText.length && !isEOL(documentText, endOffset)) endOffset++;
1146
+ formatText = documentText.substring(formatTextStart, endOffset);
1147
+ initialIndentLevel = computeIndentLevel(formatText, options);
1148
+ } else {
1149
+ formatText = documentText;
1150
+ initialIndentLevel = 0;
1151
+ formatTextStart = 0;
1152
+ rangeStart = 0;
1153
+ rangeEnd = documentText.length;
1154
+ }
1155
+ const eol = getEOL(options, documentText);
1156
+ const eolFastPathSupported = supportedEols.includes(eol);
1157
+ let numberLineBreaks = 0;
1158
+ let indentLevel = 0;
1159
+ let indentValue;
1160
+ if (options.insertSpaces) indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4);
1161
+ else indentValue = " ";
1162
+ const indentType = indentValue === " " ? " " : " ";
1163
+ let scanner = createScanner(formatText, false);
1164
+ let hasError = false;
1165
+ function newLinesAndIndent() {
1166
+ if (numberLineBreaks > 1) return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);
1167
+ const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);
1168
+ if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) return eol + repeat(indentValue, initialIndentLevel + indentLevel);
1169
+ if (amountOfSpaces <= 0) return eol;
1170
+ return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];
1171
+ }
1172
+ function scanNext() {
1173
+ let token = scanner.scan();
1174
+ numberLineBreaks = 0;
1175
+ while (token === 15 || token === 14) {
1176
+ if (token === 14 && options.keepLines) numberLineBreaks += 1;
1177
+ else if (token === 14) numberLineBreaks = 1;
1178
+ token = scanner.scan();
1179
+ }
1180
+ hasError = token === 16 || scanner.getTokenError() !== 0;
1181
+ return token;
1182
+ }
1183
+ const editOperations = [];
1184
+ function addEdit(text, startOffset, endOffset) {
1185
+ if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) editOperations.push({
1186
+ offset: startOffset,
1187
+ length: endOffset - startOffset,
1188
+ content: text
1189
+ });
1190
+ }
1191
+ let firstToken = scanNext();
1192
+ if (options.keepLines && numberLineBreaks > 0) addEdit(repeat(eol, numberLineBreaks), 0, 0);
1193
+ if (firstToken !== 17) {
1194
+ let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
1195
+ addEdit(indentValue.length * initialIndentLevel < 20 && options.insertSpaces ? cachedSpaces[indentValue.length * initialIndentLevel] : repeat(indentValue, initialIndentLevel), formatTextStart, firstTokenStart);
1196
+ }
1197
+ while (firstToken !== 17) {
1198
+ let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
1199
+ let secondToken = scanNext();
1200
+ let replaceContent = "";
1201
+ let needsLineBreak = false;
1202
+ while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
1203
+ let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
1204
+ addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);
1205
+ firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
1206
+ needsLineBreak = secondToken === 12;
1207
+ replaceContent = needsLineBreak ? newLinesAndIndent() : "";
1208
+ secondToken = scanNext();
1209
+ }
1210
+ if (secondToken === 2) {
1211
+ if (firstToken !== 1) indentLevel--;
1212
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) replaceContent = newLinesAndIndent();
1213
+ else if (options.keepLines) replaceContent = cachedSpaces[1];
1214
+ } else if (secondToken === 4) {
1215
+ if (firstToken !== 3) indentLevel--;
1216
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) replaceContent = newLinesAndIndent();
1217
+ else if (options.keepLines) replaceContent = cachedSpaces[1];
1218
+ } else {
1219
+ switch (firstToken) {
1220
+ case 3:
1221
+ case 1:
1222
+ indentLevel++;
1223
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) replaceContent = newLinesAndIndent();
1224
+ else replaceContent = cachedSpaces[1];
1225
+ break;
1226
+ case 5:
1227
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) replaceContent = newLinesAndIndent();
1228
+ else replaceContent = cachedSpaces[1];
1229
+ break;
1230
+ case 12:
1231
+ replaceContent = newLinesAndIndent();
1232
+ break;
1233
+ case 13:
1234
+ if (numberLineBreaks > 0) replaceContent = newLinesAndIndent();
1235
+ else if (!needsLineBreak) replaceContent = cachedSpaces[1];
1236
+ break;
1237
+ case 6:
1238
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
1239
+ else if (!needsLineBreak) replaceContent = cachedSpaces[1];
1240
+ break;
1241
+ case 10:
1242
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
1243
+ else if (secondToken === 6 && !needsLineBreak) replaceContent = "";
1244
+ break;
1245
+ case 7:
1246
+ case 8:
1247
+ case 9:
1248
+ case 11:
1249
+ case 2:
1250
+ case 4:
1251
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
1252
+ else if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) replaceContent = cachedSpaces[1];
1253
+ else if (secondToken !== 5 && secondToken !== 17) hasError = true;
1254
+ break;
1255
+ case 16:
1256
+ hasError = true;
1257
+ break;
1258
+ }
1259
+ if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) replaceContent = newLinesAndIndent();
1260
+ }
1261
+ if (secondToken === 17) if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
1262
+ else replaceContent = options.insertFinalNewline ? eol : "";
1263
+ const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
1264
+ addEdit(replaceContent, firstTokenEnd, secondTokenStart);
1265
+ firstToken = secondToken;
1266
+ }
1267
+ return editOperations;
1268
+ }
1269
+ function repeat(s, count) {
1270
+ let result = "";
1271
+ for (let i = 0; i < count; i++) result += s;
1272
+ return result;
1273
+ }
1274
+ function computeIndentLevel(content, options) {
1275
+ let i = 0;
1276
+ let nChars = 0;
1277
+ const tabSize = options.tabSize || 4;
1278
+ while (i < content.length) {
1279
+ let ch = content.charAt(i);
1280
+ if (ch === cachedSpaces[1]) nChars++;
1281
+ else if (ch === " ") nChars += tabSize;
1282
+ else break;
1283
+ i++;
1284
+ }
1285
+ return Math.floor(nChars / tabSize);
1286
+ }
1287
+ function getEOL(options, text) {
1288
+ for (let i = 0; i < text.length; i++) {
1289
+ const ch = text.charAt(i);
1290
+ if (ch === "\r") {
1291
+ if (i + 1 < text.length && text.charAt(i + 1) === "\n") return "\r\n";
1292
+ return "\r";
1293
+ } else if (ch === "\n") return "\n";
1294
+ }
1295
+ return options && options.eol || "\n";
1296
+ }
1297
+ function isEOL(text, offset) {
1298
+ return "\r\n".indexOf(text.charAt(offset)) !== -1;
1299
+ }
1300
+ //#endregion
1301
+ //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js
1302
+ var ParseOptions;
1303
+ (function(ParseOptions) {
1304
+ ParseOptions.DEFAULT = { allowTrailingComma: false };
1305
+ })(ParseOptions || (ParseOptions = {}));
1306
+ /**
1307
+ * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
1308
+ * Therefore always check the errors list to find out if the input was valid.
1309
+ */
1310
+ function parse$1(text, errors = [], options = ParseOptions.DEFAULT) {
1311
+ let currentProperty = null;
1312
+ let currentParent = [];
1313
+ const previousParents = [];
1314
+ function onValue(value) {
1315
+ if (Array.isArray(currentParent)) currentParent.push(value);
1316
+ else if (currentProperty !== null) currentParent[currentProperty] = value;
1317
+ }
1318
+ visit(text, {
1319
+ onObjectBegin: () => {
1320
+ const object = {};
1321
+ onValue(object);
1322
+ previousParents.push(currentParent);
1323
+ currentParent = object;
1324
+ currentProperty = null;
1325
+ },
1326
+ onObjectProperty: (name) => {
1327
+ currentProperty = name;
1328
+ },
1329
+ onObjectEnd: () => {
1330
+ currentParent = previousParents.pop();
1331
+ },
1332
+ onArrayBegin: () => {
1333
+ const array = [];
1334
+ onValue(array);
1335
+ previousParents.push(currentParent);
1336
+ currentParent = array;
1337
+ currentProperty = null;
1338
+ },
1339
+ onArrayEnd: () => {
1340
+ currentParent = previousParents.pop();
1341
+ },
1342
+ onLiteralValue: onValue,
1343
+ onError: (error, offset, length) => {
1344
+ errors.push({
1345
+ error,
1346
+ offset,
1347
+ length
1348
+ });
1349
+ }
1350
+ }, options);
1351
+ return currentParent[0];
1352
+ }
1353
+ /**
1354
+ * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
1355
+ */
1356
+ function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {
1357
+ let currentParent = {
1358
+ type: "array",
1359
+ offset: -1,
1360
+ length: -1,
1361
+ children: [],
1362
+ parent: void 0
1363
+ };
1364
+ function ensurePropertyComplete(endOffset) {
1365
+ if (currentParent.type === "property") {
1366
+ currentParent.length = endOffset - currentParent.offset;
1367
+ currentParent = currentParent.parent;
1368
+ }
1369
+ }
1370
+ function onValue(valueNode) {
1371
+ currentParent.children.push(valueNode);
1372
+ return valueNode;
1373
+ }
1374
+ visit(text, {
1375
+ onObjectBegin: (offset) => {
1376
+ currentParent = onValue({
1377
+ type: "object",
1378
+ offset,
1379
+ length: -1,
1380
+ parent: currentParent,
1381
+ children: []
1382
+ });
1383
+ },
1384
+ onObjectProperty: (name, offset, length) => {
1385
+ currentParent = onValue({
1386
+ type: "property",
1387
+ offset,
1388
+ length: -1,
1389
+ parent: currentParent,
1390
+ children: []
1391
+ });
1392
+ currentParent.children.push({
1393
+ type: "string",
1394
+ value: name,
1395
+ offset,
1396
+ length,
1397
+ parent: currentParent
1398
+ });
1399
+ },
1400
+ onObjectEnd: (offset, length) => {
1401
+ ensurePropertyComplete(offset + length);
1402
+ currentParent.length = offset + length - currentParent.offset;
1403
+ currentParent = currentParent.parent;
1404
+ ensurePropertyComplete(offset + length);
1405
+ },
1406
+ onArrayBegin: (offset, length) => {
1407
+ currentParent = onValue({
1408
+ type: "array",
1409
+ offset,
1410
+ length: -1,
1411
+ parent: currentParent,
1412
+ children: []
1413
+ });
1414
+ },
1415
+ onArrayEnd: (offset, length) => {
1416
+ currentParent.length = offset + length - currentParent.offset;
1417
+ currentParent = currentParent.parent;
1418
+ ensurePropertyComplete(offset + length);
1419
+ },
1420
+ onLiteralValue: (value, offset, length) => {
1421
+ onValue({
1422
+ type: getNodeType(value),
1423
+ offset,
1424
+ length,
1425
+ parent: currentParent,
1426
+ value
1427
+ });
1428
+ ensurePropertyComplete(offset + length);
1429
+ },
1430
+ onSeparator: (sep, offset, length) => {
1431
+ if (currentParent.type === "property") {
1432
+ if (sep === ":") currentParent.colonOffset = offset;
1433
+ else if (sep === ",") ensurePropertyComplete(offset);
1434
+ }
1435
+ },
1436
+ onError: (error, offset, length) => {
1437
+ errors.push({
1438
+ error,
1439
+ offset,
1440
+ length
1441
+ });
1442
+ }
1443
+ }, options);
1444
+ const result = currentParent.children[0];
1445
+ if (result) delete result.parent;
1446
+ return result;
1447
+ }
1448
+ /**
1449
+ * Finds the node at the given path in a JSON DOM.
1450
+ */
1451
+ function findNodeAtLocation(root, path) {
1452
+ if (!root) return;
1453
+ let node = root;
1454
+ for (let segment of path) if (typeof segment === "string") {
1455
+ if (node.type !== "object" || !Array.isArray(node.children)) return;
1456
+ let found = false;
1457
+ for (const propertyNode of node.children) if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
1458
+ node = propertyNode.children[1];
1459
+ found = true;
1460
+ break;
1461
+ }
1462
+ if (!found) return;
1463
+ } else {
1464
+ const index = segment;
1465
+ if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) return;
1466
+ node = node.children[index];
1467
+ }
1468
+ return node;
1469
+ }
1470
+ /**
1471
+ * Parses the given text and invokes the visitor functions for each object, array and literal reached.
1472
+ */
1473
+ function visit(text, visitor, options = ParseOptions.DEFAULT) {
1474
+ const _scanner = createScanner(text, false);
1475
+ const _jsonPath = [];
1476
+ let suppressedCallbacks = 0;
1477
+ function toNoArgVisit(visitFunction) {
1478
+ return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
1479
+ }
1480
+ function toOneArgVisit(visitFunction) {
1481
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
1482
+ }
1483
+ function toOneArgVisitWithPath(visitFunction) {
1484
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
1485
+ }
1486
+ function toBeginVisit(visitFunction) {
1487
+ return visitFunction ? () => {
1488
+ if (suppressedCallbacks > 0) suppressedCallbacks++;
1489
+ else if (visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) === false) suppressedCallbacks = 1;
1490
+ } : () => true;
1491
+ }
1492
+ function toEndVisit(visitFunction) {
1493
+ return visitFunction ? () => {
1494
+ if (suppressedCallbacks > 0) suppressedCallbacks--;
1495
+ if (suppressedCallbacks === 0) visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());
1496
+ } : () => true;
1497
+ }
1498
+ const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
1499
+ const disallowComments = options && options.disallowComments;
1500
+ const allowTrailingComma = options && options.allowTrailingComma;
1501
+ function scanNext() {
1502
+ while (true) {
1503
+ const token = _scanner.scan();
1504
+ switch (_scanner.getTokenError()) {
1505
+ case 4:
1506
+ handleError(14);
1507
+ break;
1508
+ case 5:
1509
+ handleError(15);
1510
+ break;
1511
+ case 3:
1512
+ handleError(13);
1513
+ break;
1514
+ case 1:
1515
+ if (!disallowComments) handleError(11);
1516
+ break;
1517
+ case 2:
1518
+ handleError(12);
1519
+ break;
1520
+ case 6:
1521
+ handleError(16);
1522
+ break;
1523
+ }
1524
+ switch (token) {
1525
+ case 12:
1526
+ case 13:
1527
+ if (disallowComments) handleError(10);
1528
+ else onComment();
1529
+ break;
1530
+ case 16:
1531
+ handleError(1);
1532
+ break;
1533
+ case 15:
1534
+ case 14: break;
1535
+ default: return token;
1536
+ }
1537
+ }
1538
+ }
1539
+ function handleError(error, skipUntilAfter = [], skipUntil = []) {
1540
+ onError(error);
1541
+ if (skipUntilAfter.length + skipUntil.length > 0) {
1542
+ let token = _scanner.getToken();
1543
+ while (token !== 17) {
1544
+ if (skipUntilAfter.indexOf(token) !== -1) {
1545
+ scanNext();
1546
+ break;
1547
+ } else if (skipUntil.indexOf(token) !== -1) break;
1548
+ token = scanNext();
1549
+ }
1550
+ }
1551
+ }
1552
+ function parseString(isValue) {
1553
+ const value = _scanner.getTokenValue();
1554
+ if (isValue) onLiteralValue(value);
1555
+ else {
1556
+ onObjectProperty(value);
1557
+ _jsonPath.push(value);
1558
+ }
1559
+ scanNext();
1560
+ return true;
1561
+ }
1562
+ function parseLiteral() {
1563
+ switch (_scanner.getToken()) {
1564
+ case 11:
1565
+ const tokenValue = _scanner.getTokenValue();
1566
+ let value = Number(tokenValue);
1567
+ if (isNaN(value)) {
1568
+ handleError(2);
1569
+ value = 0;
1570
+ }
1571
+ onLiteralValue(value);
1572
+ break;
1573
+ case 7:
1574
+ onLiteralValue(null);
1575
+ break;
1576
+ case 8:
1577
+ onLiteralValue(true);
1578
+ break;
1579
+ case 9:
1580
+ onLiteralValue(false);
1581
+ break;
1582
+ default: return false;
1583
+ }
1584
+ scanNext();
1585
+ return true;
1586
+ }
1587
+ function parseProperty() {
1588
+ if (_scanner.getToken() !== 10) {
1589
+ handleError(3, [], [2, 5]);
1590
+ return false;
1591
+ }
1592
+ parseString(false);
1593
+ if (_scanner.getToken() === 6) {
1594
+ onSeparator(":");
1595
+ scanNext();
1596
+ if (!parseValue()) handleError(4, [], [2, 5]);
1597
+ } else handleError(5, [], [2, 5]);
1598
+ _jsonPath.pop();
1599
+ return true;
1600
+ }
1601
+ function parseObject() {
1602
+ onObjectBegin();
1603
+ scanNext();
1604
+ let needsComma = false;
1605
+ while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
1606
+ if (_scanner.getToken() === 5) {
1607
+ if (!needsComma) handleError(4, [], []);
1608
+ onSeparator(",");
1609
+ scanNext();
1610
+ if (_scanner.getToken() === 2 && allowTrailingComma) break;
1611
+ } else if (needsComma) handleError(6, [], []);
1612
+ if (!parseProperty()) handleError(4, [], [2, 5]);
1613
+ needsComma = true;
1614
+ }
1615
+ onObjectEnd();
1616
+ if (_scanner.getToken() !== 2) handleError(7, [2], []);
1617
+ else scanNext();
1618
+ return true;
1619
+ }
1620
+ function parseArray() {
1621
+ onArrayBegin();
1622
+ scanNext();
1623
+ let isFirstElement = true;
1624
+ let needsComma = false;
1625
+ while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
1626
+ if (_scanner.getToken() === 5) {
1627
+ if (!needsComma) handleError(4, [], []);
1628
+ onSeparator(",");
1629
+ scanNext();
1630
+ if (_scanner.getToken() === 4 && allowTrailingComma) break;
1631
+ } else if (needsComma) handleError(6, [], []);
1632
+ if (isFirstElement) {
1633
+ _jsonPath.push(0);
1634
+ isFirstElement = false;
1635
+ } else _jsonPath[_jsonPath.length - 1]++;
1636
+ if (!parseValue()) handleError(4, [], [4, 5]);
1637
+ needsComma = true;
1638
+ }
1639
+ onArrayEnd();
1640
+ if (!isFirstElement) _jsonPath.pop();
1641
+ if (_scanner.getToken() !== 4) handleError(8, [4], []);
1642
+ else scanNext();
1643
+ return true;
1644
+ }
1645
+ function parseValue() {
1646
+ switch (_scanner.getToken()) {
1647
+ case 3: return parseArray();
1648
+ case 1: return parseObject();
1649
+ case 10: return parseString(true);
1650
+ default: return parseLiteral();
1651
+ }
1652
+ }
1653
+ scanNext();
1654
+ if (_scanner.getToken() === 17) {
1655
+ if (options.allowEmptyContent) return true;
1656
+ handleError(4, [], []);
1657
+ return false;
1658
+ }
1659
+ if (!parseValue()) {
1660
+ handleError(4, [], []);
1661
+ return false;
1662
+ }
1663
+ if (_scanner.getToken() !== 17) handleError(9, [], []);
1664
+ return true;
1665
+ }
1666
+ function getNodeType(value) {
1667
+ switch (typeof value) {
1668
+ case "boolean": return "boolean";
1669
+ case "number": return "number";
1670
+ case "string": return "string";
1671
+ case "object":
1672
+ if (!value) return "null";
1673
+ else if (Array.isArray(value)) return "array";
1674
+ return "object";
1675
+ default: return "null";
1676
+ }
1677
+ }
1678
+ //#endregion
1679
+ //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/edit.js
1680
+ function setProperty(text, originalPath, value, options) {
1681
+ const path = originalPath.slice();
1682
+ const root = parseTree(text, []);
1683
+ let parent = void 0;
1684
+ let lastSegment = void 0;
1685
+ while (path.length > 0) {
1686
+ lastSegment = path.pop();
1687
+ parent = findNodeAtLocation(root, path);
1688
+ if (parent === void 0 && value !== void 0) if (typeof lastSegment === "string") value = { [lastSegment]: value };
1689
+ else value = [value];
1690
+ else break;
1691
+ }
1692
+ if (!parent) {
1693
+ if (value === void 0) throw new Error("Can not delete in empty document");
1694
+ return withFormatting(text, {
1695
+ offset: root ? root.offset : 0,
1696
+ length: root ? root.length : 0,
1697
+ content: JSON.stringify(value)
1698
+ }, options);
1699
+ } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
1700
+ const existing = findNodeAtLocation(parent, [lastSegment]);
1701
+ if (existing !== void 0) if (value === void 0) {
1702
+ if (!existing.parent) throw new Error("Malformed AST");
1703
+ const propertyIndex = parent.children.indexOf(existing.parent);
1704
+ let removeBegin;
1705
+ let removeEnd = existing.parent.offset + existing.parent.length;
1706
+ if (propertyIndex > 0) {
1707
+ let previous = parent.children[propertyIndex - 1];
1708
+ removeBegin = previous.offset + previous.length;
1709
+ } else {
1710
+ removeBegin = parent.offset + 1;
1711
+ if (parent.children.length > 1) removeEnd = parent.children[1].offset;
1712
+ }
1713
+ return withFormatting(text, {
1714
+ offset: removeBegin,
1715
+ length: removeEnd - removeBegin,
1716
+ content: ""
1717
+ }, options);
1718
+ } else return withFormatting(text, {
1719
+ offset: existing.offset,
1720
+ length: existing.length,
1721
+ content: JSON.stringify(value)
1722
+ }, options);
1723
+ else {
1724
+ if (value === void 0) return [];
1725
+ const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
1726
+ const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p) => p.children[0].value)) : parent.children.length;
1727
+ let edit;
1728
+ if (index > 0) {
1729
+ let previous = parent.children[index - 1];
1730
+ edit = {
1731
+ offset: previous.offset + previous.length,
1732
+ length: 0,
1733
+ content: "," + newProperty
1734
+ };
1735
+ } else if (parent.children.length === 0) edit = {
1736
+ offset: parent.offset + 1,
1737
+ length: 0,
1738
+ content: newProperty
1739
+ };
1740
+ else edit = {
1741
+ offset: parent.offset + 1,
1742
+ length: 0,
1743
+ content: newProperty + ","
1744
+ };
1745
+ return withFormatting(text, edit, options);
1746
+ }
1747
+ } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
1748
+ const insertIndex = lastSegment;
1749
+ if (insertIndex === -1) {
1750
+ const newProperty = `${JSON.stringify(value)}`;
1751
+ let edit;
1752
+ if (parent.children.length === 0) edit = {
1753
+ offset: parent.offset + 1,
1754
+ length: 0,
1755
+ content: newProperty
1756
+ };
1757
+ else {
1758
+ const previous = parent.children[parent.children.length - 1];
1759
+ edit = {
1760
+ offset: previous.offset + previous.length,
1761
+ length: 0,
1762
+ content: "," + newProperty
1763
+ };
1764
+ }
1765
+ return withFormatting(text, edit, options);
1766
+ } else if (value === void 0 && parent.children.length >= 0) {
1767
+ const removalIndex = lastSegment;
1768
+ const toRemove = parent.children[removalIndex];
1769
+ let edit;
1770
+ if (parent.children.length === 1) edit = {
1771
+ offset: parent.offset + 1,
1772
+ length: parent.length - 2,
1773
+ content: ""
1774
+ };
1775
+ else if (parent.children.length - 1 === removalIndex) {
1776
+ let previous = parent.children[removalIndex - 1];
1777
+ let offset = previous.offset + previous.length;
1778
+ edit = {
1779
+ offset,
1780
+ length: parent.offset + parent.length - 2 - offset,
1781
+ content: ""
1782
+ };
1783
+ } else edit = {
1784
+ offset: toRemove.offset,
1785
+ length: parent.children[removalIndex + 1].offset - toRemove.offset,
1786
+ content: ""
1787
+ };
1788
+ return withFormatting(text, edit, options);
1789
+ } else if (value !== void 0) {
1790
+ let edit;
1791
+ const newProperty = `${JSON.stringify(value)}`;
1792
+ if (!options.isArrayInsertion && parent.children.length > lastSegment) {
1793
+ const toModify = parent.children[lastSegment];
1794
+ edit = {
1795
+ offset: toModify.offset,
1796
+ length: toModify.length,
1797
+ content: newProperty
1798
+ };
1799
+ } else if (parent.children.length === 0 || lastSegment === 0) edit = {
1800
+ offset: parent.offset + 1,
1801
+ length: 0,
1802
+ content: parent.children.length === 0 ? newProperty : newProperty + ","
1803
+ };
1804
+ else {
1805
+ const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
1806
+ const previous = parent.children[index - 1];
1807
+ edit = {
1808
+ offset: previous.offset + previous.length,
1809
+ length: 0,
1810
+ content: "," + newProperty
1811
+ };
1812
+ }
1813
+ return withFormatting(text, edit, options);
1814
+ } else throw new Error(`Can not ${value === void 0 ? "remove" : options.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`);
1815
+ } else throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
1816
+ }
1817
+ function withFormatting(text, edit, options) {
1818
+ if (!options.formattingOptions) return [edit];
1819
+ let newText = applyEdit(text, edit);
1820
+ let begin = edit.offset;
1821
+ let end = edit.offset + edit.content.length;
1822
+ if (edit.length === 0 || edit.content.length === 0) {
1823
+ while (begin > 0 && !isEOL(newText, begin - 1)) begin--;
1824
+ while (end < newText.length && !isEOL(newText, end)) end++;
1825
+ }
1826
+ const edits = format(newText, {
1827
+ offset: begin,
1828
+ length: end - begin
1829
+ }, {
1830
+ ...options.formattingOptions,
1831
+ keepLines: false
1832
+ });
1833
+ for (let i = edits.length - 1; i >= 0; i--) {
1834
+ const edit = edits[i];
1835
+ newText = applyEdit(newText, edit);
1836
+ begin = Math.min(begin, edit.offset);
1837
+ end = Math.max(end, edit.offset + edit.length);
1838
+ end += edit.content.length - edit.length;
1839
+ }
1840
+ const editLength = text.length - (newText.length - end) - begin;
1841
+ return [{
1842
+ offset: begin,
1843
+ length: editLength,
1844
+ content: newText.substring(begin, end)
1845
+ }];
1846
+ }
1847
+ function applyEdit(text, edit) {
1848
+ return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
1849
+ }
1850
+ //#endregion
1851
+ //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js
1852
+ var ScanError;
1853
+ (function(ScanError) {
1854
+ ScanError[ScanError["None"] = 0] = "None";
1855
+ ScanError[ScanError["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
1856
+ ScanError[ScanError["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
1857
+ ScanError[ScanError["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
1858
+ ScanError[ScanError["InvalidUnicode"] = 4] = "InvalidUnicode";
1859
+ ScanError[ScanError["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
1860
+ ScanError[ScanError["InvalidCharacter"] = 6] = "InvalidCharacter";
1861
+ })(ScanError || (ScanError = {}));
1862
+ var SyntaxKind;
1863
+ (function(SyntaxKind) {
1864
+ SyntaxKind[SyntaxKind["OpenBraceToken"] = 1] = "OpenBraceToken";
1865
+ SyntaxKind[SyntaxKind["CloseBraceToken"] = 2] = "CloseBraceToken";
1866
+ SyntaxKind[SyntaxKind["OpenBracketToken"] = 3] = "OpenBracketToken";
1867
+ SyntaxKind[SyntaxKind["CloseBracketToken"] = 4] = "CloseBracketToken";
1868
+ SyntaxKind[SyntaxKind["CommaToken"] = 5] = "CommaToken";
1869
+ SyntaxKind[SyntaxKind["ColonToken"] = 6] = "ColonToken";
1870
+ SyntaxKind[SyntaxKind["NullKeyword"] = 7] = "NullKeyword";
1871
+ SyntaxKind[SyntaxKind["TrueKeyword"] = 8] = "TrueKeyword";
1872
+ SyntaxKind[SyntaxKind["FalseKeyword"] = 9] = "FalseKeyword";
1873
+ SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
1874
+ SyntaxKind[SyntaxKind["NumericLiteral"] = 11] = "NumericLiteral";
1875
+ SyntaxKind[SyntaxKind["LineCommentTrivia"] = 12] = "LineCommentTrivia";
1876
+ SyntaxKind[SyntaxKind["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
1877
+ SyntaxKind[SyntaxKind["LineBreakTrivia"] = 14] = "LineBreakTrivia";
1878
+ SyntaxKind[SyntaxKind["Trivia"] = 15] = "Trivia";
1879
+ SyntaxKind[SyntaxKind["Unknown"] = 16] = "Unknown";
1880
+ SyntaxKind[SyntaxKind["EOF"] = 17] = "EOF";
1881
+ })(SyntaxKind || (SyntaxKind = {}));
1882
+ /**
1883
+ * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
1884
+ * Therefore, always check the errors list to find out if the input was valid.
1885
+ */
1886
+ const parse = parse$1;
1887
+ var ParseErrorCode;
1888
+ (function(ParseErrorCode) {
1889
+ ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 1] = "InvalidSymbol";
1890
+ ParseErrorCode[ParseErrorCode["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
1891
+ ParseErrorCode[ParseErrorCode["PropertyNameExpected"] = 3] = "PropertyNameExpected";
1892
+ ParseErrorCode[ParseErrorCode["ValueExpected"] = 4] = "ValueExpected";
1893
+ ParseErrorCode[ParseErrorCode["ColonExpected"] = 5] = "ColonExpected";
1894
+ ParseErrorCode[ParseErrorCode["CommaExpected"] = 6] = "CommaExpected";
1895
+ ParseErrorCode[ParseErrorCode["CloseBraceExpected"] = 7] = "CloseBraceExpected";
1896
+ ParseErrorCode[ParseErrorCode["CloseBracketExpected"] = 8] = "CloseBracketExpected";
1897
+ ParseErrorCode[ParseErrorCode["EndOfFileExpected"] = 9] = "EndOfFileExpected";
1898
+ ParseErrorCode[ParseErrorCode["InvalidCommentToken"] = 10] = "InvalidCommentToken";
1899
+ ParseErrorCode[ParseErrorCode["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
1900
+ ParseErrorCode[ParseErrorCode["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
1901
+ ParseErrorCode[ParseErrorCode["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
1902
+ ParseErrorCode[ParseErrorCode["InvalidUnicode"] = 14] = "InvalidUnicode";
1903
+ ParseErrorCode[ParseErrorCode["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
1904
+ ParseErrorCode[ParseErrorCode["InvalidCharacter"] = 16] = "InvalidCharacter";
1905
+ })(ParseErrorCode || (ParseErrorCode = {}));
1906
+ /**
1907
+ * Computes the edit operations needed to modify a value in the JSON document.
1908
+ *
1909
+ * @param documentText The input text
1910
+ * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
1911
+ * If the path points to an non-existing property or item, it will be created.
1912
+ * @param value The new value for the specified property or item. If the value is undefined,
1913
+ * the property or item will be removed.
1914
+ * @param options Options
1915
+ * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.
1916
+ * To apply the edit operations to the input, use {@linkcode applyEdits}.
1917
+ */
1918
+ function modify(text, path, value, options) {
1919
+ return setProperty(text, path, value, options);
1920
+ }
1921
+ /**
1922
+ * Applies edits to an input string.
1923
+ * @param text The input text
1924
+ * @param edits Edit operations following the format described in {@linkcode EditResult}.
1925
+ * @returns The text with the applied edits.
1926
+ * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.
1927
+ */
1928
+ function applyEdits(text, edits) {
1929
+ let sortedEdits = edits.slice(0).sort((a, b) => {
1930
+ const diff = a.offset - b.offset;
1931
+ if (diff === 0) return a.length - b.length;
1932
+ return diff;
1933
+ });
1934
+ let lastModifiedOffset = text.length;
1935
+ for (let i = sortedEdits.length - 1; i >= 0; i--) {
1936
+ let e = sortedEdits[i];
1937
+ if (e.offset + e.length <= lastModifiedOffset) text = applyEdit(text, e);
1938
+ else throw new Error("Overlapping edit");
1939
+ lastModifiedOffset = e.offset;
1940
+ }
1941
+ return text;
1942
+ }
1943
+ //#endregion
1944
+ //#region ../cli/src/wrangler-patch.ts
1945
+ /**
1946
+ * Surgical wrangler.jsonc helpers used by `baerly deploy` and the
1947
+ * `@gusto/create-baerly-storage` bolt-on flow. All functions are pure (no I/O) —
1948
+ * callers do the file read/write. Built on `jsonc-parser` so
1949
+ * comments and trailing commas survive round-trips.
1950
+ */
1951
+ /**
1952
+ * Parse declared `r2_buckets[]` from a `wrangler.jsonc` source
1953
+ * string. Tolerates comments + trailing commas via `jsonc-parser`.
1954
+ *
1955
+ * @throws BaerlyError code="InvalidConfig" — malformed JSONC or
1956
+ * invalid `r2_buckets` shape.
1957
+ */
1958
+ const parseR2Bindings = (source) => {
1959
+ const errors = [];
1960
+ const obj = parse(source, errors, {
1961
+ allowTrailingComma: true,
1962
+ disallowComments: false
1963
+ });
1964
+ if (errors.length > 0) throw new BaerlyError("InvalidConfig", `wrangler.jsonc parse error at offset ${errors[0].offset}: ${errors[0].error}`);
1965
+ if (obj === void 0 || typeof obj !== "object") throw new BaerlyError("InvalidConfig", `wrangler.jsonc did not parse to an object`);
1966
+ const buckets = obj.r2_buckets;
1967
+ if (buckets === void 0) return [];
1968
+ if (!Array.isArray(buckets)) throw new BaerlyError("InvalidConfig", `wrangler.jsonc: r2_buckets must be an array`);
1969
+ const out = [];
1970
+ for (const b of buckets) {
1971
+ if (b === null || typeof b !== "object") throw new BaerlyError("InvalidConfig", `wrangler.jsonc: r2_buckets entry must be an object`);
1972
+ const entry = b;
1973
+ if (typeof entry.binding !== "string" || entry.binding.length === 0) throw new BaerlyError("InvalidConfig", `wrangler.jsonc: r2_buckets[].binding must be a non-empty string`);
1974
+ if (typeof entry.bucket_name !== "string" || entry.bucket_name.length === 0) throw new BaerlyError("InvalidConfig", `wrangler.jsonc: r2_buckets[].bucket_name must be a non-empty string`);
1975
+ out.push({
1976
+ binding: entry.binding,
1977
+ bucket_name: entry.bucket_name
1978
+ });
1979
+ }
1980
+ return out;
1981
+ };
1982
+ /**
1983
+ * Read the `name` field from a `wrangler.jsonc` source string.
1984
+ * Returns `undefined` on malformed JSONC or when the field is absent.
1985
+ * Never throws — designed for caller-friendly inspection.
1986
+ */
1987
+ const readWranglerName = (source) => {
1988
+ const errors = [];
1989
+ const parsed = parse(source, errors, { allowTrailingComma: true });
1990
+ if (errors.length > 0 || typeof parsed?.name !== "string") return;
1991
+ return parsed.name;
1992
+ };
1993
+ /**
1994
+ * Read the `main` field from a `wrangler.jsonc` source string.
1995
+ * Returns `undefined` on malformed JSONC or when the field is absent.
1996
+ * Never throws — designed for caller-friendly inspection.
1997
+ */
1998
+ const readWranglerMain = (source) => {
1999
+ const errors = [];
2000
+ const parsed = parse(source, errors, { allowTrailingComma: true });
2001
+ if (errors.length > 0 || typeof parsed?.main !== "string") return;
2002
+ return parsed.main;
2003
+ };
2004
+ const detectIndent = (source) => {
2005
+ for (const line of source.split("\n")) {
2006
+ if (line.length === 0 || line.startsWith("{") || line.startsWith("}")) continue;
2007
+ const first = line.charAt(0);
2008
+ if (first === " ") return {
2009
+ insertSpaces: false,
2010
+ tabSize: 2,
2011
+ eol: "\n"
2012
+ };
2013
+ if (first === " ") {
2014
+ let count = 0;
2015
+ while (count < line.length && line.charAt(count) === " ") count += 1;
2016
+ return {
2017
+ insertSpaces: true,
2018
+ tabSize: count,
2019
+ eol: "\n"
2020
+ };
2021
+ }
2022
+ }
2023
+ return {
2024
+ insertSpaces: true,
2025
+ tabSize: 2,
2026
+ eol: "\n"
2027
+ };
2028
+ };
2029
+ /**
2030
+ * Idempotently patch a `wrangler.jsonc` source string:
2031
+ *
2032
+ * - Appends an R2 binding to `r2_buckets[]` unless an entry with
2033
+ * the same `binding` name already exists (user wins).
2034
+ * - Merges `vars` keys, skipping any key already present (user wins).
2035
+ *
2036
+ * Comments and trailing commas are preserved by `jsonc-parser`.
2037
+ *
2038
+ * @throws BaerlyError code="InvalidConfig" — malformed JSONC or
2039
+ * invalid `r2_buckets` / `vars` shape.
2040
+ */
2041
+ const patchWranglerJsonc = (source, binding, vars) => {
2042
+ const existingBindings = parseR2Bindings(source);
2043
+ const rawVars = parse(source, [], { allowTrailingComma: true })?.vars;
2044
+ if (rawVars !== void 0) {
2045
+ if (typeof rawVars !== "object" || rawVars === null || Array.isArray(rawVars)) throw new BaerlyError("InvalidConfig", "wrangler.jsonc: vars must be an object");
2046
+ }
2047
+ const existingVars = rawVars ?? {};
2048
+ const formattingOptions = detectIndent(source);
2049
+ const changes = [];
2050
+ let text = source;
2051
+ if (!existingBindings.some((b) => b.binding === binding.binding)) {
2052
+ const edits = modify(text, ["r2_buckets", -1], binding, { formattingOptions });
2053
+ text = applyEdits(text, edits);
2054
+ changes.push(`added r2 binding ${binding.binding} → ${binding.bucket_name}`);
2055
+ }
2056
+ const addedVarKeys = [];
2057
+ for (const [key, value] of Object.entries(vars)) if (!(key in existingVars)) {
2058
+ const edits = modify(text, ["vars", key], value, { formattingOptions });
2059
+ text = applyEdits(text, edits);
2060
+ addedVarKeys.push(key);
2061
+ }
2062
+ if (addedVarKeys.length > 0) changes.push(`merged vars: ${addedVarKeys.join(", ")}`);
2063
+ return {
2064
+ text,
2065
+ changes
2066
+ };
2067
+ };
2068
+ //#endregion
2069
+ //#region src/init-snippet.ts
2070
+ /**
2071
+ * Render the worker-entry paste-string that the create-baerly-storage
2072
+ * bolt-on flow prints after patching `wrangler.jsonc`. The user
2073
+ * copies this verbatim into the path declared in
2074
+ * `wrangler.jsonc:main`, replacing the stock `wrangler create`
2075
+ * hello world. baerly never writes user code (Convex-style:
2076
+ * structured config is fair game; the worker entry is sacred).
2077
+ */
2078
+ /**
2079
+ * Compute the JS import path from `wranglerMain` to `./baerly.config.ts`.
2080
+ * Both inputs are repo-root-relative; the output is the import string
2081
+ * the snippet emits. Always carries the explicit `.ts` extension
2082
+ * (project convention; see CLAUDE.md "Imports are relative, with
2083
+ * explicit `.ts`/`.tsx` extensions").
2084
+ */
2085
+ const computeConfigImportPath = (wranglerMain) => {
2086
+ const fromDir = dirname$1(normalize(wranglerMain));
2087
+ if (fromDir === "." || fromDir === "") return "./baerly.config.ts";
2088
+ const rel = relative(fromDir, "baerly.config.ts");
2089
+ return rel.startsWith("..") ? rel : `./${rel}`;
2090
+ };
2091
+ const renderWorkerEntrySnippet = (ctx) => {
2092
+ return `import { baerlyWorker, type BaerlyEnv } from "@gusto/baerly-storage/cloudflare";
2093
+ import { sharedSecret } from "@gusto/baerly-storage/auth";
2094
+ import config from "${computeConfigImportPath(ctx.wranglerMain)}";
2095
+
2096
+ interface AppEnv extends BaerlyEnv {
2097
+ readonly TENANT: string;
2098
+ readonly SHARED_SECRET: string;
2099
+ }
2100
+
2101
+ export default baerlyWorker<AppEnv>((env) => ({
2102
+ verifier: sharedSecret({ secret: env.SHARED_SECRET, tenantPrefix: env.TENANT }),
2103
+ config,
2104
+ }));
2105
+ `;
2106
+ };
2107
+ //#endregion
2108
+ //#region src/install.ts
2109
+ /**
2110
+ * `Installer` DI seam for the post-scaffold install step. The default
2111
+ * implementation shells out to the detected package manager via
2112
+ * `node:child_process.spawn` with `stdio: "inherit"` so the user sees
2113
+ * the pm's own progress (pnpm's spinner, npm's bars). Tests inject a
2114
+ * mock to avoid spawning real installs.
2115
+ *
2116
+ * Mirrors the shape of `packages/cli/src/runner.ts:ProcessRunner` —
2117
+ * intentionally not imported cross-package because `create-baerly-storage`
2118
+ * has its own dependency surface (no `@baerly/cli` dep).
2119
+ */
2120
+ const defaultInstaller = { run: (pm, cwd) => new Promise((resolve, reject) => {
2121
+ const child = spawn(pm, ["install"], {
2122
+ cwd,
2123
+ stdio: "inherit"
2124
+ });
2125
+ child.on("error", reject);
2126
+ child.on("close", (code) => resolve({ code: code ?? 1 }));
2127
+ }) };
2128
+ //#endregion
2129
+ //#region src/agent-rules.ts
2130
+ /**
2131
+ * The `--with=agent-rules` bolt-on add-on. Drops a delimited block
2132
+ * that tells the user's AI agent (Claude / Cursor / Copilot) that
2133
+ * `node_modules/@gusto/baerly-storage/dist/API.md` is the canonical API
2134
+ * surface and that the patterns those agents' training data is
2135
+ * densest with (Postgres/Prisma/Drizzle, Mongo, Firebase) don't
2136
+ * apply.
2137
+ *
2138
+ * Scaffolded apps already get this via the per-template `AGENTS.md`
2139
+ * shipped by `scaffold()`. This module is for the bolt-on path —
2140
+ * `pnpm create baerly .` in an existing wrangler project — where no
2141
+ * template file is copied.
2142
+ *
2143
+ * Target detection (first match wins):
2144
+ * 1. `.claude/rules/` exists → write `.claude/rules/baerly.md`.
2145
+ * 2. `AGENTS.md` exists at repo root → append a delimited block.
2146
+ * 3. `.cursor/rules/` exists → write `.cursor/rules/baerly.md`.
2147
+ * 4. None of the above → create `AGENTS.md` at repo root.
2148
+ *
2149
+ * Idempotent: a second run with the same target replaces the
2150
+ * delimited block in place rather than duplicating it.
2151
+ */
2152
+ const BLOCK_START = "<!-- baerly:start -->";
2153
+ const BLOCK_END = "<!-- baerly:end -->";
2154
+ /**
2155
+ * The literal block content emitted into the chosen target file.
2156
+ * Wording mirrors the per-template `AGENTS.md` preamble shipped by
2157
+ * `scaffold()` so an agent dropped into a bolt-on repo gets the
2158
+ * same orientation a scaffolded-app agent gets.
2159
+ *
2160
+ * Wrapped in `BLOCK_START` / `BLOCK_END` so a second run replaces
2161
+ * in place.
2162
+ */
2163
+ const AGENT_RULES_BLOCK = `${BLOCK_START}
2164
+ ## @gusto/baerly-storage
2165
+
2166
+ This repo uses @gusto/baerly-storage. Before writing or modifying storage code:
2167
+
2168
+ - Read **\`node_modules/@gusto/baerly-storage/dist/API.md\`** — public-API
2169
+ quickref. Every method, every error code, every example. If a
2170
+ pattern you want to use is not here, it does not exist in baerly.
2171
+ - Type contracts live in \`node_modules/@gusto/baerly-storage/dist/*.d.ts\`.
2172
+ The whole API is \`Db\`, \`Collection<T>\`, \`Query<T>\`, and \`Predicate<T>\`.
2173
+
2174
+ Anti-patterns that compile but are wrong:
2175
+
2176
+ - \`db.collection(...).insertOne(...)\` — no such method. Use
2177
+ \`db.collection(...).insert(...)\`.
2178
+ - \`.useIndex("name")\` — does not exist. The query planner picks
2179
+ indexes automatically from registered \`IndexDefinition\`s.
2180
+ - \`z.string().nullable()\` — \`DocumentValue\` excludes \`null\`. Use
2181
+ \`.optional()\`; \`null\` in update patches is the RFC 7396 deletion
2182
+ sentinel.
2183
+ - SQL strings, raw \`WHERE\` clauses — the API is a method-chain
2184
+ only: \`.where({ field: value }).all()\` (object literal, equality)
2185
+ or \`.where(q => q.gte("field", n)).all()\` (callback DSL,
2186
+ operators: \`eq\` / \`gt\` / \`gte\` / \`lt\` / \`lte\` / \`in\`).
2187
+ - \`.all()\` on a hot path — page or cursor-iterate. \`.all()\` is for
2188
+ bounded result sets only.
2189
+ ${BLOCK_END}
2190
+ `;
2191
+ const fileExists$1 = async (path) => {
2192
+ try {
2193
+ await access(path, constants.F_OK);
2194
+ return true;
2195
+ } catch {
2196
+ return false;
2197
+ }
2198
+ };
2199
+ const dirExists = async (path) => {
2200
+ try {
2201
+ return (await stat(path)).isDirectory();
2202
+ } catch {
2203
+ return false;
2204
+ }
2205
+ };
2206
+ const detectAgentRulesTarget = async (outDir) => {
2207
+ if (await dirExists(resolve(outDir, ".claude", "rules"))) return {
2208
+ path: resolve(outDir, ".claude", "rules", "baerly.md"),
2209
+ mode: "dedicated"
2210
+ };
2211
+ if (await fileExists$1(resolve(outDir, "AGENTS.md"))) return {
2212
+ path: resolve(outDir, "AGENTS.md"),
2213
+ mode: "shared"
2214
+ };
2215
+ if (await dirExists(resolve(outDir, ".cursor", "rules"))) return {
2216
+ path: resolve(outDir, ".cursor", "rules", "baerly.md"),
2217
+ mode: "dedicated"
2218
+ };
2219
+ return {
2220
+ path: resolve(outDir, "AGENTS.md"),
2221
+ mode: "shared"
2222
+ };
2223
+ };
2224
+ /**
2225
+ * `Indices` plural intentionally: returns the indices of the first
2226
+ * START and the matching END so callers can slice surrounding
2227
+ * content cleanly. Returns null when the file has no managed block.
2228
+ */
2229
+ const findBlockRange = (text) => {
2230
+ const start = text.indexOf(BLOCK_START);
2231
+ if (start === -1) return null;
2232
+ const endTag = text.indexOf(BLOCK_END, start + 21);
2233
+ if (endTag === -1) return null;
2234
+ return {
2235
+ start,
2236
+ end: endTag + 19
2237
+ };
2238
+ };
2239
+ const writeAgentRulesBlock = async (outDir) => {
2240
+ const target = await detectAgentRulesTarget(outDir);
2241
+ if (target.mode === "dedicated") {
2242
+ await mkdir(dirname(target.path), { recursive: true });
2243
+ const existed = await fileExists$1(target.path);
2244
+ await writeFile(target.path, AGENT_RULES_BLOCK, "utf8");
2245
+ return {
2246
+ path: target.path,
2247
+ action: existed ? "replaced" : "created"
2248
+ };
2249
+ }
2250
+ if (!await fileExists$1(target.path)) {
2251
+ await writeFile(target.path, AGENT_RULES_BLOCK, "utf8");
2252
+ return {
2253
+ path: target.path,
2254
+ action: "created"
2255
+ };
2256
+ }
2257
+ const existing = await readFile(target.path, "utf8");
2258
+ const range = findBlockRange(existing);
2259
+ if (range !== null) {
2260
+ const before = existing.slice(0, range.start);
2261
+ const after = existing.slice(range.end);
2262
+ const trimmedBlock = before.endsWith("\n") ? AGENT_RULES_BLOCK.replace(/\n$/, "") : `\n${AGENT_RULES_BLOCK.replace(/\n$/, "")}`;
2263
+ await writeFile(target.path, `${before}${trimmedBlock}${after}`, "utf8");
2264
+ return {
2265
+ path: target.path,
2266
+ action: "replaced"
2267
+ };
2268
+ }
2269
+ let gap;
2270
+ if (existing.endsWith("\n\n")) gap = "";
2271
+ else if (existing.endsWith("\n")) gap = "\n";
2272
+ else gap = "\n\n";
2273
+ await writeFile(target.path, `${existing}${gap}${AGENT_RULES_BLOCK}`, "utf8");
2274
+ return {
2275
+ path: target.path,
2276
+ action: "appended"
2277
+ };
2278
+ };
2279
+ //#endregion
2280
+ //#region src/bolt-on.ts
2281
+ /**
2282
+ * The wrangler bolt-on flow for `create-baerly-storage`. Runs when `runner.ts`
2283
+ * detects an existing `wrangler.jsonc` in the resolved `outDir` — the
2284
+ * user has a Cloudflare Worker project already and wants to add
2285
+ * baerly. No template copy. Patches the mergeable files
2286
+ * (`wrangler.jsonc`, `.dev.vars`, `.gitignore`, `package.json`),
2287
+ * writes `baerly.config.ts` (skip-if-exists), and returns the
2288
+ * worker-entry snippet for the caller to print.
2289
+ *
2290
+ * Mirrors Convex's `npx convex dev` philosophy: structured config is
2291
+ * fair game; user code (`src/index.ts`) is sacred — printed, never
2292
+ * written.
2293
+ */
2294
+ const DEV_SHARED_SECRET = "dev-shared-secret";
2295
+ const GITIGNORE_DEV_VARS_ALIASES = new Set([
2296
+ ".dev.vars",
2297
+ ".dev.vars*",
2298
+ ".env*.local",
2299
+ "*.local",
2300
+ ".env"
2301
+ ]);
2302
+ const configTemplate = (app, tenant) => {
2303
+ return `import { defineConfig } from "@gusto/baerly-storage/config";
2304
+
2305
+ export default defineConfig(${JSON.stringify({
2306
+ app,
2307
+ tenant,
2308
+ target: "cloudflare",
2309
+ auth: "none",
2310
+ collections: {}
2311
+ }, null, 2)});
2312
+ `;
2313
+ };
2314
+ const gitignoreCovers = (text, line) => {
2315
+ return text.split("\n").map((l) => l.trim()).some((l) => GITIGNORE_DEV_VARS_ALIASES.has(l) || l === line);
2316
+ };
2317
+ const fileExists = async (path) => {
2318
+ try {
2319
+ await access(path, constants.F_OK);
2320
+ return true;
2321
+ } catch {
2322
+ return false;
2323
+ }
2324
+ };
2325
+ const appendBaerlyStorageDep = async (pkgJsonPath, changes) => {
2326
+ const raw = await readFile(pkgJsonPath, "utf8");
2327
+ let pkg;
2328
+ try {
2329
+ pkg = JSON.parse(raw);
2330
+ } catch (error) {
2331
+ throw new BaerlyError("InvalidConfig", `create-baerly-storage bolt-on: ${pkgJsonPath} is not valid JSON — ${error instanceof Error ? error.message : String(error)}`);
2332
+ }
2333
+ pkg.dependencies = pkg.dependencies ?? {};
2334
+ if (pkg.dependencies["@gusto/baerly-storage"] !== void 0) return;
2335
+ pkg.dependencies["@gusto/baerly-storage"] = "*";
2336
+ await writeFile(pkgJsonPath, `${JSON.stringify(pkg, null, 2)}\n`, "utf8");
2337
+ changes.push("package.json: added @gusto/baerly-storage dependency");
2338
+ };
2339
+ const boltOnExistingWrangler = async (opts) => {
2340
+ const wranglerPath = resolve(opts.outDir, "wrangler.jsonc");
2341
+ if (!await fileExists(wranglerPath)) throw new BaerlyError("InvalidConfig", `create-baerly-storage bolt-on: ${wranglerPath} missing — bolt-on mode requires wrangler.jsonc`);
2342
+ const wranglerSource = await readFile(wranglerPath, "utf8");
2343
+ const detectedName = readWranglerName(wranglerSource);
2344
+ const detectedMain = readWranglerMain(wranglerSource) ?? "src/index.ts";
2345
+ const app = opts.app ?? detectedName;
2346
+ if (typeof app !== "string" || app.length === 0) throw new BaerlyError("InvalidConfig", "create-baerly-storage bolt-on: --app=<name> is required (no wrangler.jsonc:name to infer from)");
2347
+ const changes = [];
2348
+ const patch = patchWranglerJsonc(wranglerSource, {
2349
+ binding: "BUCKET",
2350
+ bucket_name: app
2351
+ }, {
2352
+ APP: app,
2353
+ TENANT: opts.tenant
2354
+ });
2355
+ if (patch.changes.length > 0) {
2356
+ await writeFile(wranglerPath, patch.text, "utf8");
2357
+ for (const c of patch.changes) changes.push(`wrangler.jsonc: ${c}`);
2358
+ }
2359
+ const devVarsPath = resolve(opts.outDir, ".dev.vars");
2360
+ if (!await fileExists(devVarsPath)) {
2361
+ await writeFile(devVarsPath, `SHARED_SECRET=${DEV_SHARED_SECRET}\n`, "utf8");
2362
+ changes.push(".dev.vars: seeded SHARED_SECRET (dev-only placeholder; replace before deploy)");
2363
+ }
2364
+ const gitignorePath = resolve(opts.outDir, ".gitignore");
2365
+ let gitignoreText = "";
2366
+ if (await fileExists(gitignorePath)) gitignoreText = await readFile(gitignorePath, "utf8");
2367
+ if (!gitignoreCovers(gitignoreText, ".dev.vars")) {
2368
+ await appendFile(gitignorePath, `${gitignoreText.length === 0 || gitignoreText.endsWith("\n") ? "" : "\n"}.dev.vars\n`, "utf8");
2369
+ changes.push(".gitignore: added .dev.vars");
2370
+ }
2371
+ const configPath = resolve(opts.outDir, "baerly.config.ts");
2372
+ const configExists = await fileExists(configPath);
2373
+ if (!configExists || opts.force === true) {
2374
+ await writeFile(configPath, configTemplate(app, opts.tenant), "utf8");
2375
+ changes.push(`baerly.config.ts: ${configExists ? "rewrote" : "wrote"}`);
2376
+ }
2377
+ const pkgJsonPath = resolve(opts.outDir, "package.json");
2378
+ if (await fileExists(pkgJsonPath)) await appendBaerlyStorageDep(pkgJsonPath, changes);
2379
+ let agentRules;
2380
+ if (opts.agentRules === true) {
2381
+ agentRules = await writeAgentRulesBlock(opts.outDir);
2382
+ const relPath = agentRules.path.startsWith(opts.outDir) ? agentRules.path.slice(opts.outDir.length + 1) : agentRules.path;
2383
+ changes.push(`${relPath}: ${agentRules.action} agent-rules block`);
2384
+ }
2385
+ if (opts.runInstall === true) {
2386
+ const pm = opts.pm ?? detectPm();
2387
+ await (opts.installer ?? defaultInstaller).run(pm, opts.outDir);
2388
+ changes.push(`${pm} install`);
2389
+ }
2390
+ const snippet = renderWorkerEntrySnippet({
2391
+ tenant: opts.tenant,
2392
+ wranglerMain: detectedMain
2393
+ });
2394
+ return {
2395
+ app,
2396
+ tenant: opts.tenant,
2397
+ changes,
2398
+ snippet,
2399
+ snippetTarget: detectedMain,
2400
+ nextSteps: [`Paste the snippet above into ${detectedMain}, replacing the stock handler.`, `Before deploy: \`wrangler secret put SHARED_SECRET\` (the .dev.vars value is dev-only).`],
2401
+ ...agentRules !== void 0 && { agentRules }
2402
+ };
2403
+ };
2404
+ //#endregion
2405
+ //#region src/runner.ts
2406
+ /**
2407
+ * `create-baerly-storage` command logic — citty `defineCommand` plus the
2408
+ * programmatic `runCreateBaerly` entry consumed by tests. The bin
2409
+ * shim at `./index.ts` imports `main` from here and invokes citty's
2410
+ * `runMain`. Tests import `runCreateBaerly` so they can drive the
2411
+ * CLI in-process without `runMain` calling `process.exit` inside
2412
+ * vitest.
2413
+ *
2414
+ * That `npm create` invocation is the **post-publish** form; until
2415
+ * the package ships to npm, stage locally from a clone via
2416
+ * `pnpm pack` + `pnpm dlx file:.../create-baerly-0.1.0.tgz` — see
2417
+ * the repo `README.md` Quick Start.
2418
+ *
2419
+ * Citty arg shape matches `@baerly/cli`'s `defineCommand` pattern
2420
+ * (see `packages/cli/src/init.ts`).
2421
+ *
2422
+ * Two flows live here:
2423
+ * - **Interactive wizard** — enters `runWizard` from `./prompts.ts`
2424
+ * when stdin is a TTY *and* `--json` is not set *and* either
2425
+ * `projectName` or `target` was omitted.
2426
+ * - **Flag-driven** — unchanged: CI, agents, piped stdin, and any
2427
+ * TTY invocation with `--json` keep the existing behavior and
2428
+ * the existing JSON envelope shape (part of the agent contract).
2429
+ */
2430
+ const CREATE_BAERLY_ARGS = {
2431
+ projectName: {
2432
+ type: "positional",
2433
+ description: "Output directory name (or '.' to scaffold into the current directory)",
2434
+ required: false,
2435
+ valueHint: "name"
2436
+ },
2437
+ target: {
2438
+ type: "enum",
2439
+ options: ["cloudflare", "node"],
2440
+ description: "Deploy target — \"cloudflare\" or \"node\".",
2441
+ required: false
2442
+ },
2443
+ starter: {
2444
+ type: "enum",
2445
+ options: ["minimal", "react"],
2446
+ description: "Starter template — \"minimal\" (default) or \"react\"."
2447
+ },
2448
+ tenant: {
2449
+ type: "string",
2450
+ description: "Default tenant pin (default \"default\").",
2451
+ valueHint: "string"
2452
+ },
2453
+ domain: {
2454
+ type: "string",
2455
+ description: "Custom domain for the deployed service.",
2456
+ valueHint: "host"
2457
+ },
2458
+ install: {
2459
+ type: "boolean",
2460
+ description: "Run <pm> install after writing files (default false)."
2461
+ },
2462
+ force: {
2463
+ type: "boolean",
2464
+ description: "In bolt-on mode, overwrite an existing baerly.config.ts (no-op in scaffold mode)."
2465
+ },
2466
+ git: {
2467
+ type: "boolean",
2468
+ description: "Initialise a git repo + create the initial commit after scaffold (default true in wizard, false in flag-driven mode). Negate with --no-git."
2469
+ },
2470
+ with: {
2471
+ type: "string",
2472
+ description: "Comma-separated add-ons. Scaffold mode: \"docker\" (requires --target=node). Bolt-on mode (`create baerly .` in an existing wrangler project): \"agent-rules\" drops an AGENTS.md block pointing at the baerly API surface.",
2473
+ valueHint: "docker|agent-rules"
2474
+ },
2475
+ pm: {
2476
+ type: "string",
2477
+ description: "Override package manager — \"npm\", \"pnpm\", or \"yarn\".",
2478
+ valueHint: "pm"
2479
+ },
2480
+ json: {
2481
+ type: "boolean",
2482
+ description: "Emit JSON envelope to stdout (success) or stderr (error)."
2483
+ }
2484
+ };
2485
+ const resolveOutDir = (projectName) => projectName === "." ? process.cwd() : resolve(process.cwd(), projectName);
2486
+ const dispatchBoltOn = async (opts) => {
2487
+ try {
2488
+ const result = await boltOnExistingWrangler({
2489
+ outDir: opts.outDir,
2490
+ tenant: opts.tenant,
2491
+ ...opts.force && { force: true },
2492
+ runInstall: opts.install,
2493
+ ...opts.pm !== void 0 && { pm: opts.pm },
2494
+ ...opts.installer !== void 0 && { installer: opts.installer },
2495
+ ...opts.agentRules && { agentRules: true }
2496
+ });
2497
+ if (opts.json) process.stdout.write(`${JSON.stringify({ result: {
2498
+ command: "create-baerly-storage",
2499
+ status: "ok",
2500
+ mode: "bolt-on",
2501
+ outDir: opts.outDir,
2502
+ app: result.app,
2503
+ tenant: result.tenant,
2504
+ changes: result.changes,
2505
+ snippet: result.snippet,
2506
+ snippetTarget: result.snippetTarget,
2507
+ nextSteps: result.nextSteps,
2508
+ ...result.agentRules !== void 0 && { agentRules: result.agentRules }
2509
+ } })}\n`);
2510
+ else if (opts.isInteractive) {
2511
+ const changesBlock = result.changes.length === 0 ? " (no changes — already bolted on)" : result.changes.map((c) => ` ${c}`).join("\n");
2512
+ outro(`${pc.green("✓")} bolted baerly onto ${opts.outDir}\n\nChanges:\n${changesBlock}\n\nPaste this into ${result.snippetTarget}, replacing the stock handler:\n\n` + result.snippet + `\nNext steps:\n` + result.nextSteps.map((s) => ` ${s}`).join("\n"));
2513
+ } else {
2514
+ process.stdout.write(`${pc.green("✓")} bolted baerly onto ${opts.outDir}\n`);
2515
+ if (result.changes.length > 0) {
2516
+ process.stdout.write(`\n Changes:\n`);
2517
+ for (const c of result.changes) process.stdout.write(` ${c}\n`);
2518
+ }
2519
+ process.stdout.write(`\n Paste this into ${result.snippetTarget}, replacing the stock handler:\n\n`);
2520
+ process.stdout.write(result.snippet);
2521
+ process.stdout.write(`\n Next steps:\n`);
2522
+ for (const s of result.nextSteps) process.stdout.write(` ${s}\n`);
2523
+ process.stdout.write("\n");
2524
+ }
2525
+ return 0;
2526
+ } catch (error) {
2527
+ const msg = error instanceof Error ? error.message : String(error);
2528
+ if (opts.json) process.stderr.write(`${JSON.stringify({ error: {
2529
+ code: "InvalidConfig",
2530
+ message: msg,
2531
+ command: "create-baerly-storage"
2532
+ } })}\n`);
2533
+ else process.stderr.write(`${pc.red("create-baerly-storage:")} ${msg}\n`);
2534
+ return 1;
2535
+ }
2536
+ };
2537
+ const handleCreateBaerly = async (args, opts = {}) => {
2538
+ const jsonMode = args.json === true;
2539
+ try {
2540
+ const isInteractive = process.stdin.isTTY === true && !jsonMode;
2541
+ const wantWizard = isInteractive && (args.projectName === void 0 || args.target === void 0);
2542
+ let withAddonsFromFlag;
2543
+ if (args.with !== void 0) {
2544
+ const parts = args.with.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
2545
+ const seen = /* @__PURE__ */ new Set();
2546
+ for (const p of parts) {
2547
+ if (!KNOWN_ADDONS.includes(p)) throw new Error(`Unknown add-on ${JSON.stringify(p)}. Available add-ons: ${KNOWN_ADDONS.join(", ")}.`);
2548
+ seen.add(p);
2549
+ }
2550
+ withAddonsFromFlag = [...seen];
2551
+ }
2552
+ let projectName;
2553
+ let target;
2554
+ let starter;
2555
+ let withAddons;
2556
+ let install;
2557
+ let git;
2558
+ if (wantWizard) {
2559
+ const w = await runWizard({
2560
+ projectName: args.projectName,
2561
+ target: args.target,
2562
+ starter: args.starter,
2563
+ withAddons: withAddonsFromFlag,
2564
+ install: args.install,
2565
+ git: args.git,
2566
+ ...args.tenant !== void 0 && { tenant: args.tenant }
2567
+ });
2568
+ if (w.mode === "bolt-on") return await dispatchBoltOn({
2569
+ outDir: resolveOutDir(w.projectName),
2570
+ tenant: w.tenant,
2571
+ force: args.force === true,
2572
+ install: w.install,
2573
+ pm: args.pm,
2574
+ json: jsonMode,
2575
+ isInteractive,
2576
+ installer: opts.installer,
2577
+ agentRules: withAddonsFromFlag?.includes("agent-rules") === true
2578
+ });
2579
+ projectName = w.projectName;
2580
+ target = w.target;
2581
+ starter = w.starter;
2582
+ withAddons = w.withAddons;
2583
+ install = w.install;
2584
+ git = w.git;
2585
+ } else {
2586
+ if (args.projectName === void 0) throw new Error("projectName is required (positional)");
2587
+ projectName = args.projectName;
2588
+ const outDir = resolveOutDir(projectName);
2589
+ if (args.target === "node" && existsSync(resolve(outDir, "wrangler.jsonc"))) throw new Error("create-baerly-storage: detected wrangler.jsonc but --target=node was passed. Bolt-on only supports Cloudflare. Remove --target=node, or move out of this directory to scaffold a Node app.");
2590
+ if (existsSync(resolve(outDir, "wrangler.jsonc"))) return await dispatchBoltOn({
2591
+ outDir,
2592
+ tenant: args.tenant ?? "default",
2593
+ force: args.force === true,
2594
+ install: args.install === true,
2595
+ pm: args.pm,
2596
+ json: jsonMode,
2597
+ isInteractive,
2598
+ installer: opts.installer,
2599
+ agentRules: withAddonsFromFlag?.includes("agent-rules") === true
2600
+ });
2601
+ if (args.target === void 0) throw new Error(`--target is required when not running in wizard mode (got undefined)`);
2602
+ target = args.target;
2603
+ starter = args.starter ?? "minimal";
2604
+ withAddons = withAddonsFromFlag ?? [];
2605
+ install = args.install === true;
2606
+ git = args.git === true;
2607
+ }
2608
+ if (withAddons.includes("docker") && target !== "node") throw new Error(`--with=docker only applies to --target=node. The Docker add-on adds a Dockerfile to the Node template. Use --target=node --with=docker, or drop --with=docker to scaffold for --target=${target}.`);
2609
+ if (withAddons.includes("agent-rules")) throw new Error("--with=agent-rules only applies to bolt-on mode (pnpm create baerly . inside an existing wrangler project). Scaffolded apps already include an AGENTS.md preamble — drop --with=agent-rules.");
2610
+ const result = await scaffold({
2611
+ projectName,
2612
+ target,
2613
+ starter,
2614
+ ...args.tenant !== void 0 && { tenant: args.tenant },
2615
+ ...args.domain !== void 0 && { domain: args.domain },
2616
+ ...args.pm !== void 0 && { pm: args.pm },
2617
+ ...withAddons.length > 0 && { withAddons }
2618
+ });
2619
+ const pm = args.pm ?? detectPm();
2620
+ if (git) {
2621
+ const gitRunner = opts.gitRunner ?? defaultGitRunner;
2622
+ const pmVersion = probePmVersion(pm);
2623
+ const outcome = initRepoAndCommit({
2624
+ outDir: result.outDir,
2625
+ cliVersion: result.cliVersion,
2626
+ appName: result.appName,
2627
+ target,
2628
+ starter,
2629
+ pm,
2630
+ ...pmVersion !== void 0 && { pmVersion }
2631
+ }, gitRunner);
2632
+ if (!outcome.initialized && outcome.reason !== "already-in-repo") {
2633
+ const detail = outcome.message === void 0 || outcome.message.length === 0 ? "" : `: ${outcome.message}`;
2634
+ let hint = `${outcome.reason}${detail}`;
2635
+ if (outcome.reason === "git-not-available") hint = `git is not installed; install it then run \`git init && git add . && git commit -m '…'\` in ${result.outDir}.`;
2636
+ else if (outcome.reason === "no-identity") hint = `git user.name / user.email are not configured. Set them with \`git config --global user.name '…'\` + \`git config --global user.email '…'\`, then commit manually.`;
2637
+ process.stderr.write(`${pc.yellow("create-baerly-storage:")} git init skipped — ${hint}\n`);
2638
+ }
2639
+ }
2640
+ if (install) {
2641
+ const { code } = await (opts.installer ?? defaultInstaller).run(pm, result.outDir);
2642
+ if (code !== 0) process.stderr.write(`${pc.yellow("create-baerly-storage:")} install exited with code ${code}. Run \`${pm} install\` in ${result.outDir} manually.\n`);
2643
+ }
2644
+ if (jsonMode) process.stdout.write(`${JSON.stringify({ result: {
2645
+ command: "create-baerly-storage",
2646
+ status: "ok",
2647
+ outDir: result.outDir,
2648
+ filesWritten: result.filesWritten.length,
2649
+ nextSteps: result.nextSteps
2650
+ } })}\n`);
2651
+ else if (isInteractive) outro(`${pc.green("✓")} ${result.outDir}\n\n Next steps:\n` + result.nextSteps.map((s) => ` ${s}`).join("\n"));
2652
+ else {
2653
+ process.stdout.write(`${pc.green("✓")} scaffolded ${result.outDir}\n`);
2654
+ process.stdout.write(`\n Next steps:\n`);
2655
+ for (const s of result.nextSteps) process.stdout.write(` ${s}\n`);
2656
+ process.stdout.write("\n");
2657
+ }
2658
+ return 0;
2659
+ } catch (error) {
2660
+ const msg = error instanceof Error ? error.message : String(error);
2661
+ if (jsonMode) process.stderr.write(`${JSON.stringify({ error: {
2662
+ code: "InvalidConfig",
2663
+ message: msg,
2664
+ command: "create-baerly-storage"
2665
+ } })}\n`);
2666
+ else process.stderr.write(`${pc.red("create-baerly-storage:")} ${msg}\n`);
2667
+ return 1;
2668
+ }
2669
+ };
2670
+ const main = defineCommand({
2671
+ meta: {
2672
+ name: "create-baerly-storage",
2673
+ version: "0.0.0",
2674
+ description: "Scaffold a new baerly app (Cloudflare Worker or self-hosted Node)."
2675
+ },
2676
+ args: CREATE_BAERLY_ARGS,
2677
+ run: async ({ args }) => {
2678
+ const code = await handleCreateBaerly(args);
2679
+ if (code !== 0) process.exit(code);
2680
+ }
2681
+ });
2682
+ //#endregion
2683
+ //#region src/index.ts
2684
+ /**
2685
+ * `create-baerly-storage` bin entry. Imports the citty command from `./runner.ts`
2686
+ * and dispatches via an inline `runBin` shim. Kept as a thin shim so
2687
+ * the runner module has no import-time side effects — tests can
2688
+ * import `runCreateBaerly` from `./runner.ts` directly without citty
2689
+ * running and calling `process.exit` inside vitest.
2690
+ *
2691
+ * The shim mirrors the shape of `@baerly/cli`'s `bin-runner.ts`
2692
+ * (same `--help` / `--version` interception, same `CLIError →
2693
+ * InvalidConfig` translation). Inlined here rather than imported
2694
+ * cross-package because `create-baerly-storage` is a separate publishable
2695
+ * with its own dependency surface — the cross-package import
2696
+ * overhead beats the dedup at this scale.
2697
+ */
2698
+ const resolve$1 = async (v) => {
2699
+ if (typeof v === "function") return v();
2700
+ return v;
2701
+ };
2702
+ const writeError = (json, code, message) => {
2703
+ if (json) process.stderr.write(`${JSON.stringify({ error: {
2704
+ code,
2705
+ message,
2706
+ command: "create-baerly-storage"
2707
+ } })}\n`);
2708
+ else process.stderr.write(`${pc.red("create-baerly-storage:")} ${code}: ${message}\n`);
2709
+ };
2710
+ const argv = process.argv.slice(2);
2711
+ const wantJson = argv.includes("--json");
2712
+ const run = async () => {
2713
+ if (argv.includes("--help") || argv.includes("-h")) {
2714
+ await showUsage(main);
2715
+ process.exit(0);
2716
+ }
2717
+ if (argv.includes("--version") || argv.includes("-v")) {
2718
+ const version = (await resolve$1(main.meta) ?? {}).version;
2719
+ if (typeof version !== "string" || version.length === 0) {
2720
+ writeError(wantJson, "InvalidConfig", "no version declared on this command");
2721
+ process.exit(1);
2722
+ }
2723
+ process.stdout.write(`${version}\n`);
2724
+ process.exit(0);
2725
+ }
2726
+ try {
2727
+ await runCommand(main, { rawArgs: [...argv] });
2728
+ process.exit(0);
2729
+ } catch (error) {
2730
+ writeError(wantJson, "InvalidConfig", error instanceof Error ? error.message : String(error));
2731
+ process.exit(1);
2732
+ }
2733
+ };
2734
+ run();
2735
+ //#endregion
2736
+
2737
+ //# sourceMappingURL=index.js.map