@gusto/create-baerly-storage 0.5.0 → 0.7.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 (37) hide show
  1. package/dist/THIRD-PARTY-LICENSES.txt +204 -0
  2. package/dist/index.js +1537 -145
  3. package/dist/index.js.map +1 -1
  4. package/dist/templates/addons/docker/Dockerfile +13 -11
  5. package/dist/templates/minimal-cloudflare/AGENTS.md +77 -399
  6. package/dist/templates/minimal-cloudflare/README.md +33 -97
  7. package/dist/templates/minimal-cloudflare/package.json +12 -9
  8. package/dist/templates/minimal-cloudflare/pnpm-workspace.yaml +13 -7
  9. package/dist/templates/minimal-cloudflare/tsconfig.app.json +2 -3
  10. package/dist/templates/minimal-cloudflare/tsconfig.worker.json +2 -3
  11. package/dist/templates/minimal-cloudflare/vitest.config.ts +1 -1
  12. package/dist/templates/minimal-cloudflare/wrangler.jsonc +4 -2
  13. package/dist/templates/minimal-node/AGENTS.md +80 -380
  14. package/dist/templates/minimal-node/README.md +37 -135
  15. package/dist/templates/minimal-node/package.json +11 -9
  16. package/dist/templates/minimal-node/pnpm-workspace.yaml +14 -9
  17. package/dist/templates/minimal-node/tsconfig.app.json +2 -3
  18. package/dist/templates/minimal-node/tsconfig.server.json +2 -3
  19. package/dist/templates/react-cloudflare/AGENTS.md +101 -444
  20. package/dist/templates/react-cloudflare/README.md +14 -54
  21. package/dist/templates/react-cloudflare/package.json +18 -15
  22. package/dist/templates/react-cloudflare/pnpm-workspace.yaml +13 -7
  23. package/dist/templates/react-cloudflare/tsconfig.app.json +2 -3
  24. package/dist/templates/react-cloudflare/tsconfig.worker.json +2 -3
  25. package/dist/templates/react-cloudflare/vitest.config.ts +1 -1
  26. package/dist/templates/react-cloudflare/wrangler.jsonc +4 -2
  27. package/dist/templates/react-node/AGENTS.md +108 -474
  28. package/dist/templates/react-node/README.md +35 -125
  29. package/dist/templates/react-node/package.json +16 -14
  30. package/dist/templates/react-node/pnpm-workspace.yaml +14 -9
  31. package/dist/templates/react-node/tsconfig.app.json +2 -3
  32. package/dist/templates/react-node/tsconfig.server.json +2 -3
  33. package/package.json +7 -7
  34. package/dist/templates/minimal-cloudflare/uint8array-base64.d.ts +0 -16
  35. package/dist/templates/minimal-node/uint8array-base64.d.ts +0 -16
  36. package/dist/templates/react-cloudflare/uint8array-base64.d.ts +0 -16
  37. package/dist/templates/react-node/uint8array-base64.d.ts +0 -16
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["runCommand","runCommand","parse","parser.parse","edit.setProperty","edit.applyEdit","dirname","fileExists","resolve"],"sources":["../src/git.ts","../src/prompts.ts","../src/pm-detect.ts","../src/substitute.ts","../src/scaffold.ts","../../protocol/src/errors.ts","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/format.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/edit.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js","../../cli/src/wrangler-patch.ts","../src/init-snippet.ts","../src/install.ts","../src/agent-rules.ts","../src/bolt-on.ts","../src/runner.ts","../src/index.ts"],"sourcesContent":["/**\n * Optional post-scaffold `git init` + initial commit. Mirrors what\n * `create-vite`, `create-next-app`, and Cloudflare's `c3` already do\n * — gives the user (and any subsequent diff-driven workflow, human\n * or agent) a clean baseline-vs-HEAD diff for their first edits.\n *\n * Skips silently when:\n * - `outDir` is already inside a git work tree (nested repos confuse\n * more than they help; the user is scaffolding into an existing\n * workspace and the host repo owns the history).\n * - `git` is not installed (`git --version` fails).\n * - No global `user.name` / `user.email` is configured (the commit\n * would fail anyway; better to skip with a clear warning than to\n * leave a half-initialised `.git/` behind).\n *\n * DI'd via `GitRunner` so tests can stub spawning. The default impl\n * shells out via `spawnSync` (short calls; no need for the async\n * pump). Mirrors the `Installer` DI seam in `install.ts`.\n */\nimport { spawnSync } from \"node:child_process\";\nimport type { Pm } from \"./pm-detect.ts\";\n\nexport interface GitRunner {\n /**\n * Run `git <args>` in `cwd`. Returns the child's exit code and\n * captured stdout/stderr. Never throws on a non-zero exit — callers\n * branch on `code`. A missing `git` binary surfaces as `code: 127`\n * with the spawn error on `stderr`, so callers don't need a separate\n * try/catch for ENOENT.\n */\n run(args: readonly string[], cwd: string): { code: number; stdout: string; stderr: string };\n}\n\nexport const defaultGitRunner: GitRunner = {\n run: (args, cwd) => {\n const res = spawnSync(\"git\", [...args], { cwd, encoding: \"utf8\" });\n if (res.error !== undefined) {\n return { code: 127, stdout: \"\", stderr: res.error.message };\n }\n return {\n code: res.status ?? 1,\n stdout: res.stdout ?? \"\",\n stderr: res.stderr ?? \"\",\n };\n },\n};\n\nexport type GitInitOutcome =\n | { readonly initialized: true; readonly branch: \"main\" }\n | {\n readonly initialized: false;\n readonly reason:\n | \"already-in-repo\"\n | \"git-not-available\"\n | \"no-identity\"\n | \"init-failed\"\n | \"add-failed\"\n | \"commit-failed\";\n readonly message?: string;\n };\n\nexport interface GitInitDetails {\n /** Absolute path to the freshly-scaffolded directory. */\n readonly outDir: string;\n /** `create-baerly-storage` package version. Stamped into the commit body. */\n readonly cliVersion: string;\n /** Substituted `appName` sentinel from the scaffold. */\n readonly appName: string;\n readonly target: \"cloudflare\" | \"node\";\n readonly starter: \"minimal\" | \"react\";\n readonly pm: Pm;\n /** Optional; resolved by the runner via `probePmVersion()`. */\n readonly pmVersion?: string;\n}\n\nconst trim = (s: string): string => s.trim();\n\nconst isInsideGitWorkTree = (cwd: string, runner: GitRunner): boolean => {\n const res = runner.run([\"rev-parse\", \"--is-inside-work-tree\"], cwd);\n return res.code === 0 && trim(res.stdout) === \"true\";\n};\n\nconst probeGitVersion = (cwd: string, runner: GitRunner): string | undefined => {\n const res = runner.run([\"--version\"], cwd);\n if (res.code !== 0) {\n return undefined;\n }\n // \"git version 2.54.0\" — strip the prefix when present, otherwise\n // pass through whatever the shim emitted.\n const m = /^git version (\\S+)/.exec(trim(res.stdout));\n return m === null ? trim(res.stdout) : m[1];\n};\n\nconst hasIdentity = (cwd: string, runner: GitRunner): boolean => {\n const name = runner.run([\"config\", \"user.name\"], cwd);\n const email = runner.run([\"config\", \"user.email\"], cwd);\n return (\n name.code === 0 &&\n email.code === 0 &&\n trim(name.stdout).length > 0 &&\n trim(email.stdout).length > 0\n );\n};\n\nconst commitMessage = (details: GitInitDetails, gitVersion: string): string => {\n const pmLine =\n details.pmVersion === undefined ? details.pm : `${details.pm}@${details.pmVersion}`;\n return [\n \"Initial commit (by create-baerly-storage)\",\n \"\",\n \"Details:\",\n ` create-baerly-storage = ${details.cliVersion}`,\n ` project name = ${details.appName}`,\n ` target = ${details.target}`,\n ` starter = ${details.starter}`,\n ` package mgr = ${pmLine}`,\n ` git = ${gitVersion}`,\n \"\",\n ].join(\"\\n\");\n};\n\n/**\n * `git init --initial-branch=main` is rejected by gits older than\n * 2.28 (released 2020). Fall back to plain `git init` followed by\n * `symbolic-ref HEAD refs/heads/main` so the resulting branch is the\n * same regardless of which git the user has on PATH.\n */\nconst initWithMainBranch = (\n outDir: string,\n runner: GitRunner,\n): { code: number; message: string } => {\n const first = runner.run([\"init\", \"--initial-branch=main\"], outDir);\n if (first.code === 0) {\n return { code: 0, message: trim(first.stdout) };\n }\n const fallback = runner.run([\"init\"], outDir);\n if (fallback.code !== 0) {\n return { code: fallback.code, message: trim(fallback.stderr) };\n }\n const setBranch = runner.run([\"symbolic-ref\", \"HEAD\", \"refs/heads/main\"], outDir);\n return { code: setBranch.code, message: trim(setBranch.stderr) };\n};\n\n/**\n * `outDir` must already exist on disk (scaffold has written into it).\n * Probes are all DI'd through the runner, so a test stub controls the\n * whole flow — including the \"is this dir inside a repo?\" question.\n */\nexport const initRepoAndCommit = (\n details: GitInitDetails,\n runner: GitRunner = defaultGitRunner,\n): GitInitOutcome => {\n const gitVersion = probeGitVersion(details.outDir, runner);\n if (gitVersion === undefined) {\n return { initialized: false, reason: \"git-not-available\" };\n }\n if (isInsideGitWorkTree(details.outDir, runner)) {\n return { initialized: false, reason: \"already-in-repo\" };\n }\n if (!hasIdentity(details.outDir, runner)) {\n return { initialized: false, reason: \"no-identity\" };\n }\n const init = initWithMainBranch(details.outDir, runner);\n if (init.code !== 0) {\n return { initialized: false, reason: \"init-failed\", message: init.message };\n }\n const add = runner.run([\"add\", \".\"], details.outDir);\n if (add.code !== 0) {\n return { initialized: false, reason: \"add-failed\", message: trim(add.stderr) };\n }\n const commit = runner.run(\n [\"commit\", \"-m\", commitMessage(details, gitVersion), \"--no-verify\"],\n details.outDir,\n );\n if (commit.code !== 0) {\n return { initialized: false, reason: \"commit-failed\", message: trim(commit.stderr) };\n }\n return { initialized: true, branch: \"main\" };\n};\n","/**\n * Interactive wizard for `create-baerly-storage`. Invoked only when the\n * process is attached to a real TTY and at least one required arg\n * (`projectName` / `target`) is missing. Non-TTY callers (CI, agents,\n * piped stdin) and `--json` callers retain the flag-driven path and\n * unchanged JSON envelope — see `index.ts`.\n *\n * API surface (`@clack/prompts` v1+): `intro`, `text`, `select`,\n * `confirm`, `outro`, `isCancel`, `cancel`. `isCancel(value)` returns\n * `true` when the user hits Ctrl+C; in that case we call `cancel()`\n * and `process.exit(1)` (same exit code as a user error).\n */\nimport { cancel, confirm, intro, isCancel, note, select, text } from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { defaultGitRunner, type GitRunner } from \"./git.ts\";\nimport type { Addon } from \"./scaffold.ts\";\n\nconst TARGETS = [\n {\n value: \"cloudflare\",\n label: \"Cloudflare Workers\",\n hint: \"R2 + Workers, deploy via wrangler\",\n },\n {\n value: \"node\",\n label: \"Node\",\n hint: \"Any host that runs `node server.js` (Railway, Render, Fly without Docker, Heroku, a VM)\",\n },\n] as const;\n\nconst STARTERS = [\n {\n value: \"minimal\",\n label: \"Minimal\",\n hint: \"Server only — no UI framework\",\n },\n {\n value: \"react\",\n label: \"React\",\n hint: \"React + Vite SPA over a sample notes collection\",\n },\n] as const;\n\nexport interface WizardInput {\n /** When non-undefined, skip the projectName prompt and use this. */\n readonly projectName?: string;\n /** When non-undefined, skip the target prompt and use this. */\n readonly target?: \"cloudflare\" | \"node\";\n /** When non-undefined, skip the starter prompt and use this. */\n readonly starter?: \"minimal\" | \"react\";\n /**\n * When non-undefined, skip the per-add-on confirms and use this set.\n * Today only `\"docker\"` is a meaningful element (and only when\n * `target === \"node\"`).\n */\n readonly withAddons?: readonly Addon[];\n /** When non-undefined, skip the install confirm and use this. */\n readonly install?: boolean;\n /**\n * When non-undefined, skip the git-init confirm and use this. The\n * wizard also skips the prompt — defaulting to `false` — when the\n * current directory is already inside a git work tree, since\n * `create-baerly-storage` won't nest a new repo inside an existing one\n * either way.\n */\n readonly git?: boolean;\n /** Tenant pin passed through from --tenant; bolt-on mode uses it directly. */\n readonly tenant?: string;\n}\n\nexport type WizardOutput = ScaffoldWizardOutput | BoltOnWizardOutput;\n\nexport interface ScaffoldWizardOutput {\n readonly mode: \"scaffold\";\n /**\n * May be `\".\"` — the sentinel for \"scaffold into the current\n * directory\". Callers must not blindly compose this with a path\n * (e.g. `path.join(cwd, projectName)`); branch on `=== \".\"`\n * first or pass it straight through to `scaffold()`.\n */\n readonly projectName: string;\n readonly target: \"cloudflare\" | \"node\";\n readonly starter: \"minimal\" | \"react\";\n readonly withAddons: readonly Addon[];\n readonly install: boolean;\n readonly git: boolean;\n}\n\ninterface BoltOnWizardOutput {\n readonly mode: \"bolt-on\";\n readonly projectName: string;\n readonly tenant: string;\n readonly install: boolean;\n}\n\nexport const runWizard = async (\n input: WizardInput,\n opts: { readonly gitRunner?: GitRunner } = {},\n): Promise<WizardOutput> => {\n intro(pc.bold(pc.cyan(\"create-baerly-storage\")));\n const projectName = input.projectName ?? (await promptProjectName());\n const outDir = projectName === \".\" ? process.cwd() : resolve(process.cwd(), projectName);\n const wranglerPath = resolve(outDir, \"wrangler.jsonc\");\n if (existsSync(wranglerPath)) {\n note(\"Detected existing Cloudflare Worker — bolting baerly on instead of scaffolding.\");\n const install = input.install ?? (await promptInstall());\n return {\n mode: \"bolt-on\",\n projectName,\n tenant: input.tenant ?? \"default\",\n install,\n };\n }\n const target = input.target ?? (await promptTarget());\n const starter = input.starter ?? (await promptStarter());\n // Add-on prompts are gated per-target. Today only `docker` exists\n // and only applies when `target === \"node\"`; on `cloudflare` we\n // skip the prompt and emit an empty addon list.\n let withAddons: readonly Addon[];\n if (input.withAddons !== undefined) {\n withAddons = input.withAddons;\n } else if (target === \"node\") {\n withAddons = (await promptDocker()) ? [\"docker\"] : [];\n } else {\n withAddons = [];\n }\n const install = input.install ?? (await promptInstall());\n // Skip the git prompt entirely when we're already inside a git\n // work tree — `initRepoAndCommit` would skip with `already-in-repo`\n // anyway, and asking the question would only confuse a user who\n // can't usefully answer it. `opts.gitRunner` makes this stubbable\n // for the wizard-flow tests. Pre-filled `input.git` short-circuits\n // BEFORE the spawn so pure-prompt tests don't incur the side effect.\n let git: boolean;\n if (input.git !== undefined) {\n git = input.git;\n } else {\n const gitRunner = opts.gitRunner ?? defaultGitRunner;\n const insideRepo =\n gitRunner.run([\"rev-parse\", \"--is-inside-work-tree\"], process.cwd()).stdout.trim() === \"true\";\n git = insideRepo ? false : await promptGit();\n }\n return { mode: \"scaffold\", projectName, target, starter, withAddons, install, git };\n};\n\nconst promptProjectName = async (): Promise<string> => {\n const v = await text({\n message: \"Project name (use '.' for current directory)\",\n placeholder: \"my-app\",\n // `@clack/prompts` v1 widened the `validate` callback's parameter\n // to `string | undefined`. Treat `undefined` as the empty string\n // so the existing \"non-empty\" guard fires.\n validate: (raw = \"\") => {\n if (raw.length === 0) {\n return \"name must be non-empty\";\n }\n // `\".\"` (exactly one character) is the shorthand for \"scaffold\n // into the current directory\" — `scaffold.ts` derives `appName`\n // from `basename(cwd)` and applies the same regex below to that\n // derived value.\n if (raw === \".\") {\n return undefined;\n }\n // MUST mirror the validation regex in `scaffold.ts`'s `scaffold()`.\n if (!/^[a-z0-9][a-z0-9_-]*$/.test(raw)) {\n return \"lowercase, alphanumeric + - / _, starting with [a-z0-9] (or '.' for current directory)\";\n }\n return undefined;\n },\n });\n if (isCancel(v)) {\n cancel(\"Cancelled.\");\n process.exit(1);\n }\n return v as string;\n};\n\nconst promptTarget = async (): Promise<\"cloudflare\" | \"node\"> => {\n const v = await select({\n message: \"Deploy target\",\n options: [...TARGETS],\n initialValue: \"cloudflare\",\n });\n if (isCancel(v)) {\n cancel(\"Cancelled.\");\n process.exit(1);\n }\n return v as \"cloudflare\" | \"node\";\n};\n\nconst promptStarter = async (): Promise<\"minimal\" | \"react\"> => {\n const v = await select({\n message: \"Starter template\",\n options: [...STARTERS],\n initialValue: \"minimal\",\n });\n if (isCancel(v)) {\n cancel(\"Cancelled.\");\n process.exit(1);\n }\n return v as \"minimal\" | \"react\";\n};\n\nconst promptDocker = async (): Promise<boolean> => {\n const v = await confirm({\n message: \"Add a production Dockerfile?\",\n initialValue: false,\n });\n if (isCancel(v)) {\n cancel(\"Cancelled.\");\n process.exit(1);\n }\n return v as boolean;\n};\n\nconst promptInstall = async (): Promise<boolean> => {\n const v = await confirm({ message: \"Install dependencies?\", initialValue: true });\n if (isCancel(v)) {\n cancel(\"Cancelled.\");\n process.exit(1);\n }\n return v as boolean;\n};\n\nconst promptGit = async (): Promise<boolean> => {\n const v = await confirm({\n message: \"Initialise a git repo and create the initial commit?\",\n initialValue: true,\n });\n if (isCancel(v)) {\n cancel(\"Cancelled.\");\n process.exit(1);\n }\n return v as boolean;\n};\n","/**\n * Which package manager invoked us. Read from\n * `npm_config_user_agent` — set by npm/pnpm/yarn when they run\n * their `create` shorthand. Defaults to `\"npm\"` on any parse\n * failure (most conservative — npm has the widest install base).\n */\nimport { spawnSync } from \"node:child_process\";\n\nexport type Pm = \"npm\" | \"pnpm\" | \"yarn\";\n\nexport const detectPm = (\n userAgent: string | undefined = process.env[\"npm_config_user_agent\"],\n): Pm => {\n if (userAgent === undefined) {\n return \"npm\";\n }\n // user-agent format: \"<pm>/<version> node/<v> <platform> <arch>\"\n const m = /^(npm|pnpm|yarn)\\//.exec(userAgent);\n if (m === null) {\n return \"npm\";\n }\n return m[1] as Pm;\n};\n\n/**\n * The install command for the detected PM. Used in the post-\n * scaffold \"next steps\" output.\n */\nexport const installCommand = (pm: Pm): string => {\n if (pm === \"npm\") {\n return \"npm install\";\n }\n if (pm === \"pnpm\") {\n return \"pnpm install\";\n }\n return \"yarn install\";\n};\n\n/**\n * The run-script invocation prefix. `pnpm dev` / `npm run dev` /\n * `yarn dev`. The scaffolded `package.json` scripts assume this\n * shape.\n */\nexport const runCommand = (pm: Pm, script: string): string => {\n if (pm === \"pnpm\") {\n return `pnpm ${script}`;\n }\n if (pm === \"yarn\") {\n return `yarn ${script}`;\n }\n return `npm run ${script}`;\n};\n\n/**\n * Best-effort `<pm> --version` probe. Returns the trimmed version\n * string on success, or `undefined` if the pm binary can't be\n * spawned or returns non-zero. Used by the `git init` commit-message\n * body — a missing pm version is a stylistic loss, not a hard error,\n * so callers should pass the result through unchecked.\n */\nexport const probePmVersion = (pm: Pm): string | undefined => {\n const res = spawnSync(pm, [\"--version\"], { encoding: \"utf8\" });\n if (res.error !== undefined || res.status !== 0) {\n return undefined;\n }\n const out = (res.stdout ?? \"\").trim();\n return out.length > 0 ? out : undefined;\n};\n","/**\n * Manifest-driven content rewrite for the scaffolder. Two kinds of\n * edits happen at copy time:\n *\n * 1. Sentinel rename. Each entry in `manifest.renames` is a literal\n * substring to replace, mapped to a user-supplied value via\n * `fromKey`. Sentinels are applied longest-first so a longer\n * sentinel (e.g. \"minimal-cloudflare-server\") rewrites before a\n * shorter one it contains as a prefix (\"minimal-cloudflare\").\n *\n * 2. package.json normalisation. For files named `package.json`,\n * any `workspace:*` value under a dep key matching `@gusto/baerly-storage`\n * is pinned to `^<cliVersion>` (the scaffolder + the\n * `@gusto/baerly-storage` umbrella ship at the same version), and\n * any dep in `manifest.dropDevDeps` is removed from\n * `devDependencies`. Indentation is preserved by round-tripping\n * through `JSON.parse` + `JSON.stringify(_, null, 2)`.\n *\n * Literal substring substitution is deliberate: example sentinels are\n * unusual enough (`minimal-cloudflare`, `minimal-demo`, …) not to\n * collide with unrelated content, and substring matching covers the\n * full surface of code/JSON/Markdown/Dockerfile/systemd without per-\n * extension parsing.\n */\n\ninterface ManifestRename {\n readonly from: string;\n readonly fromKey: string;\n}\n\ninterface ManifestCopy {\n readonly from: string;\n readonly to: string;\n}\n\nexport interface ScaffoldManifest {\n readonly renames: readonly ManifestRename[];\n /**\n * Paths relative to the example root that must be skipped during\n * the copy. Matched as exact relative paths (e.g.\n * `\".baerly/scaffold.json\"`).\n */\n readonly excludePaths: readonly string[];\n /**\n * Basename patterns skipped at any depth in the source tree. Each\n * entry is either a literal name (e.g. `\"node_modules\"`) or a\n * `*.<ext>` suffix glob (e.g. `\"*.tsbuildinfo\"`). Use this for\n * build artifacts / OS detritus that may exist inside the\n * example's working tree but must never land in a scaffolded app.\n */\n readonly excludeNames: readonly string[];\n readonly dropDevDeps: readonly string[];\n /**\n * Files written more than once during a single scaffold pass. Each\n * entry mirrors a source file (`from`, relative to the example\n * root) into a second destination (`to`, relative to the output\n * root) with the same `substituteText` pass applied. Lets the\n * example author declare AGENTS.md ↔ CLAUDE.md parity (and any\n * future coding-tool variant) in data, not in walker branches.\n */\n readonly copies: readonly ManifestCopy[];\n}\n\nexport interface SubstituteContext {\n readonly manifest: ScaffoldManifest;\n readonly vars: Record<string, string>;\n readonly cliVersion: string;\n}\n\n/**\n * Rewrite text content (any non-JSON-aware file). Applies sentinel\n * renames longest-first. Unknown `fromKey` values cause the rename to\n * be skipped — that's a scaffolder authoring bug, not a user error,\n * and silent empty-substitution would hide it.\n */\nexport const substituteText = (text: string, ctx: SubstituteContext): string => {\n const sorted = ctx.manifest.renames.toSorted((a, b) => b.from.length - a.from.length);\n let out = text;\n for (const r of sorted) {\n if (!Object.hasOwn(ctx.vars, r.fromKey)) {\n continue;\n }\n out = out.replaceAll(r.from, ctx.vars[r.fromKey]!);\n }\n return out;\n};\n\n/**\n * Rewrite a package.json's text content. Applies sentinel renames\n * first (covers the `\"name\"` field and any other string), then pins\n * `@gusto/baerly-storage` workspace deps to the CLI version, and drops\n * listed devDependencies.\n */\nexport const substitutePackageJson = (text: string, ctx: SubstituteContext): string => {\n const renamed = substituteText(text, ctx);\n const pkg = JSON.parse(renamed) as Record<string, unknown> & {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n };\n const pin = `^${ctx.cliVersion}`;\n for (const block of [\"dependencies\", \"devDependencies\", \"peerDependencies\"] as const) {\n const deps = pkg[block];\n if (deps === undefined) {\n continue;\n }\n for (const [name, value] of Object.entries(deps)) {\n if (value !== \"workspace:*\") {\n continue;\n }\n if (name === \"@gusto/baerly-storage\") {\n deps[name] = pin;\n }\n }\n }\n if (pkg.devDependencies !== undefined) {\n for (const drop of ctx.manifest.dropDevDeps) {\n delete pkg.devDependencies[drop];\n }\n if (Object.keys(pkg.devDependencies).length === 0) {\n delete pkg.devDependencies;\n }\n }\n return `${JSON.stringify(pkg, null, 2)}\\n`;\n};\n","import { fileURLToPath } from \"node:url\";\nimport { basename, dirname, join, resolve, sep } from \"node:path\";\nimport { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from \"node:fs\";\nimport { detectPm, installCommand, runCommand, type Pm } from \"./pm-detect.ts\";\nimport {\n type ScaffoldManifest,\n type SubstituteContext,\n substitutePackageJson,\n substituteText,\n} from \"./substitute.ts\";\n\n/**\n * Optional add-ons and compatibility tokens recognised by the CLI.\n * `docker` is a scaffold template overlay; `agent-rules` is the legacy\n * bolt-on `--with` token for the default-on agent-rules writer. Adding\n * a new entry here is what makes `--with=<name>` recognised by both the\n * flag parser and the wizard.\n *\n * - `docker` (scaffold-only, `--target=node`): copies the Dockerfile\n * add-on under `templates/addons/docker/` on top of the scaffolded\n * project.\n * - `agent-rules` (bolt-on compatibility token): the CLI now writes\n * this by default in bolt-on mode and accepts `--no-agent-rules` to\n * opt out. Scaffolded apps already ship the same guidance via the\n * per-template `AGENTS.md`.\n */\nexport const KNOWN_ADDONS = [\"docker\", \"agent-rules\"] as const;\nexport type Addon = (typeof KNOWN_ADDONS)[number];\n\nexport interface ScaffoldOptions {\n /**\n * Lowercase alphanumeric + `-` / `_`, starting with `[a-z0-9]`.\n * `\".\"` is a sentinel that scaffolds into the current `outRoot`\n * (or `process.cwd()` when `outRoot` is unset); the `appName`\n * substitution sentinel is then derived from that directory's\n * basename and must itself satisfy the same regex.\n */\n readonly projectName: string;\n readonly target: \"cloudflare\" | \"node\";\n readonly starter?: \"minimal\" | \"react\";\n readonly pm?: Pm;\n readonly tenant?: string;\n readonly domain?: string;\n /** Add-ons to layer on top of the base template. */\n readonly withAddons?: readonly Addon[];\n /** Override the templates root. Tests inject a fixture path. */\n readonly templatesRoot?: string;\n /** Override the add-ons root. Tests inject a fixture path. */\n readonly addonsRoot?: string;\n /** Override the output root. Tests inject a tmpdir. */\n readonly outRoot?: string;\n}\n\nexport interface ScaffoldResult {\n readonly outDir: string;\n readonly filesWritten: readonly string[];\n readonly nextSteps: readonly string[];\n /**\n * `create-baerly-storage`'s own `package.json:version`. Stamped into the\n * post-scaffold initial commit (when `--git` runs) so the user\n * can grep `git log` for the scaffolder version that produced\n * their repo.\n */\n readonly cliVersion: string;\n /**\n * The substitution sentinel that was applied to template literals.\n * Equals `projectName` for the named-dir form and `basename(outDir)`\n * for `create-baerly-storage .`. Surfaced on the result so the caller can\n * pass it through to the git-init commit body without re-deriving.\n */\n readonly appName: string;\n}\n\n/**\n * When `projectName === \".\"` (scaffold into the current directory),\n * a pre-existing entry whose basename is in this set is always\n * permitted — even if the scaffold also ships a file by the same\n * name (the scaffold overwrites). Other names are checked against\n * the precomputed \"would-write\" set (see `topLevelOutputs`); only\n * actual collisions fail the guard, so a pre-existing `.npmrc` /\n * `mise.toml` / `.tool-versions` (or any other top-level metadata\n * the user already wrote) coexists with the scaffold.\n */\nconst SCAFFOLD_HERE_ALLOWLIST: ReadonlySet<string> = new Set([\n \".git\",\n \".gitignore\",\n \".gitattributes\",\n \"README.md\",\n \"LICENSE\",\n \"LICENSE.md\",\n \"LICENSE.txt\",\n]);\n\n/**\n * Compute the set of top-level basenames the scaffold will emit\n * into `outDir`. Used by the `inPlace` guard to decide which\n * pre-existing entries actually collide.\n *\n * Mirrors the logic in `walk()`: applies `excludePaths` /\n * `excludeNames`, renames `_gitignore` → `.gitignore`, and folds\n * in the top-level destination of each `manifest.copies` entry.\n * Add-ons layer on top of the base template via the same walker,\n * so their top-level basenames are included here too.\n */\nconst topLevelOutputs = (\n templateDir: string,\n manifest: ScaffoldManifest,\n addonDirs: readonly string[],\n): Set<string> => {\n const excluded = new Set(manifest.excludePaths.map((p) => p.split(\"/\").join(sep)));\n const { literals: excludeLiterals, suffixes: excludeSuffixes } = splitExcludeNames(\n manifest.excludeNames,\n );\n const matchesExcludeName = (name: string): boolean => {\n if (excludeLiterals.has(name)) {\n return true;\n }\n for (const suffix of excludeSuffixes) {\n if (name.endsWith(suffix)) {\n return true;\n }\n }\n return false;\n };\n const out = new Set<string>();\n const addTopLevel = (sourceDir: string): void => {\n for (const ent of readdirSync(sourceDir)) {\n if (excluded.has(ent) || matchesExcludeName(ent)) {\n continue;\n }\n out.add(ent === \"_gitignore\" ? \".gitignore\" : ent);\n }\n };\n addTopLevel(templateDir);\n for (const addonDir of addonDirs) {\n addTopLevel(addonDir);\n }\n for (const copy of manifest.copies) {\n const dest = copy.to.split(\"/\").join(sep);\n const firstSeg = dest.split(sep)[0];\n if (firstSeg !== undefined && firstSeg.length > 0) {\n out.add(firstSeg);\n }\n }\n return out;\n};\n\nconst TEXT_EXTS = new Set([\n \".ts\",\n \".tsx\",\n \".js\",\n \".cjs\",\n \".json\",\n \".jsonc\",\n \".md\",\n \".toml\",\n \".yaml\",\n \".yml\",\n \".html\",\n \".css\",\n \".gitignore\",\n \".dockerignore\",\n \".example\",\n \".service\",\n]);\n\n/**\n * `${target}:${starter}` → example directory name (under `examples/`).\n * Default starter is `\"minimal\"`. The compound key lets us add richer\n * starters per target without renaming or duplicating maps.\n */\nconst STARTER_TO_EXAMPLE: Record<string, string> = {\n \"cloudflare:minimal\": \"minimal-cloudflare\",\n \"cloudflare:react\": \"react-cloudflare\",\n \"node:minimal\": \"minimal-node\",\n \"node:react\": \"react-node\",\n};\n\n/**\n * Resolve the templates root. In a built CLI, examples are copied\n * to `dist/templates/<name>/` so the binary is self-contained\n * (preserving today's `package.json:files` shape). In dev (running\n * straight from `src/` via Node's strip-types) the same directory\n * doesn't exist, so we fall back to `examples/` three levels up\n * (`src/ → create-baerly-storage/ → packages/ → repo-root`).\n */\nconst resolveTemplatesRoot = (): string => {\n const here = dirname(fileURLToPath(import.meta.url));\n const distSidecar = resolve(here, \"templates\");\n if (existsSync(distSidecar)) {\n return distSidecar;\n }\n return resolve(here, \"..\", \"..\", \"..\", \"examples\");\n};\n\n/**\n * Resolve the add-ons root. In a built CLI, add-on trees are copied\n * to `dist/templates/addons/<name>/` next to the example templates.\n * In dev (running from `src/` via Node's strip-types) they live at\n * `packages/create-baerly-storage/templates/addons/<name>/`, one level up\n * from `src/`.\n */\nconst resolveAddonsRoot = (): string => {\n const here = dirname(fileURLToPath(import.meta.url));\n const distSidecar = resolve(here, \"templates\", \"addons\");\n if (existsSync(distSidecar)) {\n return distSidecar;\n }\n return resolve(here, \"..\", \"templates\", \"addons\");\n};\n\n/**\n * Read the CLI's own package.json:version. Used to rewrite\n * `workspace:*` dep specs to `^X.Y.Z` at copy time, since\n * `create-baerly-storage` ships in the same release train as `@baerly/*`.\n */\nconst readCliVersion = (): string => {\n const here = dirname(fileURLToPath(import.meta.url));\n // `src/scaffold.ts` and `dist/index.js` both sit one level under the\n // package root, so `../package.json` works for both.\n const pkgPath = resolve(here, \"..\", \"package.json\");\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf8\")) as { version?: string };\n if (typeof pkg.version !== \"string\" || pkg.version.length === 0) {\n throw new Error(`create-baerly-storage: could not read version from ${pkgPath}`);\n }\n return pkg.version;\n};\n\nconst DEFAULT_MANIFEST: ScaffoldManifest = {\n renames: [],\n excludePaths: [\".baerly/scaffold.json\"],\n excludeNames: [],\n dropDevDeps: [],\n copies: [],\n};\n\nconst loadManifest = (exampleRoot: string): ScaffoldManifest => {\n const p = join(exampleRoot, \".baerly\", \"scaffold.json\");\n if (!existsSync(p)) {\n return DEFAULT_MANIFEST;\n }\n const raw = JSON.parse(readFileSync(p, \"utf8\")) as Partial<ScaffoldManifest>;\n return {\n renames: raw.renames ?? [],\n excludePaths: raw.excludePaths ?? [\".baerly/scaffold.json\"],\n excludeNames: raw.excludeNames ?? [],\n dropDevDeps: raw.dropDevDeps ?? [],\n copies: raw.copies ?? [],\n };\n};\n\n/**\n * `excludeNames` supports both literal basenames (`node_modules`)\n * and `*.<ext>` suffix globs (`*.tsbuildinfo`). Split once per\n * scaffold; the walker calls `matchesExcludeName` per entry.\n */\nconst splitExcludeNames = (\n names: readonly string[],\n): { literals: Set<string>; suffixes: string[] } => {\n const literals = new Set<string>();\n const suffixes: string[] = [];\n for (const n of names) {\n if (n.startsWith(\"*.\")) {\n suffixes.push(n.slice(1));\n } else {\n literals.add(n);\n }\n }\n return { literals, suffixes };\n};\n\n/**\n * Walk the source example tree, apply manifest-driven rewrites, and\n * write to `outRoot/<projectName>/`. Returns the absolute output\n * directory and the relative list of files written.\n *\n * Refuses to overwrite an existing non-empty directory — fails\n * fast with a thrown Error. Callers catch and translate to the\n * CLI's exit-code contract.\n */\nexport const scaffold = async (opts: ScaffoldOptions): Promise<ScaffoldResult> => {\n if (opts.projectName.length === 0) {\n throw new Error(\"create-baerly-storage: projectName must be non-empty\");\n }\n // `\".\"` (exactly one character) is the sole sentinel for \"scaffold\n // into the current directory\" — matches `npm create vite@latest`\n // and `create-next-app`. `\"./\"`, `\"./foo\"`, `\"..\"`, etc. fall\n // through to the regex check below and are rejected like any other\n // invalid name.\n const inPlace = opts.projectName === \".\";\n // MUST mirror the regex in `prompts.ts:promptProjectName`.\n if (!inPlace && !/^[a-z0-9][a-z0-9_-]*$/.test(opts.projectName)) {\n throw new Error(\n `create-baerly-storage: projectName must be lowercase, alphanumeric + \"_\"/\"-\", starting with [a-z0-9] (got ${JSON.stringify(opts.projectName)})`,\n );\n }\n const pm = opts.pm ?? detectPm();\n const tenant = opts.tenant ?? \"default\";\n const domain = opts.domain ?? \"\";\n const templatesRoot = opts.templatesRoot ?? resolveTemplatesRoot();\n const outRoot = opts.outRoot ?? process.cwd();\n const outDir = inPlace ? resolve(outRoot) : resolve(outRoot, opts.projectName);\n // When scaffolding into the current directory, derive the\n // substitution sentinel (`appName`) from the directory's basename\n // and re-run it through the same regex — the value lands in\n // `package.json:name`, `wrangler.jsonc`, etc., which all require\n // an npm-package-shaped slug.\n const appName = inPlace ? basename(outDir) : opts.projectName;\n if (inPlace && !/^[a-z0-9][a-z0-9_-]*$/.test(appName)) {\n throw new Error(\n `create-baerly-storage: appName must be lowercase, alphanumeric + \"_\"/\"-\", starting with [a-z0-9] (got ${JSON.stringify(appName)}) — derived from current directory ${JSON.stringify(outDir)}`,\n );\n }\n const starter = opts.starter ?? \"minimal\";\n const lookupKey = `${opts.target}:${starter}`;\n const exampleName = STARTER_TO_EXAMPLE[lookupKey];\n const templateDir = exampleName === undefined ? \"\" : join(templatesRoot, exampleName);\n if (exampleName === undefined || !existsSync(templateDir)) {\n throw new Error(\n `create-baerly-storage: template not found for target=${opts.target} starter=${starter}`,\n );\n }\n\n const manifest = loadManifest(templateDir);\n\n // Resolve add-on directories up-front so the in-place collision\n // check below can see their top-level outputs too, and so an\n // unknown add-on fails fast before we start writing files.\n const addons = opts.withAddons ?? [];\n const addonsRoot = addons.length > 0 ? (opts.addonsRoot ?? resolveAddonsRoot()) : \"\";\n const addonDirs: string[] = [];\n for (const addon of addons) {\n const addonDir = join(addonsRoot, addon);\n if (!existsSync(addonDir)) {\n throw new Error(\n `create-baerly-storage: add-on directory not found: ${addonDir} (addon=${addon})`,\n );\n }\n addonDirs.push(addonDir);\n }\n\n if (existsSync(outDir)) {\n const entries = readdirSync(outDir);\n if (inPlace) {\n // Allow pre-existing files that don't collide with the scaffold:\n // a user's `.npmrc`, `mise.toml`, `.tool-versions`, etc. should\n // survive untouched. The allowlist (`.git`, `README.md`, …) is a\n // strict superset — those names are permitted even when the\n // scaffold also ships them (the scaffold overwrites).\n const wouldWrite = topLevelOutputs(templateDir, manifest, addonDirs);\n const colliding = entries.filter((e) => !SCAFFOLD_HERE_ALLOWLIST.has(e) && wouldWrite.has(e));\n if (colliding.length > 0) {\n throw new Error(\n `create-baerly-storage: ${outDir} contains files that would be overwritten: ${colliding.join(\", \")}. ` +\n `Move or remove these, then re-run.`,\n );\n }\n } else if (entries.length > 0) {\n throw new Error(`create-baerly-storage: ${outDir} exists and is non-empty`);\n }\n }\n\n const vars: Record<string, string> = {\n appName,\n tenant,\n domain,\n pm,\n installCmd: installCommand(pm),\n runDev: runCommand(pm, \"dev\"),\n runTypecheck: runCommand(pm, \"typecheck\"),\n };\n const ctx: SubstituteContext = { manifest, vars, cliVersion: readCliVersion() };\n\n const excluded = new Set(manifest.excludePaths.map((p) => p.split(\"/\").join(sep)));\n const isExcluded = (rel: string): boolean => excluded.has(rel);\n const { literals: excludeLiterals, suffixes: excludeSuffixes } = splitExcludeNames(\n manifest.excludeNames,\n );\n const matchesExcludeName = (name: string): boolean => {\n if (excludeLiterals.has(name)) {\n return true;\n }\n for (const suffix of excludeSuffixes) {\n if (name.endsWith(suffix)) {\n return true;\n }\n }\n return false;\n };\n\n const copyByFrom = new Map<string, string>(\n manifest.copies.map((c) => [c.from.split(\"/\").join(sep), c.to.split(\"/\").join(sep)]),\n );\n\n const filesWritten: string[] = [];\n const walk = (sourceDir: string, rel: string): void => {\n const from = join(sourceDir, rel);\n for (const ent of readdirSync(from)) {\n const fromEnt = join(from, ent);\n const relEnt = rel === \"\" ? ent : join(rel, ent);\n if (isExcluded(relEnt) || matchesExcludeName(ent)) {\n continue;\n }\n // `npm pack` strips `.gitignore` files from published tarballs\n // (it reads each one as an ignore-source control file and then\n // drops the file itself), so template trees ship `_gitignore`\n // and we rename on emit. Same trick as create-vite. Output\n // file name lives in `outName` / `relOut`; the source name\n // (`ent` / `relEnt`) is unchanged for read + manifest lookup.\n const outName = ent === \"_gitignore\" ? \".gitignore\" : ent;\n const relOut = rel === \"\" ? outName : join(rel, outName);\n const toEnt = join(outDir, relOut);\n if (statSync(fromEnt).isDirectory()) {\n mkdirSync(toEnt, { recursive: true });\n walk(sourceDir, relEnt);\n } else {\n const ext = ent.includes(\".\") ? ent.slice(ent.lastIndexOf(\".\")) : \"\";\n const isText = TEXT_EXTS.has(ext) || ent === \"Dockerfile\" || ent === \"_gitignore\";\n mkdirSync(dirname(toEnt), { recursive: true });\n if (ent === \"package.json\") {\n writeFileSync(toEnt, substitutePackageJson(readFileSync(fromEnt, \"utf8\"), ctx));\n } else if (isText) {\n writeFileSync(toEnt, substituteText(readFileSync(fromEnt, \"utf8\"), ctx));\n } else {\n writeFileSync(toEnt, readFileSync(fromEnt));\n }\n filesWritten.push(relOut);\n const copyTo = copyByFrom.get(relEnt);\n if (copyTo !== undefined) {\n const copyDest = join(outDir, copyTo);\n mkdirSync(dirname(copyDest), { recursive: true });\n writeFileSync(copyDest, substituteText(readFileSync(fromEnt, \"utf8\"), ctx));\n filesWritten.push(copyTo);\n }\n }\n }\n };\n walk(templateDir, \"\");\n\n // Layer requested add-ons on top of the base scaffold. Each add-on\n // directory was already resolved + existence-checked above so the\n // in-place collision guard could see its top-level outputs; here we\n // just walk them through the same substituter pass as the base\n // template (reusing the host's manifest so the appName sentinel\n // rewrite picks up any literal in the add-on files too).\n for (const addonDir of addonDirs) {\n walk(addonDir, \"\");\n }\n\n // When scaffolding into the current directory the user is already\n // sitting in `outDir`, so the `cd <projectName>` step would be a\n // no-op confusion. Drop it.\n const nextSteps = inPlace\n ? [installCommand(pm), runCommand(pm, \"dev\")]\n : [`cd ${opts.projectName}`, installCommand(pm), runCommand(pm, \"dev\")];\n return { outDir, filesWritten, nextSteps, cliVersion: ctx.cliVersion, appName };\n};\n","/**\n * Discriminator for {@link BaerlyError}. Strings (not subclasses) so they\n * survive cross-realm boundaries (e.g. a Web Worker) and so callers can\n * pattern-match with grep-friendly equality.\n */\nexport type BaerlyErrorCode =\n /** Caller-provided config or input is invalid (bad bucket, unsupported credential type, malformed URL, bucket not version-enabled when versioning was requested). */\n | \"InvalidConfig\"\n /** Generic S3/HTTP transport failure (5xx, unexpected status, retries exhausted). */\n | \"NetworkError\"\n /** S3 returned 403. Either credentials are wrong or the bucket policy denies the operation. */\n | \"AccessDenied\"\n /** Server returned data that didn't parse (malformed XML, non-JSON body where JSON expected). */\n | \"InvalidResponse\"\n /** Internal invariant violation — should not be reachable. File a bug. */\n | \"Internal\"\n /**\n * Document body failed schema validation. Emitted by the table-API\n * write verbs (`Collection.insert`, `Query.update`, `Collection.replace`) when\n * the body is not valid JSON or contains an array where\n * `DocumentValue` is required; also emitted when a collection has a\n * declared `SchemaValidator` (via `Db.create({ collections })`) and\n * the bound schema rejects the doc. In the schema-rejection case the\n * error carries an `issues` array describing each failure. HTTP layer\n * maps this to 400.\n */\n | \"SchemaError\"\n /**\n * Write conflicted with current state: CAS retry budget exhausted,\n * duplicate caller-supplied `_id`, or an already-existing guarded\n * storage key. Check `BaerlyError.retriable` to decide whether the\n * same logical operation should be retried.\n */\n | \"Conflict\"\n /**\n * `Verifier` returned no identity. HTTP server maps to 401.\n * Code is reserved here so the union locks.\n */\n | \"Unauthorized\"\n /**\n * The addressed resource does not exist. HTTP server maps to 404.\n * Emitted by the row-by-id read / update / delete handlers in\n * `packages/server/src/http/router.ts` when the predicate\n * `{ _id }` matches zero rows. Not a protocol invariant —\n * callers may retry after creating the resource or treat as a\n * miss depending on intent. The CLI maps this to the generic\n * exit-2 \"storage error\" bucket, not the exit-3 \"protocol\n * invariant\" bucket.\n */\n | \"NotFound\"\n /**\n * Request body exceeded the server's size cap. HTTP server maps\n * to 413. Cap is `MAX_BODY_BYTES` (1 MiB today; exported from\n * `packages/server/src/http/router.ts`). The Node adapter\n * enforces during the `node:http` stream pump so the process\n * never materializes a multi-MiB body; Workers also rely on\n * platform-side caps (16 MB free / 100 MB paid).\n */\n | \"PayloadTooLarge\"\n /**\n * A predicate is structurally well-formed but contradicts itself —\n * no document can match. Emitted by `validateWire` and\n * `mergePredicateWires`. Triggers:\n * - `{ clauses: [{op:\"in\", field:\"priority\", value:[]}] }` (empty `in` set)\n * - an `eq` clause with a value outside the residual interval\n * established by range clauses on the same field\n * - merging `{op:\"gt\", value:10}` with `{op:\"lt\", value:5}` on the\n * same field (empty interval)\n * - merging two `in` clauses on the same field with empty intersection\n *\n * Conflicting equality across clauses (`eq:\"open\"` + `eq:\"closed\"` on\n * the same field) surfaces as `InvalidConfig` rather than this code —\n * the merger treats it as a caller-side configuration bug, not an\n * algebraic contradiction.\n *\n * The HTTP layer treats this as a 400 (caller error). The distinct\n * code lets downstream code short-circuit empty-by-construction\n * without re-running the validator or parsing messages.\n */\n | \"UnsatisfiablePredicate\"\n /**\n * A `useQuery` callback awaited a recorder terminal\n * (`.get`/`.first`/`.all`/`.count`). The recorder runs once per\n * render to capture the chain shape; it cannot survive an `await`\n * because the proxy doesn't proxy across microtask boundaries. The\n * recorder's terminal returns a thenable whose `.then` throws this\n * error synchronously, converting what would otherwise be a silent\n * spinner-hang into a render-time error the hook surfaces as\n * `status: \"error\"`. Companion `baerly/no-await-in-use-query` lint\n * flags the pattern at edit time. For compound reads, use\n * `Promise.all` (parallel) or compose two `useQuery` calls with\n * `useQuery.skip` (dependent).\n */\n | \"UseQueryAwaitedRecorder\"\n /**\n * A write method (`.insert`/`.update`/`.replace`/`.delete`) was\n * called on the recorder inside a `useQuery` callback. Writes\n * inside reads are a programming error; the recorder rejects them\n * synchronously from the discovery pass, before any I/O fires. Use\n * `useMutation()` instead.\n */\n | \"UnexpectedWriteInQuery\"\n /**\n * A `useMutation()` callback rejected with a non-`BaerlyError`\n * throwable. The hook wraps the original throw under this code so\n * the `error` slot is always a `BaerlyError`; the original value\n * is preserved on `.cause`.\n */\n | \"MutationFailed\";\n\n/**\n * Runtime enumeration of every {@link BaerlyErrorCode}. The spec\n * generator and the drift gate iterate this to assert the IR lists\n * each code; the type guard in `spec/ir-schema.test.ts` fails tsgo if\n * this tuple and the union diverge. Keep order stable for deterministic\n * artifact diffs. This is the canonical code list — do not re-list\n * codes elsewhere (see RETRIABLE_CODES, the sibling retriable subset).\n */\nexport const ERROR_CODES = [\n \"InvalidConfig\",\n \"NetworkError\",\n \"AccessDenied\",\n \"InvalidResponse\",\n \"Internal\",\n \"SchemaError\",\n \"Conflict\",\n \"Unauthorized\",\n \"NotFound\",\n \"PayloadTooLarge\",\n \"UnsatisfiablePredicate\",\n \"UseQueryAwaitedRecorder\",\n \"UnexpectedWriteInQuery\",\n \"MutationFailed\",\n] as const satisfies readonly BaerlyErrorCode[];\n\n// Exhaustiveness guard: every union member must appear in ERROR_CODES.\n// If a code is added to BaerlyErrorCode without a tuple entry, this\n// errors at tsgo time (the union is not assignable to the tuple's union).\ntype _ErrorCodesExhaustive = [BaerlyErrorCode] extends [(typeof ERROR_CODES)[number]]\n ? true\n : [\"missing code in ERROR_CODES\", Exclude<BaerlyErrorCode, (typeof ERROR_CODES)[number]>];\n// eslint-disable-next-line no-underscore-dangle\nconst _errorCodesExhaustive: _ErrorCodesExhaustive = true;\nvoid _errorCodesExhaustive;\n\n/**\n * Codes whose default failure class is resolved by retrying with a fresh read.\n * Throw sites may override this when the same code is context-sensitive\n * (notably caller-supplied `_id` collisions, which also use `Conflict`).\n */\nexport const RETRIABLE_CODES: ReadonlySet<BaerlyErrorCode> = new Set<BaerlyErrorCode>([\n \"NetworkError\",\n \"Conflict\",\n]);\n\n/** True iff this error code's default failure class is retriable. */\nexport const isRetriableCode = (code: BaerlyErrorCode): boolean => RETRIABLE_CODES.has(code);\n\n/**\n * Codes raised only inside the client-side React runtime\n * (`useQuery` / `useMutation`); they never travel the HTTP wire, so the\n * machine-contract IR reports `httpStatus: null` for them — distinct\n * from a real `500` (a server-side transport/internal failure the HTTP\n * layer maps to a status). Sibling of {@link RETRIABLE_CODES}; add a\n * code here when a new client-only failure mode joins the union.\n */\nexport const CLIENT_RUNTIME_CODES: ReadonlySet<BaerlyErrorCode> = new Set<BaerlyErrorCode>([\n \"UseQueryAwaitedRecorder\",\n \"UnexpectedWriteInQuery\",\n \"MutationFailed\",\n]);\n\n/**\n * The single error class thrown by baerly-storage. Discriminate by `code`, not\n * `instanceof`: the code string survives `JSON.stringify` round-trips\n * across Worker / iframe / postMessage realm boundaries, where each\n * realm has its own `BaerlyError` constructor identity. IDB-restored\n * writes can replay across realms, so `instanceof` would spuriously\n * fail on a structurally-identical error from another realm.\n *\n * @example\n * ```ts\n * try {\n * await db.collection(\"tickets\").insert({ title: \"hi\" });\n * } catch (err) {\n * if (err instanceof BaerlyError && err.code === \"Conflict\") {\n * // Check err.retriable; CAS can retry, duplicate _id cannot.\n * }\n * throw err;\n * }\n * ```\n */\nexport class BaerlyError extends Error {\n readonly code: BaerlyErrorCode;\n override readonly cause?: unknown;\n /**\n * Structured field-path issues, set only when `code === \"SchemaError\"`.\n * Each entry's `path` is a dotted-key list (e.g. `[\"assignee\", \"team\"]`\n * or `[\"items\", 3, \"qty\"]`) that targets the offending field on the\n * input document. `message` is the validator-emitted human string.\n *\n * The HTTP layer's `mapError` renders these into the 400 body via\n * the existing `HttpErrorEnvelope`; older callers that don't know\n * about `issues` see a plain message-only error and stay correct.\n */\n readonly issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>;\n /**\n * Raw HTTP status, set only by the client-side wire decoder when\n * inflating an `HttpErrorEnvelope` into this class. Server-side\n * throws never set it (the HTTP layer's `mapError` derives the\n * outbound status from `code`). Useful for diagnostics — e.g. to\n * distinguish 404-as-\"no such row\" from 404-as-\"route not found\".\n * Discriminate by `code` for behavior; reach for `status` only when\n * you genuinely need the wire value.\n */\n readonly status?: number;\n /** Canonical corrective action; crosses the wire via `HttpErrorEnvelope.error.resolution`. */\n readonly resolution?: string;\n private readonly retriableOverride: boolean | undefined;\n\n /**\n * Whether this error instance is retriable. Defaults from `code`, but\n * context-sensitive throw sites can override it.\n */\n get retriable(): boolean {\n return this.retriableOverride ?? isRetriableCode(this.code);\n }\n\n constructor(\n code: BaerlyErrorCode,\n message: string,\n cause?: unknown,\n issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>,\n status?: number,\n resolution?: string,\n retriableOverride?: boolean,\n ) {\n super(message);\n this.name = \"BaerlyError\";\n this.code = code;\n this.cause = cause;\n this.retriableOverride = retriableOverride;\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (issues !== undefined) {\n this.issues = issues;\n }\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (status !== undefined) {\n this.status = status;\n }\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (resolution !== undefined) {\n this.resolution = resolution;\n }\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport function createScanner(text, ignoreTrivia = false) {\n const len = text.length;\n let pos = 0, value = '', tokenOffset = 0, token = 16 /* SyntaxKind.Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* ScanError.None */;\n function scanHexDigits(count, exact) {\n let digits = 0;\n let value = 0;\n while (digits < count || !exact) {\n let ch = text.charCodeAt(pos);\n if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) {\n value = value * 16 + ch - 48 /* CharacterCodes._0 */;\n }\n else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) {\n value = value * 16 + ch - 65 /* CharacterCodes.A */ + 10;\n }\n else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) {\n value = value * 16 + ch - 97 /* CharacterCodes.a */ + 10;\n }\n else {\n break;\n }\n pos++;\n digits++;\n }\n if (digits < count) {\n value = -1;\n }\n return value;\n }\n function setPosition(newPosition) {\n pos = newPosition;\n value = '';\n tokenOffset = 0;\n token = 16 /* SyntaxKind.Unknown */;\n scanError = 0 /* ScanError.None */;\n }\n function scanNumber() {\n let start = pos;\n if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) {\n pos++;\n }\n else {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) {\n pos++;\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n return text.substring(start, pos);\n }\n }\n let end = pos;\n if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) {\n pos++;\n if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) {\n pos++;\n }\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n end = pos;\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n }\n }\n return text.substring(start, end);\n }\n function scanString() {\n let result = '', start = pos;\n while (true) {\n if (pos >= len) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch = text.charCodeAt(pos);\n if (ch === 34 /* CharacterCodes.doubleQuote */) {\n result += text.substring(start, pos);\n pos++;\n break;\n }\n if (ch === 92 /* CharacterCodes.backslash */) {\n result += text.substring(start, pos);\n pos++;\n if (pos >= len) {\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch2 = text.charCodeAt(pos++);\n switch (ch2) {\n case 34 /* CharacterCodes.doubleQuote */:\n result += '\\\"';\n break;\n case 92 /* CharacterCodes.backslash */:\n result += '\\\\';\n break;\n case 47 /* CharacterCodes.slash */:\n result += '/';\n break;\n case 98 /* CharacterCodes.b */:\n result += '\\b';\n break;\n case 102 /* CharacterCodes.f */:\n result += '\\f';\n break;\n case 110 /* CharacterCodes.n */:\n result += '\\n';\n break;\n case 114 /* CharacterCodes.r */:\n result += '\\r';\n break;\n case 116 /* CharacterCodes.t */:\n result += '\\t';\n break;\n case 117 /* CharacterCodes.u */:\n const ch3 = scanHexDigits(4, true);\n if (ch3 >= 0) {\n result += String.fromCharCode(ch3);\n }\n else {\n scanError = 4 /* ScanError.InvalidUnicode */;\n }\n break;\n default:\n scanError = 5 /* ScanError.InvalidEscapeCharacter */;\n }\n start = pos;\n continue;\n }\n if (ch >= 0 && ch <= 0x1f) {\n if (isLineBreak(ch)) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n else {\n scanError = 6 /* ScanError.InvalidCharacter */;\n // mark as error but continue with string\n }\n }\n pos++;\n }\n return result;\n }\n function scanNext() {\n value = '';\n scanError = 0 /* ScanError.None */;\n tokenOffset = pos;\n lineStartOffset = lineNumber;\n prevTokenLineStartOffset = tokenLineStartOffset;\n if (pos >= len) {\n // at the end\n tokenOffset = len;\n return token = 17 /* SyntaxKind.EOF */;\n }\n let code = text.charCodeAt(pos);\n // trivia: whitespace\n if (isWhiteSpace(code)) {\n do {\n pos++;\n value += String.fromCharCode(code);\n code = text.charCodeAt(pos);\n } while (isWhiteSpace(code));\n return token = 15 /* SyntaxKind.Trivia */;\n }\n // trivia: newlines\n if (isLineBreak(code)) {\n pos++;\n value += String.fromCharCode(code);\n if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n value += '\\n';\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n return token = 14 /* SyntaxKind.LineBreakTrivia */;\n }\n switch (code) {\n // tokens: []{}:,\n case 123 /* CharacterCodes.openBrace */:\n pos++;\n return token = 1 /* SyntaxKind.OpenBraceToken */;\n case 125 /* CharacterCodes.closeBrace */:\n pos++;\n return token = 2 /* SyntaxKind.CloseBraceToken */;\n case 91 /* CharacterCodes.openBracket */:\n pos++;\n return token = 3 /* SyntaxKind.OpenBracketToken */;\n case 93 /* CharacterCodes.closeBracket */:\n pos++;\n return token = 4 /* SyntaxKind.CloseBracketToken */;\n case 58 /* CharacterCodes.colon */:\n pos++;\n return token = 6 /* SyntaxKind.ColonToken */;\n case 44 /* CharacterCodes.comma */:\n pos++;\n return token = 5 /* SyntaxKind.CommaToken */;\n // strings\n case 34 /* CharacterCodes.doubleQuote */:\n pos++;\n value = scanString();\n return token = 10 /* SyntaxKind.StringLiteral */;\n // comments\n case 47 /* CharacterCodes.slash */:\n const start = pos - 1;\n // Single-line comment\n if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n while (pos < len) {\n if (isLineBreak(text.charCodeAt(pos))) {\n break;\n }\n pos++;\n }\n value = text.substring(start, pos);\n return token = 12 /* SyntaxKind.LineCommentTrivia */;\n }\n // Multi-line comment\n if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) {\n pos += 2;\n const safeLength = len - 1; // For lookahead.\n let commentClosed = false;\n while (pos < safeLength) {\n const ch = text.charCodeAt(pos);\n if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n commentClosed = true;\n break;\n }\n pos++;\n if (isLineBreak(ch)) {\n if (ch === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n }\n }\n if (!commentClosed) {\n pos++;\n scanError = 1 /* ScanError.UnexpectedEndOfComment */;\n }\n value = text.substring(start, pos);\n return token = 13 /* SyntaxKind.BlockCommentTrivia */;\n }\n // just a single slash\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n // numbers\n case 45 /* CharacterCodes.minus */:\n value += String.fromCharCode(code);\n pos++;\n if (pos === len || !isDigit(text.charCodeAt(pos))) {\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // found a minus, followed by a number so\n // we fall through to proceed with scanning\n // numbers\n case 48 /* CharacterCodes._0 */:\n case 49 /* CharacterCodes._1 */:\n case 50 /* CharacterCodes._2 */:\n case 51 /* CharacterCodes._3 */:\n case 52 /* CharacterCodes._4 */:\n case 53 /* CharacterCodes._5 */:\n case 54 /* CharacterCodes._6 */:\n case 55 /* CharacterCodes._7 */:\n case 56 /* CharacterCodes._8 */:\n case 57 /* CharacterCodes._9 */:\n value += scanNumber();\n return token = 11 /* SyntaxKind.NumericLiteral */;\n // literals and unknown symbols\n default:\n // is a literal? Read the full word.\n while (pos < len && isUnknownContentCharacter(code)) {\n pos++;\n code = text.charCodeAt(pos);\n }\n if (tokenOffset !== pos) {\n value = text.substring(tokenOffset, pos);\n // keywords: true, false, null\n switch (value) {\n case 'true': return token = 8 /* SyntaxKind.TrueKeyword */;\n case 'false': return token = 9 /* SyntaxKind.FalseKeyword */;\n case 'null': return token = 7 /* SyntaxKind.NullKeyword */;\n }\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // some\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n }\n }\n function isUnknownContentCharacter(code) {\n if (isWhiteSpace(code) || isLineBreak(code)) {\n return false;\n }\n switch (code) {\n case 125 /* CharacterCodes.closeBrace */:\n case 93 /* CharacterCodes.closeBracket */:\n case 123 /* CharacterCodes.openBrace */:\n case 91 /* CharacterCodes.openBracket */:\n case 34 /* CharacterCodes.doubleQuote */:\n case 58 /* CharacterCodes.colon */:\n case 44 /* CharacterCodes.comma */:\n case 47 /* CharacterCodes.slash */:\n return false;\n }\n return true;\n }\n function scanNextNonTrivia() {\n let result;\n do {\n result = scanNext();\n } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */);\n return result;\n }\n return {\n setPosition: setPosition,\n getPosition: () => pos,\n scan: ignoreTrivia ? scanNextNonTrivia : scanNext,\n getToken: () => token,\n getTokenValue: () => value,\n getTokenOffset: () => tokenOffset,\n getTokenLength: () => pos - tokenOffset,\n getTokenStartLine: () => lineStartOffset,\n getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,\n getTokenError: () => scanError,\n };\n}\nfunction isWhiteSpace(ch) {\n return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */;\n}\nfunction isLineBreak(ch) {\n return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */;\n}\nfunction isDigit(ch) {\n return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */;\n}\nvar CharacterCodes;\n(function (CharacterCodes) {\n CharacterCodes[CharacterCodes[\"lineFeed\"] = 10] = \"lineFeed\";\n CharacterCodes[CharacterCodes[\"carriageReturn\"] = 13] = \"carriageReturn\";\n CharacterCodes[CharacterCodes[\"space\"] = 32] = \"space\";\n CharacterCodes[CharacterCodes[\"_0\"] = 48] = \"_0\";\n CharacterCodes[CharacterCodes[\"_1\"] = 49] = \"_1\";\n CharacterCodes[CharacterCodes[\"_2\"] = 50] = \"_2\";\n CharacterCodes[CharacterCodes[\"_3\"] = 51] = \"_3\";\n CharacterCodes[CharacterCodes[\"_4\"] = 52] = \"_4\";\n CharacterCodes[CharacterCodes[\"_5\"] = 53] = \"_5\";\n CharacterCodes[CharacterCodes[\"_6\"] = 54] = \"_6\";\n CharacterCodes[CharacterCodes[\"_7\"] = 55] = \"_7\";\n CharacterCodes[CharacterCodes[\"_8\"] = 56] = \"_8\";\n CharacterCodes[CharacterCodes[\"_9\"] = 57] = \"_9\";\n CharacterCodes[CharacterCodes[\"a\"] = 97] = \"a\";\n CharacterCodes[CharacterCodes[\"b\"] = 98] = \"b\";\n CharacterCodes[CharacterCodes[\"c\"] = 99] = \"c\";\n CharacterCodes[CharacterCodes[\"d\"] = 100] = \"d\";\n CharacterCodes[CharacterCodes[\"e\"] = 101] = \"e\";\n CharacterCodes[CharacterCodes[\"f\"] = 102] = \"f\";\n CharacterCodes[CharacterCodes[\"g\"] = 103] = \"g\";\n CharacterCodes[CharacterCodes[\"h\"] = 104] = \"h\";\n CharacterCodes[CharacterCodes[\"i\"] = 105] = \"i\";\n CharacterCodes[CharacterCodes[\"j\"] = 106] = \"j\";\n CharacterCodes[CharacterCodes[\"k\"] = 107] = \"k\";\n CharacterCodes[CharacterCodes[\"l\"] = 108] = \"l\";\n CharacterCodes[CharacterCodes[\"m\"] = 109] = \"m\";\n CharacterCodes[CharacterCodes[\"n\"] = 110] = \"n\";\n CharacterCodes[CharacterCodes[\"o\"] = 111] = \"o\";\n CharacterCodes[CharacterCodes[\"p\"] = 112] = \"p\";\n CharacterCodes[CharacterCodes[\"q\"] = 113] = \"q\";\n CharacterCodes[CharacterCodes[\"r\"] = 114] = \"r\";\n CharacterCodes[CharacterCodes[\"s\"] = 115] = \"s\";\n CharacterCodes[CharacterCodes[\"t\"] = 116] = \"t\";\n CharacterCodes[CharacterCodes[\"u\"] = 117] = \"u\";\n CharacterCodes[CharacterCodes[\"v\"] = 118] = \"v\";\n CharacterCodes[CharacterCodes[\"w\"] = 119] = \"w\";\n CharacterCodes[CharacterCodes[\"x\"] = 120] = \"x\";\n CharacterCodes[CharacterCodes[\"y\"] = 121] = \"y\";\n CharacterCodes[CharacterCodes[\"z\"] = 122] = \"z\";\n CharacterCodes[CharacterCodes[\"A\"] = 65] = \"A\";\n CharacterCodes[CharacterCodes[\"B\"] = 66] = \"B\";\n CharacterCodes[CharacterCodes[\"C\"] = 67] = \"C\";\n CharacterCodes[CharacterCodes[\"D\"] = 68] = \"D\";\n CharacterCodes[CharacterCodes[\"E\"] = 69] = \"E\";\n CharacterCodes[CharacterCodes[\"F\"] = 70] = \"F\";\n CharacterCodes[CharacterCodes[\"G\"] = 71] = \"G\";\n CharacterCodes[CharacterCodes[\"H\"] = 72] = \"H\";\n CharacterCodes[CharacterCodes[\"I\"] = 73] = \"I\";\n CharacterCodes[CharacterCodes[\"J\"] = 74] = \"J\";\n CharacterCodes[CharacterCodes[\"K\"] = 75] = \"K\";\n CharacterCodes[CharacterCodes[\"L\"] = 76] = \"L\";\n CharacterCodes[CharacterCodes[\"M\"] = 77] = \"M\";\n CharacterCodes[CharacterCodes[\"N\"] = 78] = \"N\";\n CharacterCodes[CharacterCodes[\"O\"] = 79] = \"O\";\n CharacterCodes[CharacterCodes[\"P\"] = 80] = \"P\";\n CharacterCodes[CharacterCodes[\"Q\"] = 81] = \"Q\";\n CharacterCodes[CharacterCodes[\"R\"] = 82] = \"R\";\n CharacterCodes[CharacterCodes[\"S\"] = 83] = \"S\";\n CharacterCodes[CharacterCodes[\"T\"] = 84] = \"T\";\n CharacterCodes[CharacterCodes[\"U\"] = 85] = \"U\";\n CharacterCodes[CharacterCodes[\"V\"] = 86] = \"V\";\n CharacterCodes[CharacterCodes[\"W\"] = 87] = \"W\";\n CharacterCodes[CharacterCodes[\"X\"] = 88] = \"X\";\n CharacterCodes[CharacterCodes[\"Y\"] = 89] = \"Y\";\n CharacterCodes[CharacterCodes[\"Z\"] = 90] = \"Z\";\n CharacterCodes[CharacterCodes[\"asterisk\"] = 42] = \"asterisk\";\n CharacterCodes[CharacterCodes[\"backslash\"] = 92] = \"backslash\";\n CharacterCodes[CharacterCodes[\"closeBrace\"] = 125] = \"closeBrace\";\n CharacterCodes[CharacterCodes[\"closeBracket\"] = 93] = \"closeBracket\";\n CharacterCodes[CharacterCodes[\"colon\"] = 58] = \"colon\";\n CharacterCodes[CharacterCodes[\"comma\"] = 44] = \"comma\";\n CharacterCodes[CharacterCodes[\"dot\"] = 46] = \"dot\";\n CharacterCodes[CharacterCodes[\"doubleQuote\"] = 34] = \"doubleQuote\";\n CharacterCodes[CharacterCodes[\"minus\"] = 45] = \"minus\";\n CharacterCodes[CharacterCodes[\"openBrace\"] = 123] = \"openBrace\";\n CharacterCodes[CharacterCodes[\"openBracket\"] = 91] = \"openBracket\";\n CharacterCodes[CharacterCodes[\"plus\"] = 43] = \"plus\";\n CharacterCodes[CharacterCodes[\"slash\"] = 47] = \"slash\";\n CharacterCodes[CharacterCodes[\"formFeed\"] = 12] = \"formFeed\";\n CharacterCodes[CharacterCodes[\"tab\"] = 9] = \"tab\";\n})(CharacterCodes || (CharacterCodes = {}));\n","export const cachedSpaces = new Array(20).fill(0).map((_, index) => {\n return ' '.repeat(index);\n});\nconst maxCachedValues = 200;\nexport const cachedBreakLinesWithSpaces = {\n ' ': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + ' '.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + ' '.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + ' '.repeat(index);\n }),\n },\n '\\t': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + '\\t'.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + '\\t'.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + '\\t'.repeat(index);\n }),\n }\n};\nexport const supportedEols = ['\\n', '\\r', '\\r\\n'];\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport { createScanner } from './scanner';\nimport { cachedSpaces, cachedBreakLinesWithSpaces, supportedEols } from './string-intern';\nexport function format(documentText, range, options) {\n let initialIndentLevel;\n let formatText;\n let formatTextStart;\n let rangeStart;\n let rangeEnd;\n if (range) {\n rangeStart = range.offset;\n rangeEnd = rangeStart + range.length;\n formatTextStart = rangeStart;\n while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {\n formatTextStart--;\n }\n let endOffset = rangeEnd;\n while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {\n endOffset++;\n }\n formatText = documentText.substring(formatTextStart, endOffset);\n initialIndentLevel = computeIndentLevel(formatText, options);\n }\n else {\n formatText = documentText;\n initialIndentLevel = 0;\n formatTextStart = 0;\n rangeStart = 0;\n rangeEnd = documentText.length;\n }\n const eol = getEOL(options, documentText);\n const eolFastPathSupported = supportedEols.includes(eol);\n let numberLineBreaks = 0;\n let indentLevel = 0;\n let indentValue;\n if (options.insertSpaces) {\n indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4);\n }\n else {\n indentValue = '\\t';\n }\n const indentType = indentValue === '\\t' ? '\\t' : ' ';\n let scanner = createScanner(formatText, false);\n let hasError = false;\n function newLinesAndIndent() {\n if (numberLineBreaks > 1) {\n return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);\n }\n const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);\n if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) {\n return eol + repeat(indentValue, initialIndentLevel + indentLevel);\n }\n if (amountOfSpaces <= 0) {\n return eol;\n }\n return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];\n }\n function scanNext() {\n let token = scanner.scan();\n numberLineBreaks = 0;\n while (token === 15 /* SyntaxKind.Trivia */ || token === 14 /* SyntaxKind.LineBreakTrivia */) {\n if (token === 14 /* SyntaxKind.LineBreakTrivia */ && options.keepLines) {\n numberLineBreaks += 1;\n }\n else if (token === 14 /* SyntaxKind.LineBreakTrivia */) {\n numberLineBreaks = 1;\n }\n token = scanner.scan();\n }\n hasError = token === 16 /* SyntaxKind.Unknown */ || scanner.getTokenError() !== 0 /* ScanError.None */;\n return token;\n }\n const editOperations = [];\n function addEdit(text, startOffset, endOffset) {\n if (!hasError && (!range || (startOffset < rangeEnd && endOffset > rangeStart)) && documentText.substring(startOffset, endOffset) !== text) {\n editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });\n }\n }\n let firstToken = scanNext();\n if (options.keepLines && numberLineBreaks > 0) {\n addEdit(repeat(eol, numberLineBreaks), 0, 0);\n }\n if (firstToken !== 17 /* SyntaxKind.EOF */) {\n let firstTokenStart = scanner.getTokenOffset() + formatTextStart;\n let initialIndent = (indentValue.length * initialIndentLevel < 20) && options.insertSpaces\n ? cachedSpaces[indentValue.length * initialIndentLevel]\n : repeat(indentValue, initialIndentLevel);\n addEdit(initialIndent, formatTextStart, firstTokenStart);\n }\n while (firstToken !== 17 /* SyntaxKind.EOF */) {\n let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;\n let secondToken = scanNext();\n let replaceContent = '';\n let needsLineBreak = false;\n while (numberLineBreaks === 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) {\n let commentTokenStart = scanner.getTokenOffset() + formatTextStart;\n addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);\n firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;\n needsLineBreak = secondToken === 12 /* SyntaxKind.LineCommentTrivia */;\n replaceContent = needsLineBreak ? newLinesAndIndent() : '';\n secondToken = scanNext();\n }\n if (secondToken === 2 /* SyntaxKind.CloseBraceToken */) {\n if (firstToken !== 1 /* SyntaxKind.OpenBraceToken */) {\n indentLevel--;\n }\n ;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1 /* SyntaxKind.OpenBraceToken */) {\n replaceContent = newLinesAndIndent();\n }\n else if (options.keepLines) {\n replaceContent = cachedSpaces[1];\n }\n }\n else if (secondToken === 4 /* SyntaxKind.CloseBracketToken */) {\n if (firstToken !== 3 /* SyntaxKind.OpenBracketToken */) {\n indentLevel--;\n }\n ;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3 /* SyntaxKind.OpenBracketToken */) {\n replaceContent = newLinesAndIndent();\n }\n else if (options.keepLines) {\n replaceContent = cachedSpaces[1];\n }\n }\n else {\n switch (firstToken) {\n case 3 /* SyntaxKind.OpenBracketToken */:\n case 1 /* SyntaxKind.OpenBraceToken */:\n indentLevel++;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 5 /* SyntaxKind.CommaToken */:\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 12 /* SyntaxKind.LineCommentTrivia */:\n replaceContent = newLinesAndIndent();\n break;\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n if (numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (!needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 6 /* SyntaxKind.ColonToken */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (!needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 10 /* SyntaxKind.StringLiteral */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (secondToken === 6 /* SyntaxKind.ColonToken */ && !needsLineBreak) {\n replaceContent = '';\n }\n break;\n case 7 /* SyntaxKind.NullKeyword */:\n case 8 /* SyntaxKind.TrueKeyword */:\n case 9 /* SyntaxKind.FalseKeyword */:\n case 11 /* SyntaxKind.NumericLiteral */:\n case 2 /* SyntaxKind.CloseBraceToken */:\n case 4 /* SyntaxKind.CloseBracketToken */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else {\n if ((secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */) && !needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n else if (secondToken !== 5 /* SyntaxKind.CommaToken */ && secondToken !== 17 /* SyntaxKind.EOF */) {\n hasError = true;\n }\n }\n break;\n case 16 /* SyntaxKind.Unknown */:\n hasError = true;\n break;\n }\n if (numberLineBreaks > 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) {\n replaceContent = newLinesAndIndent();\n }\n }\n if (secondToken === 17 /* SyntaxKind.EOF */) {\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = options.insertFinalNewline ? eol : '';\n }\n }\n const secondTokenStart = scanner.getTokenOffset() + formatTextStart;\n addEdit(replaceContent, firstTokenEnd, secondTokenStart);\n firstToken = secondToken;\n }\n return editOperations;\n}\nfunction repeat(s, count) {\n let result = '';\n for (let i = 0; i < count; i++) {\n result += s;\n }\n return result;\n}\nfunction computeIndentLevel(content, options) {\n let i = 0;\n let nChars = 0;\n const tabSize = options.tabSize || 4;\n while (i < content.length) {\n let ch = content.charAt(i);\n if (ch === cachedSpaces[1]) {\n nChars++;\n }\n else if (ch === '\\t') {\n nChars += tabSize;\n }\n else {\n break;\n }\n i++;\n }\n return Math.floor(nChars / tabSize);\n}\nfunction getEOL(options, text) {\n for (let i = 0; i < text.length; i++) {\n const ch = text.charAt(i);\n if (ch === '\\r') {\n if (i + 1 < text.length && text.charAt(i + 1) === '\\n') {\n return '\\r\\n';\n }\n return '\\r';\n }\n else if (ch === '\\n') {\n return '\\n';\n }\n }\n return (options && options.eol) || '\\n';\n}\nexport function isEOL(text, offset) {\n return '\\r\\n'.indexOf(text.charAt(offset)) !== -1;\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport { createScanner } from './scanner';\nvar ParseOptions;\n(function (ParseOptions) {\n ParseOptions.DEFAULT = {\n allowTrailingComma: false\n };\n})(ParseOptions || (ParseOptions = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport function getLocation(text, position) {\n const segments = []; // strings or numbers\n const earlyReturnException = new Object();\n let previousNode = undefined;\n const previousNodeInst = {\n value: {},\n offset: 0,\n length: 0,\n type: 'object',\n parent: undefined\n };\n let isAtPropertyKey = false;\n function setPreviousNode(value, offset, length, type) {\n previousNodeInst.value = value;\n previousNodeInst.offset = offset;\n previousNodeInst.length = length;\n previousNodeInst.type = type;\n previousNodeInst.colonOffset = undefined;\n previousNode = previousNodeInst;\n }\n try {\n visit(text, {\n onObjectBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n isAtPropertyKey = position > offset;\n segments.push(''); // push a placeholder (will be replaced)\n },\n onObjectProperty: (name, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(name, offset, length, 'property');\n segments[segments.length - 1] = name;\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onObjectEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onArrayBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.push(0);\n },\n onArrayEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onLiteralValue: (value, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(value, offset, length, getNodeType(value));\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onSeparator: (sep, offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n if (sep === ':' && previousNode && previousNode.type === 'property') {\n previousNode.colonOffset = offset;\n isAtPropertyKey = false;\n previousNode = undefined;\n }\n else if (sep === ',') {\n const last = segments[segments.length - 1];\n if (typeof last === 'number') {\n segments[segments.length - 1] = last + 1;\n }\n else {\n isAtPropertyKey = true;\n segments[segments.length - 1] = '';\n }\n previousNode = undefined;\n }\n }\n });\n }\n catch (e) {\n if (e !== earlyReturnException) {\n throw e;\n }\n }\n return {\n path: segments,\n previousNode,\n isAtPropertyKey,\n matches: (pattern) => {\n let k = 0;\n for (let i = 0; k < pattern.length && i < segments.length; i++) {\n if (pattern[k] === segments[i] || pattern[k] === '*') {\n k++;\n }\n else if (pattern[k] !== '**') {\n return false;\n }\n }\n return k === pattern.length;\n }\n };\n}\n/**\n * 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.\n * Therefore always check the errors list to find out if the input was valid.\n */\nexport function parse(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentProperty = null;\n let currentParent = [];\n const previousParents = [];\n function onValue(value) {\n if (Array.isArray(currentParent)) {\n currentParent.push(value);\n }\n else if (currentProperty !== null) {\n currentParent[currentProperty] = value;\n }\n }\n const visitor = {\n onObjectBegin: () => {\n const object = {};\n onValue(object);\n previousParents.push(currentParent);\n currentParent = object;\n currentProperty = null;\n },\n onObjectProperty: (name) => {\n currentProperty = name;\n },\n onObjectEnd: () => {\n currentParent = previousParents.pop();\n },\n onArrayBegin: () => {\n const array = [];\n onValue(array);\n previousParents.push(currentParent);\n currentParent = array;\n currentProperty = null;\n },\n onArrayEnd: () => {\n currentParent = previousParents.pop();\n },\n onLiteralValue: onValue,\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n return currentParent[0];\n}\n/**\n * 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.\n */\nexport function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n const visitor = {\n onObjectBegin: (offset) => {\n currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: (name, offset, length) => {\n currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent });\n },\n onObjectEnd: (offset, length) => {\n ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: (offset, length) => {\n currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: (offset, length) => {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: (value, offset, length) => {\n onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: (sep, offset, length) => {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.colonOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n const result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n}\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport function findNodeAtLocation(root, path) {\n if (!root) {\n return undefined;\n }\n let node = root;\n for (let segment of path) {\n if (typeof segment === 'string') {\n if (node.type !== 'object' || !Array.isArray(node.children)) {\n return undefined;\n }\n let found = false;\n for (const propertyNode of node.children) {\n if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {\n node = propertyNode.children[1];\n found = true;\n break;\n }\n }\n if (!found) {\n return undefined;\n }\n }\n else {\n const index = segment;\n if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {\n return undefined;\n }\n node = node.children[index];\n }\n }\n return node;\n}\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport function getNodePath(node) {\n if (!node.parent || !node.parent.children) {\n return [];\n }\n const path = getNodePath(node.parent);\n if (node.parent.type === 'property') {\n const key = node.parent.children[0].value;\n path.push(key);\n }\n else if (node.parent.type === 'array') {\n const index = node.parent.children.indexOf(node);\n if (index !== -1) {\n path.push(index);\n }\n }\n return path;\n}\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport function getNodeValue(node) {\n switch (node.type) {\n case 'array':\n return node.children.map(getNodeValue);\n case 'object':\n const obj = Object.create(null);\n for (let prop of node.children) {\n const valueNode = prop.children[1];\n if (valueNode) {\n obj[prop.children[0].value] = getNodeValue(valueNode);\n }\n }\n return obj;\n case 'null':\n case 'string':\n case 'number':\n case 'boolean':\n return node.value;\n default:\n return undefined;\n }\n}\nexport function contains(node, offset, includeRightBound = false) {\n return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));\n}\n/**\n * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport function findNodeAtOffset(node, offset, includeRightBound = false) {\n if (contains(node, offset, includeRightBound)) {\n const children = node.children;\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length && children[i].offset <= offset; i++) {\n const item = findNodeAtOffset(children[i], offset, includeRightBound);\n if (item) {\n return item;\n }\n }\n }\n return node;\n }\n return undefined;\n}\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport function visit(text, visitor, options = ParseOptions.DEFAULT) {\n const _scanner = createScanner(text, false);\n // Important: Only pass copies of this to visitor functions to prevent accidental modification, and\n // to not affect visitor functions which stored a reference to a previous JSONPath\n const _jsonPath = [];\n // Depth of onXXXBegin() callbacks suppressed. onXXXEnd() decrements this if it isn't 0 already.\n // Callbacks are only called when this value is 0.\n let suppressedCallbacks = 0;\n function toNoArgVisit(visitFunction) {\n return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisit(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisitWithPath(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;\n }\n function toBeginVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks++;\n }\n else {\n let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());\n if (cbReturn === false) {\n suppressedCallbacks = 1;\n }\n }\n }\n : () => true;\n }\n function toEndVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks--;\n }\n if (suppressedCallbacks === 0) {\n visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());\n }\n }\n : () => true;\n }\n 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);\n const disallowComments = options && options.disallowComments;\n const allowTrailingComma = options && options.allowTrailingComma;\n function scanNext() {\n while (true) {\n const token = _scanner.scan();\n switch (_scanner.getTokenError()) {\n case 4 /* ScanError.InvalidUnicode */:\n handleError(14 /* ParseErrorCode.InvalidUnicode */);\n break;\n case 5 /* ScanError.InvalidEscapeCharacter */:\n handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */);\n break;\n case 3 /* ScanError.UnexpectedEndOfNumber */:\n handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */);\n break;\n case 1 /* ScanError.UnexpectedEndOfComment */:\n if (!disallowComments) {\n handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */);\n }\n break;\n case 2 /* ScanError.UnexpectedEndOfString */:\n handleError(12 /* ParseErrorCode.UnexpectedEndOfString */);\n break;\n case 6 /* ScanError.InvalidCharacter */:\n handleError(16 /* ParseErrorCode.InvalidCharacter */);\n break;\n }\n switch (token) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n if (disallowComments) {\n handleError(10 /* ParseErrorCode.InvalidCommentToken */);\n }\n else {\n onComment();\n }\n break;\n case 16 /* SyntaxKind.Unknown */:\n handleError(1 /* ParseErrorCode.InvalidSymbol */);\n break;\n case 15 /* SyntaxKind.Trivia */:\n case 14 /* SyntaxKind.LineBreakTrivia */:\n break;\n default:\n return token;\n }\n }\n }\n function handleError(error, skipUntilAfter = [], skipUntil = []) {\n onError(error);\n if (skipUntilAfter.length + skipUntil.length > 0) {\n let token = _scanner.getToken();\n while (token !== 17 /* SyntaxKind.EOF */) {\n if (skipUntilAfter.indexOf(token) !== -1) {\n scanNext();\n break;\n }\n else if (skipUntil.indexOf(token) !== -1) {\n break;\n }\n token = scanNext();\n }\n }\n }\n function parseString(isValue) {\n const value = _scanner.getTokenValue();\n if (isValue) {\n onLiteralValue(value);\n }\n else {\n onObjectProperty(value);\n // add property name afterwards\n _jsonPath.push(value);\n }\n scanNext();\n return true;\n }\n function parseLiteral() {\n switch (_scanner.getToken()) {\n case 11 /* SyntaxKind.NumericLiteral */:\n const tokenValue = _scanner.getTokenValue();\n let value = Number(tokenValue);\n if (isNaN(value)) {\n handleError(2 /* ParseErrorCode.InvalidNumberFormat */);\n value = 0;\n }\n onLiteralValue(value);\n break;\n case 7 /* SyntaxKind.NullKeyword */:\n onLiteralValue(null);\n break;\n case 8 /* SyntaxKind.TrueKeyword */:\n onLiteralValue(true);\n break;\n case 9 /* SyntaxKind.FalseKeyword */:\n onLiteralValue(false);\n break;\n default:\n return false;\n }\n scanNext();\n return true;\n }\n function parseProperty() {\n if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) {\n handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n return false;\n }\n parseString(false);\n if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) {\n onSeparator(':');\n scanNext(); // consume colon\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n }\n else {\n handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n _jsonPath.pop(); // remove processed property name\n return true;\n }\n function parseObject() {\n onObjectBegin();\n scanNext(); // consume open brace\n let needsComma = false;\n while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (!parseProperty()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onObjectEnd();\n if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) {\n handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []);\n }\n else {\n scanNext(); // consume close brace\n }\n return true;\n }\n function parseArray() {\n onArrayBegin();\n scanNext(); // consume open bracket\n let isFirstElement = true;\n let needsComma = false;\n while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (isFirstElement) {\n _jsonPath.push(0);\n isFirstElement = false;\n }\n else {\n _jsonPath[_jsonPath.length - 1]++;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onArrayEnd();\n if (!isFirstElement) {\n _jsonPath.pop(); // remove array index\n }\n if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) {\n handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []);\n }\n else {\n scanNext(); // consume close bracket\n }\n return true;\n }\n function parseValue() {\n switch (_scanner.getToken()) {\n case 3 /* SyntaxKind.OpenBracketToken */:\n return parseArray();\n case 1 /* SyntaxKind.OpenBraceToken */:\n return parseObject();\n case 10 /* SyntaxKind.StringLiteral */:\n return parseString(true);\n default:\n return parseLiteral();\n }\n }\n scanNext();\n if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) {\n if (options.allowEmptyContent) {\n return true;\n }\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []);\n }\n return true;\n}\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport function stripComments(text, replaceCh) {\n let _scanner = createScanner(text), parts = [], kind, offset = 0, pos;\n do {\n pos = _scanner.getPosition();\n kind = _scanner.scan();\n switch (kind) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n case 17 /* SyntaxKind.EOF */:\n if (offset !== pos) {\n parts.push(text.substring(offset, pos));\n }\n if (replaceCh !== undefined) {\n parts.push(_scanner.getTokenValue().replace(/[^\\r\\n]/g, replaceCh));\n }\n offset = _scanner.getPosition();\n break;\n }\n } while (kind !== 17 /* SyntaxKind.EOF */);\n return parts.join('');\n}\nexport function getNodeType(value) {\n switch (typeof value) {\n case 'boolean': return 'boolean';\n case 'number': return 'number';\n case 'string': return 'string';\n case 'object': {\n if (!value) {\n return 'null';\n }\n else if (Array.isArray(value)) {\n return 'array';\n }\n return 'object';\n }\n default: return 'null';\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport { format, isEOL } from './format';\nimport { parseTree, findNodeAtLocation } from './parser';\nexport function removeProperty(text, path, options) {\n return setProperty(text, path, void 0, options);\n}\nexport function setProperty(text, originalPath, value, options) {\n const path = originalPath.slice();\n const errors = [];\n const root = parseTree(text, errors);\n let parent = void 0;\n let lastSegment = void 0;\n while (path.length > 0) {\n lastSegment = path.pop();\n parent = findNodeAtLocation(root, path);\n if (parent === void 0 && value !== void 0) {\n if (typeof lastSegment === 'string') {\n value = { [lastSegment]: value };\n }\n else {\n value = [value];\n }\n }\n else {\n break;\n }\n }\n if (!parent) {\n // empty document\n if (value === void 0) { // delete\n throw new Error('Can not delete in empty document');\n }\n return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);\n }\n else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {\n const existing = findNodeAtLocation(parent, [lastSegment]);\n if (existing !== void 0) {\n if (value === void 0) { // delete\n if (!existing.parent) {\n throw new Error('Malformed AST');\n }\n const propertyIndex = parent.children.indexOf(existing.parent);\n let removeBegin;\n let removeEnd = existing.parent.offset + existing.parent.length;\n if (propertyIndex > 0) {\n // remove the comma of the previous node\n let previous = parent.children[propertyIndex - 1];\n removeBegin = previous.offset + previous.length;\n }\n else {\n removeBegin = parent.offset + 1;\n if (parent.children.length > 1) {\n // remove the comma of the next node\n let next = parent.children[1];\n removeEnd = next.offset;\n }\n }\n return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options);\n }\n else {\n // set value of existing property\n return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);\n }\n }\n else {\n if (value === void 0) { // delete\n return []; // property does not exist, nothing to do\n }\n const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;\n const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(p => p.children[0].value)) : parent.children.length;\n let edit;\n if (index > 0) {\n let previous = parent.children[index - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n else if (parent.children.length === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty };\n }\n else {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };\n }\n return withFormatting(text, edit, options);\n }\n }\n else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {\n const insertIndex = lastSegment;\n if (insertIndex === -1) {\n // Insert\n const newProperty = `${JSON.stringify(value)}`;\n let edit;\n if (parent.children.length === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty };\n }\n else {\n const previous = parent.children[parent.children.length - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n return withFormatting(text, edit, options);\n }\n else if (value === void 0 && parent.children.length >= 0) {\n // Removal\n const removalIndex = lastSegment;\n const toRemove = parent.children[removalIndex];\n let edit;\n if (parent.children.length === 1) {\n // only item\n edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };\n }\n else if (parent.children.length - 1 === removalIndex) {\n // last item\n let previous = parent.children[removalIndex - 1];\n let offset = previous.offset + previous.length;\n let parentEndOffset = parent.offset + parent.length;\n edit = { offset, length: parentEndOffset - 2 - offset, content: '' };\n }\n else {\n edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };\n }\n return withFormatting(text, edit, options);\n }\n else if (value !== void 0) {\n let edit;\n const newProperty = `${JSON.stringify(value)}`;\n if (!options.isArrayInsertion && parent.children.length > lastSegment) {\n const toModify = parent.children[lastSegment];\n edit = { offset: toModify.offset, length: toModify.length, content: newProperty };\n }\n else if (parent.children.length === 0 || lastSegment === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' };\n }\n else {\n const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;\n const previous = parent.children[index - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n return withFormatting(text, edit, options);\n }\n else {\n throw new Error(`Can not ${value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')} Array index ${insertIndex} as length is not sufficient`);\n }\n }\n else {\n throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`);\n }\n}\nfunction withFormatting(text, edit, options) {\n if (!options.formattingOptions) {\n return [edit];\n }\n // apply the edit\n let newText = applyEdit(text, edit);\n // format the new text\n let begin = edit.offset;\n let end = edit.offset + edit.content.length;\n if (edit.length === 0 || edit.content.length === 0) { // insert or remove\n while (begin > 0 && !isEOL(newText, begin - 1)) {\n begin--;\n }\n while (end < newText.length && !isEOL(newText, end)) {\n end++;\n }\n }\n const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false });\n // apply the formatting edits and track the begin and end offsets of the changes\n for (let i = edits.length - 1; i >= 0; i--) {\n const edit = edits[i];\n newText = applyEdit(newText, edit);\n begin = Math.min(begin, edit.offset);\n end = Math.max(end, edit.offset + edit.length);\n end += edit.content.length - edit.length;\n }\n // create a single edit with all changes\n const editLength = text.length - (newText.length - end) - begin;\n return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];\n}\nexport function applyEdit(text, edit) {\n return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);\n}\nexport function isWS(text, offset) {\n return '\\r\\n \\t'.indexOf(text.charAt(offset)) !== -1;\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport * as formatter from './impl/format';\nimport * as edit from './impl/edit';\nimport * as scanner from './impl/scanner';\nimport * as parser from './impl/parser';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport const createScanner = scanner.createScanner;\nexport var ScanError;\n(function (ScanError) {\n ScanError[ScanError[\"None\"] = 0] = \"None\";\n ScanError[ScanError[\"UnexpectedEndOfComment\"] = 1] = \"UnexpectedEndOfComment\";\n ScanError[ScanError[\"UnexpectedEndOfString\"] = 2] = \"UnexpectedEndOfString\";\n ScanError[ScanError[\"UnexpectedEndOfNumber\"] = 3] = \"UnexpectedEndOfNumber\";\n ScanError[ScanError[\"InvalidUnicode\"] = 4] = \"InvalidUnicode\";\n ScanError[ScanError[\"InvalidEscapeCharacter\"] = 5] = \"InvalidEscapeCharacter\";\n ScanError[ScanError[\"InvalidCharacter\"] = 6] = \"InvalidCharacter\";\n})(ScanError || (ScanError = {}));\nexport var SyntaxKind;\n(function (SyntaxKind) {\n SyntaxKind[SyntaxKind[\"OpenBraceToken\"] = 1] = \"OpenBraceToken\";\n SyntaxKind[SyntaxKind[\"CloseBraceToken\"] = 2] = \"CloseBraceToken\";\n SyntaxKind[SyntaxKind[\"OpenBracketToken\"] = 3] = \"OpenBracketToken\";\n SyntaxKind[SyntaxKind[\"CloseBracketToken\"] = 4] = \"CloseBracketToken\";\n SyntaxKind[SyntaxKind[\"CommaToken\"] = 5] = \"CommaToken\";\n SyntaxKind[SyntaxKind[\"ColonToken\"] = 6] = \"ColonToken\";\n SyntaxKind[SyntaxKind[\"NullKeyword\"] = 7] = \"NullKeyword\";\n SyntaxKind[SyntaxKind[\"TrueKeyword\"] = 8] = \"TrueKeyword\";\n SyntaxKind[SyntaxKind[\"FalseKeyword\"] = 9] = \"FalseKeyword\";\n SyntaxKind[SyntaxKind[\"StringLiteral\"] = 10] = \"StringLiteral\";\n SyntaxKind[SyntaxKind[\"NumericLiteral\"] = 11] = \"NumericLiteral\";\n SyntaxKind[SyntaxKind[\"LineCommentTrivia\"] = 12] = \"LineCommentTrivia\";\n SyntaxKind[SyntaxKind[\"BlockCommentTrivia\"] = 13] = \"BlockCommentTrivia\";\n SyntaxKind[SyntaxKind[\"LineBreakTrivia\"] = 14] = \"LineBreakTrivia\";\n SyntaxKind[SyntaxKind[\"Trivia\"] = 15] = \"Trivia\";\n SyntaxKind[SyntaxKind[\"Unknown\"] = 16] = \"Unknown\";\n SyntaxKind[SyntaxKind[\"EOF\"] = 17] = \"EOF\";\n})(SyntaxKind || (SyntaxKind = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport const getLocation = parser.getLocation;\n/**\n * 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.\n * Therefore, always check the errors list to find out if the input was valid.\n */\nexport const parse = parser.parse;\n/**\n * 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.\n */\nexport const parseTree = parser.parseTree;\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport const findNodeAtLocation = parser.findNodeAtLocation;\n/**\n * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport const findNodeAtOffset = parser.findNodeAtOffset;\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport const getNodePath = parser.getNodePath;\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport const getNodeValue = parser.getNodeValue;\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport const visit = parser.visit;\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport const stripComments = parser.stripComments;\nexport var ParseErrorCode;\n(function (ParseErrorCode) {\n ParseErrorCode[ParseErrorCode[\"InvalidSymbol\"] = 1] = \"InvalidSymbol\";\n ParseErrorCode[ParseErrorCode[\"InvalidNumberFormat\"] = 2] = \"InvalidNumberFormat\";\n ParseErrorCode[ParseErrorCode[\"PropertyNameExpected\"] = 3] = \"PropertyNameExpected\";\n ParseErrorCode[ParseErrorCode[\"ValueExpected\"] = 4] = \"ValueExpected\";\n ParseErrorCode[ParseErrorCode[\"ColonExpected\"] = 5] = \"ColonExpected\";\n ParseErrorCode[ParseErrorCode[\"CommaExpected\"] = 6] = \"CommaExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBraceExpected\"] = 7] = \"CloseBraceExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBracketExpected\"] = 8] = \"CloseBracketExpected\";\n ParseErrorCode[ParseErrorCode[\"EndOfFileExpected\"] = 9] = \"EndOfFileExpected\";\n ParseErrorCode[ParseErrorCode[\"InvalidCommentToken\"] = 10] = \"InvalidCommentToken\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfComment\"] = 11] = \"UnexpectedEndOfComment\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfString\"] = 12] = \"UnexpectedEndOfString\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfNumber\"] = 13] = \"UnexpectedEndOfNumber\";\n ParseErrorCode[ParseErrorCode[\"InvalidUnicode\"] = 14] = \"InvalidUnicode\";\n ParseErrorCode[ParseErrorCode[\"InvalidEscapeCharacter\"] = 15] = \"InvalidEscapeCharacter\";\n ParseErrorCode[ParseErrorCode[\"InvalidCharacter\"] = 16] = \"InvalidCharacter\";\n})(ParseErrorCode || (ParseErrorCode = {}));\nexport function printParseErrorCode(code) {\n switch (code) {\n case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol';\n case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat';\n case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected';\n case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected';\n case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected';\n case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected';\n case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected';\n case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected';\n case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected';\n case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken';\n case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';\n case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString';\n case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';\n case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode';\n case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';\n case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter';\n }\n return '<unknown ParseErrorCode>';\n}\n/**\n * Computes the edit operations needed to format a JSON document.\n *\n * @param documentText The input text\n * @param range The range to format or `undefined` to format the full content\n * @param options The formatting options\n * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function format(documentText, range, options) {\n return formatter.format(documentText, range, options);\n}\n/**\n * Computes the edit operations needed to modify a value in the JSON document.\n *\n * @param documentText The input text\n * @param path The path of the value to change. The path represents either to the document root, a property or an array item.\n * If the path points to an non-existing property or item, it will be created.\n * @param value The new value for the specified property or item. If the value is undefined,\n * the property or item will be removed.\n * @param options Options\n * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function modify(text, path, value, options) {\n return edit.setProperty(text, path, value, options);\n}\n/**\n * Applies edits to an input string.\n * @param text The input text\n * @param edits Edit operations following the format described in {@linkcode EditResult}.\n * @returns The text with the applied edits.\n * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.\n */\nexport function applyEdits(text, edits) {\n let sortedEdits = edits.slice(0).sort((a, b) => {\n const diff = a.offset - b.offset;\n if (diff === 0) {\n return a.length - b.length;\n }\n return diff;\n });\n let lastModifiedOffset = text.length;\n for (let i = sortedEdits.length - 1; i >= 0; i--) {\n let e = sortedEdits[i];\n if (e.offset + e.length <= lastModifiedOffset) {\n text = edit.applyEdit(text, e);\n }\n else {\n throw new Error('Overlapping edit');\n }\n lastModifiedOffset = e.offset;\n }\n return text;\n}\n","/**\n * Surgical wrangler.jsonc helpers used by `baerly deploy` and the\n * `@gusto/create-baerly-storage` bolt-on flow. All functions are pure (no I/O) —\n * callers do the file read/write. Built on `jsonc-parser` so\n * comments and trailing commas survive round-trips.\n */\n\nimport { parse, modify, applyEdits, type ParseError, type FormattingOptions } from \"jsonc-parser\";\nimport { BaerlyError } from \"@baerly/protocol\";\n\n/**\n * Declared R2 binding extracted from a `wrangler.jsonc` source.\n * Subset of the wrangler schema — we only consume `binding` and\n * `bucket_name`, not the optional preview/jurisdiction fields.\n */\nexport interface R2BindingDeclaration {\n readonly binding: string;\n readonly bucket_name: string;\n}\n\n/**\n * Parse declared `r2_buckets[]` from a `wrangler.jsonc` source\n * string. Tolerates comments + trailing commas via `jsonc-parser`.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — malformed JSONC or\n * invalid `r2_buckets` shape.\n */\nexport const parseR2Bindings = (source: string): readonly R2BindingDeclaration[] => {\n const errors: ParseError[] = [];\n const obj = parse(source, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { r2_buckets?: unknown }\n | undefined;\n if (errors.length > 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `wrangler.jsonc parse error at offset ${errors[0]!.offset}: ${errors[0]!.error}`,\n );\n }\n if (obj === undefined || typeof obj !== \"object\") {\n throw new BaerlyError(\"InvalidConfig\", `wrangler.jsonc did not parse to an object`);\n }\n const buckets = obj.r2_buckets;\n if (buckets === undefined) {\n return [];\n }\n if (!Array.isArray(buckets)) {\n throw new BaerlyError(\"InvalidConfig\", `wrangler.jsonc: r2_buckets must be an array`);\n }\n const out: R2BindingDeclaration[] = [];\n for (const b of buckets) {\n if (b === null || typeof b !== \"object\") {\n throw new BaerlyError(\"InvalidConfig\", `wrangler.jsonc: r2_buckets entry must be an object`);\n }\n const entry = b as { binding?: unknown; bucket_name?: unknown };\n if (typeof entry.binding !== \"string\" || entry.binding.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `wrangler.jsonc: r2_buckets[].binding must be a non-empty string`,\n );\n }\n if (typeof entry.bucket_name !== \"string\" || entry.bucket_name.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `wrangler.jsonc: r2_buckets[].bucket_name must be a non-empty string`,\n );\n }\n out.push({ binding: entry.binding, bucket_name: entry.bucket_name });\n }\n return out;\n};\n\n/**\n * Input spec for a single R2 binding to add or verify in\n * `wrangler.jsonc`. Mirrors `R2BindingDeclaration` in shape but\n * represents caller intent rather than a parsed declaration.\n */\nexport interface R2BindingSpec {\n readonly binding: string;\n readonly bucket_name: string;\n}\n\n/**\n * Flat string→string map of `vars` entries to merge into\n * `wrangler.jsonc`. Existing keys are never overwritten (user wins).\n */\nexport interface VarsSpec {\n readonly [key: string]: string;\n}\n\n/**\n * Result returned by `patchWranglerJsonc`. `text` is the updated\n * JSONC source; `changes` is a human-readable summary of what was\n * added (empty when the file was already up to date).\n */\nexport interface PatchResult {\n readonly text: string;\n readonly changes: readonly string[];\n}\n\n/**\n * Read the `name` field from a `wrangler.jsonc` source string.\n * Returns `undefined` on malformed JSONC or when the field is absent.\n * Never throws — designed for caller-friendly inspection.\n */\nexport const readWranglerName = (source: string): string | undefined => {\n const errors: ParseError[] = [];\n const parsed = parse(source, errors, { allowTrailingComma: true }) as\n | { name?: unknown }\n | undefined;\n if (errors.length > 0 || typeof parsed?.name !== \"string\") {\n return undefined;\n }\n return parsed.name;\n};\n\n/**\n * Read the `main` field from a `wrangler.jsonc` source string.\n * Returns `undefined` on malformed JSONC or when the field is absent.\n * Never throws — designed for caller-friendly inspection.\n */\nexport const readWranglerMain = (source: string): string | undefined => {\n const errors: ParseError[] = [];\n const parsed = parse(source, errors, { allowTrailingComma: true }) as\n | { main?: unknown }\n | undefined;\n if (errors.length > 0 || typeof parsed?.main !== \"string\") {\n return undefined;\n }\n return parsed.main;\n};\n\n// Sniff the indent style of a JSONC source by scanning for the first\n// indented line and inspecting its leading whitespace. The stock\n// `pnpm create cloudflare` template uses tabs; older / hand-rolled\n// `wrangler.jsonc` files commonly use 2- or 4-space indents. Falls\n// back to 2-space when the file has no indented content (e.g. `{}`).\nconst detectIndent = (source: string): FormattingOptions => {\n for (const line of source.split(\"\\n\")) {\n if (line.length === 0 || line.startsWith(\"{\") || line.startsWith(\"}\")) {\n continue;\n }\n const first = line.charAt(0);\n if (first === \"\\t\") {\n return { insertSpaces: false, tabSize: 2, eol: \"\\n\" };\n }\n if (first === \" \") {\n let count = 0;\n while (count < line.length && line.charAt(count) === \" \") {\n count += 1;\n }\n return { insertSpaces: true, tabSize: count, eol: \"\\n\" };\n }\n }\n return { insertSpaces: true, tabSize: 2, eol: \"\\n\" };\n};\n\n/**\n * Idempotently patch a `wrangler.jsonc` source string:\n *\n * - Appends an R2 binding to `r2_buckets[]` unless an entry with\n * the same `binding` name already exists (user wins).\n * - Merges `vars` keys, skipping any key already present (user wins).\n *\n * Comments and trailing commas are preserved by `jsonc-parser`.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — malformed JSONC or\n * invalid `r2_buckets` / `vars` shape.\n */\nexport const patchWranglerJsonc = (\n source: string,\n binding: R2BindingSpec,\n vars: VarsSpec,\n): PatchResult => {\n const existingBindings = parseR2Bindings(source);\n\n const errors: ParseError[] = [];\n const entry = parse(source, errors, { allowTrailingComma: true }) as\n | { vars?: unknown }\n | undefined;\n\n const rawVars = entry?.vars;\n if (rawVars !== undefined) {\n if (typeof rawVars !== \"object\" || rawVars === null || Array.isArray(rawVars)) {\n throw new BaerlyError(\"InvalidConfig\", \"wrangler.jsonc: vars must be an object\");\n }\n }\n const existingVars = (rawVars ?? {}) as Record<string, unknown>;\n\n const formattingOptions = detectIndent(source);\n const changes: string[] = [];\n let text = source;\n\n const bindingAlreadyDeclared = existingBindings.some((b) => b.binding === binding.binding);\n if (!bindingAlreadyDeclared) {\n const edits = modify(text, [\"r2_buckets\", -1], binding, { formattingOptions });\n text = applyEdits(text, edits);\n changes.push(`added r2 binding ${binding.binding} → ${binding.bucket_name}`);\n }\n\n const addedVarKeys: string[] = [];\n for (const [key, value] of Object.entries(vars)) {\n if (!(key in existingVars)) {\n const edits = modify(text, [\"vars\", key], value, { formattingOptions });\n text = applyEdits(text, edits);\n addedVarKeys.push(key);\n }\n }\n if (addedVarKeys.length > 0) {\n changes.push(`merged vars: ${addedVarKeys.join(\", \")}`);\n }\n\n return { text, changes };\n};\n","/**\n * Render the worker-entry paste-string that the create-baerly-storage\n * bolt-on flow prints after patching `wrangler.jsonc`. The user\n * copies this verbatim into the path declared in\n * `wrangler.jsonc:main`, replacing the stock `wrangler create`\n * hello world. baerly never writes user code (Convex-style:\n * structured config is fair game; the worker entry is sacred).\n */\n\nimport { relative, dirname, normalize } from \"node:path/posix\";\n\nexport interface SnippetContext {\n /**\n * Tenant identifier the bolt-on flow seeds into `wrangler.jsonc:vars.TENANT`.\n * The snippet itself does NOT interpolate this — it references the runtime\n * `env.TENANT`. The field lives on this context type so callers pass a\n * single object to both the snippet renderer and the wrangler patcher.\n */\n readonly tenant: string;\n /** Verbatim `wrangler.jsonc:main` — drives the import-to-config relpath. */\n readonly wranglerMain: string;\n}\n\n/**\n * Compute the JS import path from `wranglerMain` to `./baerly.config.ts`.\n * Both inputs are repo-root-relative; the output is the import string\n * the snippet emits. Always carries the explicit `.ts` extension\n * (project convention; see CLAUDE.md \"Imports are relative, with\n * explicit `.ts`/`.tsx` extensions\").\n */\n// Callers must pass forward-slash paths. POSIX normalize treats `\\\\` as a\n// literal character, not a separator, so backslash-style Windows paths\n// would be misinterpreted. `wrangler.jsonc:main` always uses forward slashes\n// on every host, so this is safe in practice.\nexport const computeConfigImportPath = (wranglerMain: string): string => {\n const normalised = normalize(wranglerMain);\n const fromDir = dirname(normalised);\n if (fromDir === \".\" || fromDir === \"\") {\n return \"./baerly.config.ts\";\n }\n const rel = relative(fromDir, \"baerly.config.ts\");\n return rel.startsWith(\"..\") ? rel : `./${rel}`;\n};\n\nexport const renderWorkerEntrySnippet = (ctx: SnippetContext): string => {\n const configPath = computeConfigImportPath(ctx.wranglerMain);\n return `import { baerlyWorker, type BaerlyEnv } from \"@gusto/baerly-storage/cloudflare\";\nimport { sharedSecret } from \"@gusto/baerly-storage/auth\";\nimport config from \"${configPath}\";\n\ninterface AppEnv extends BaerlyEnv {\n readonly TENANT: string;\n readonly SHARED_SECRET: string;\n}\n\nexport default baerlyWorker<AppEnv>((env) => ({\n verifier: sharedSecret({ secret: env.SHARED_SECRET, tenantPrefix: env.TENANT }),\n config,\n}));\n`;\n};\n","/**\n * `Installer` DI seam for the post-scaffold install step. The default\n * implementation shells out to the detected package manager via\n * `node:child_process.spawn` with `stdio: \"inherit\"` so the user sees\n * the pm's own progress (pnpm's spinner, npm's bars). Tests inject a\n * mock to avoid spawning real installs.\n *\n * Mirrors the shape of `packages/cli/src/runner.ts:ProcessRunner` —\n * intentionally not imported cross-package because `create-baerly-storage`\n * has its own dependency surface (no `@baerly/cli` dep).\n */\nimport { spawn } from \"node:child_process\";\nimport type { Pm } from \"./pm-detect.ts\";\n\nexport interface Installer {\n /**\n * Run `<pm> install` in `cwd`. Resolves with the child's exit code.\n * Never throws on a non-zero exit — the caller decides whether that\n * should be fatal. Throws only if `spawn` itself fails (binary not\n * on PATH, permission denied).\n */\n run(pm: Pm, cwd: string): Promise<{ readonly code: number }>;\n}\n\nexport const defaultInstaller: Installer = {\n run: (pm, cwd) =>\n new Promise((resolve, reject) => {\n const child = spawn(pm, [\"install\"], { cwd, stdio: \"inherit\" });\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolve({ code: code ?? 1 }));\n }),\n};\n","/**\n * Bolt-on agent-rules writer. The CLI enables this by default for\n * existing wrangler projects and lets users opt out with\n * `--no-agent-rules`. It drops a delimited block that tells the user's\n * AI agent (Claude / Cursor / Copilot) that\n * `node_modules/@gusto/baerly-storage/dist/API.md` is the canonical API\n * surface and that the patterns those agents' training data is densest\n * with (Postgres/Prisma/Drizzle, Mongo, Firebase) don't apply.\n *\n * Scaffolded apps already get this via the per-template `AGENTS.md`\n * shipped by `scaffold()`. This module is for the bolt-on path —\n * `pnpm create @gusto/baerly-storage@latest .` in an existing wrangler\n * project — where no template file is copied.\n *\n * Target detection (first match wins):\n * 1. `.claude/rules/` exists → write `.claude/rules/baerly.md`.\n * 2. `AGENTS.md` exists at repo root → append a delimited block.\n * 3. `.cursor/rules/` exists → write `.cursor/rules/baerly.md`.\n * 4. None of the above → create `AGENTS.md` at repo root.\n *\n * Idempotent: a second run with the same target replaces the\n * delimited block in place rather than duplicating it.\n */\n\nimport { constants } from \"node:fs\";\nimport { mkdir, readFile, writeFile, access, stat } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\n\nconst BLOCK_START = \"<!-- baerly:start -->\";\nconst BLOCK_END = \"<!-- baerly:end -->\";\n\n/**\n * The literal block content emitted into the chosen target file.\n * Wording mirrors the per-template `AGENTS.md` preamble shipped by\n * `scaffold()` so an agent dropped into a bolt-on repo gets the\n * same orientation a scaffolded-app agent gets.\n *\n * Wrapped in `BLOCK_START` / `BLOCK_END` so a second run replaces\n * in place.\n */\nconst AGENT_RULES_BLOCK = `${BLOCK_START}\n## @gusto/baerly-storage\n\nThis repo uses @gusto/baerly-storage. Before writing or modifying storage code:\n\n- Read **\\`node_modules/@gusto/baerly-storage/dist/API.md\\`** — public-API\n quickref. Every method, every error code, every example. If a\n pattern you want to use is not here, it does not exist in baerly.\n- Common mistakes keyed by the exact error string live in\n \\`node_modules/@gusto/baerly-storage/dist/RECIPES.md\\`.\n- Type contracts live in \\`node_modules/@gusto/baerly-storage/dist/*.d.ts\\`.\n The whole API is \\`Db\\`, \\`Collection<T>\\`, \\`Query<T>\\`, and \\`Predicate<T>\\`.\n\nAnti-patterns that compile but are wrong:\n\n- \\`db.collection(...).insertOne(...)\\` — no such method. Use\n \\`db.collection(...).insert(...)\\`.\n- \\`.useIndex(\"name\")\\` — does not exist. The query planner picks\n indexes automatically from registered \\`IndexDefinition\\`s.\n- \\`z.string().nullable()\\` — \\`DocumentValue\\` excludes \\`null\\`. Use\n \\`.optional()\\`; \\`null\\` in update patches is the RFC 7386 deletion\n sentinel.\n- SQL strings, raw \\`WHERE\\` clauses — the API is a method-chain\n only: \\`.where({ field: value }).all()\\` (object literal, equality)\n or \\`.where(q => q.gte(\"field\", n)).all()\\` (callback DSL,\n operators: \\`eq\\` / \\`gt\\` / \\`gte\\` / \\`lt\\` / \\`lte\\` / \\`in\\`).\n- \\`.all()\\` on a hot path — page or cursor-iterate. \\`.all()\\` is for\n bounded result sets only.\n${BLOCK_END}\n`;\n\ntype AgentRulesAction = \"created\" | \"appended\" | \"replaced\";\n\nexport interface AgentRulesResult {\n /** Absolute path of the file written. */\n readonly path: string;\n readonly action: AgentRulesAction;\n}\n\n/**\n * Target-file resolution. Exported for tests; callers should use\n * `writeAgentRulesBlock` directly.\n */\ninterface AgentRulesTarget {\n /** Absolute path. */\n readonly path: string;\n /**\n * `dedicated` → write a fresh file owned entirely by us (we are\n * inside `.claude/rules/` or `.cursor/rules/`). `shared` → append\n * to / replace inside a file the user may also edit (root\n * `AGENTS.md`).\n */\n readonly mode: \"dedicated\" | \"shared\";\n}\n\nconst fileExists = async (path: string): Promise<boolean> => {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n};\n\nconst dirExists = async (path: string): Promise<boolean> => {\n try {\n const s = await stat(path);\n return s.isDirectory();\n } catch {\n return false;\n }\n};\n\nconst detectAgentRulesTarget = async (outDir: string): Promise<AgentRulesTarget> => {\n if (await dirExists(resolve(outDir, \".claude\", \"rules\"))) {\n return { path: resolve(outDir, \".claude\", \"rules\", \"baerly.md\"), mode: \"dedicated\" };\n }\n if (await fileExists(resolve(outDir, \"AGENTS.md\"))) {\n return { path: resolve(outDir, \"AGENTS.md\"), mode: \"shared\" };\n }\n if (await dirExists(resolve(outDir, \".cursor\", \"rules\"))) {\n return { path: resolve(outDir, \".cursor\", \"rules\", \"baerly.md\"), mode: \"dedicated\" };\n }\n return { path: resolve(outDir, \"AGENTS.md\"), mode: \"shared\" };\n};\n\n/**\n * `Indices` plural intentionally: returns the indices of the first\n * START and the matching END so callers can slice surrounding\n * content cleanly. Returns null when the file has no managed block.\n */\nconst findBlockRange = (text: string): { start: number; end: number } | null => {\n const start = text.indexOf(BLOCK_START);\n if (start === -1) {\n return null;\n }\n const endTag = text.indexOf(BLOCK_END, start + BLOCK_START.length);\n if (endTag === -1) {\n return null;\n }\n return { start, end: endTag + BLOCK_END.length };\n};\n\nexport const writeAgentRulesBlock = async (outDir: string): Promise<AgentRulesResult> => {\n const target = await detectAgentRulesTarget(outDir);\n\n if (target.mode === \"dedicated\") {\n // .claude/rules/ or .cursor/rules/ — we own the whole file.\n // First run: `created`. Second run: `replaced` (idempotent\n // overwrite is byte-identical since the block constant is the\n // whole file).\n await mkdir(dirname(target.path), { recursive: true });\n const existed = await fileExists(target.path);\n await writeFile(target.path, AGENT_RULES_BLOCK, \"utf8\");\n return { path: target.path, action: existed ? \"replaced\" : \"created\" };\n }\n\n // Shared mode: AGENTS.md at repo root. Three sub-cases.\n if (!(await fileExists(target.path))) {\n await writeFile(target.path, AGENT_RULES_BLOCK, \"utf8\");\n return { path: target.path, action: \"created\" };\n }\n\n const existing = await readFile(target.path, \"utf8\");\n const range = findBlockRange(existing);\n if (range !== null) {\n const before = existing.slice(0, range.start);\n const after = existing.slice(range.end);\n // Drop the leading newline of our block when the preceding text\n // already ends with one — keeps replace byte-identical to the\n // append case.\n const trimmedBlock = before.endsWith(\"\\n\")\n ? AGENT_RULES_BLOCK.replace(/\\n$/, \"\")\n : `\\n${AGENT_RULES_BLOCK.replace(/\\n$/, \"\")}`;\n await writeFile(target.path, `${before}${trimmedBlock}${after}`, \"utf8\");\n return { path: target.path, action: \"replaced\" };\n }\n\n // Append. Ensure the user's existing content is byte-identical\n // before the appended block: introduce a single blank-line gap\n // when the existing file doesn't already end with `\\n\\n`.\n let gap: string;\n if (existing.endsWith(\"\\n\\n\")) {\n gap = \"\";\n } else if (existing.endsWith(\"\\n\")) {\n gap = \"\\n\";\n } else {\n gap = \"\\n\\n\";\n }\n await writeFile(target.path, `${existing}${gap}${AGENT_RULES_BLOCK}`, \"utf8\");\n return { path: target.path, action: \"appended\" };\n};\n","/**\n * The wrangler bolt-on flow for `create-baerly-storage`. Runs when `runner.ts`\n * detects an existing `wrangler.jsonc` in the resolved `outDir` — the\n * user has a Cloudflare Worker project already and wants to add\n * baerly. No template copy. Patches the mergeable files\n * (`wrangler.jsonc`, `.dev.vars`, `.gitignore`, `package.json`),\n * writes `baerly.config.ts` (skip-if-exists), and returns the\n * worker-entry snippet for the caller to print.\n *\n * Mirrors Convex's `npx convex dev` philosophy: structured config is\n * fair game; user code (`src/index.ts`) is sacred — printed, never\n * written.\n */\n\nimport { constants } from \"node:fs\";\nimport { readFile, writeFile, appendFile, access } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport type { BaerlyAppConfig } from \"@baerly/server\";\nimport { patchWranglerJsonc, readWranglerName, readWranglerMain } from \"@baerly/cli/wrangler-patch\";\nimport { renderWorkerEntrySnippet } from \"./init-snippet.ts\";\nimport { detectPm, type Pm } from \"./pm-detect.ts\";\nimport { defaultInstaller, type Installer } from \"./install.ts\";\nimport { writeAgentRulesBlock, type AgentRulesResult } from \"./agent-rules.ts\";\n\nconst DEV_SHARED_SECRET = \"dev-shared-secret\";\n\n// Lines that, if present literally in .gitignore, are treated as \"the user\n// already has a story for env-var files.\" We don't add a separate .dev.vars\n// entry in that case — we trust their convention. (NOT gitignore glob semantics.)\nconst GITIGNORE_DEV_VARS_ALIASES = new Set([\n \".dev.vars\",\n \".dev.vars*\",\n \".env*.local\",\n \"*.local\",\n \".env\",\n]);\n\nexport interface BoltOnOptions {\n readonly outDir: string;\n readonly tenant: string;\n readonly app?: string;\n readonly force?: boolean;\n readonly runInstall?: boolean;\n readonly pm?: Pm;\n readonly installer?: Installer;\n /**\n * When `true`, drop a delimited \"this repo uses @gusto/baerly-storage\"\n * block telling the user's AI agent where the canonical API\n * surface lives. The programmatic helper is opt-in; the CLI bolt-on\n * path passes `true` by default unless `--no-agent-rules` is set.\n * See `agent-rules.ts` for the target-detection chain and the\n * literal block content.\n */\n readonly agentRules?: boolean;\n}\n\nexport interface BoltOnResult {\n readonly app: string;\n readonly tenant: string;\n readonly changes: readonly string[];\n readonly snippet: string;\n readonly snippetTarget: string;\n readonly nextSteps: readonly string[];\n /** Present iff `opts.agentRules === true`. */\n readonly agentRules?: AgentRulesResult;\n}\n\nconst configTemplate = (app: string, tenant: string): string => {\n const cfg = {\n app,\n tenant,\n target: \"cloudflare\",\n auth: \"none\",\n collections: {},\n } as const satisfies BaerlyAppConfig;\n return `import { defineConfig } from \"@gusto/baerly-storage/config\";\n\nexport default defineConfig(${JSON.stringify(cfg, null, 2)});\n`;\n};\n\nconst gitignoreCovers = (text: string, line: string): boolean => {\n const lines = text.split(\"\\n\").map((l) => l.trim());\n return lines.some((l) => GITIGNORE_DEV_VARS_ALIASES.has(l) || l === line);\n};\n\nconst fileExists = async (path: string): Promise<boolean> => {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n};\n\nconst appendBaerlyStorageDep = async (pkgJsonPath: string, changes: string[]): Promise<void> => {\n const raw = await readFile(pkgJsonPath, \"utf8\");\n let pkg: { dependencies?: Record<string, string> };\n try {\n pkg = JSON.parse(raw) as { dependencies?: Record<string, string> };\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `create-baerly-storage bolt-on: ${pkgJsonPath} is not valid JSON — ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n pkg.dependencies = pkg.dependencies ?? {};\n if (pkg.dependencies[\"@gusto/baerly-storage\"] !== undefined) {\n return;\n }\n pkg.dependencies[\"@gusto/baerly-storage\"] = \"*\";\n await writeFile(pkgJsonPath, `${JSON.stringify(pkg, null, 2)}\\n`, \"utf8\");\n changes.push(\"package.json: added @gusto/baerly-storage dependency\");\n};\n\nexport const boltOnExistingWrangler = async (opts: BoltOnOptions): Promise<BoltOnResult> => {\n const wranglerPath = resolve(opts.outDir, \"wrangler.jsonc\");\n if (!(await fileExists(wranglerPath))) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `create-baerly-storage bolt-on: ${wranglerPath} missing — bolt-on mode requires wrangler.jsonc`,\n );\n }\n const wranglerSource = await readFile(wranglerPath, \"utf8\");\n const detectedName = readWranglerName(wranglerSource);\n const detectedMain = readWranglerMain(wranglerSource) ?? \"src/index.ts\";\n\n const app = opts.app ?? detectedName;\n if (typeof app !== \"string\" || app.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"create-baerly-storage bolt-on: --app=<name> is required (no wrangler.jsonc:name to infer from)\",\n );\n }\n\n const changes: string[] = [];\n\n const patch = patchWranglerJsonc(\n wranglerSource,\n { binding: \"BUCKET\", bucket_name: app },\n { APP: app, TENANT: opts.tenant },\n );\n if (patch.changes.length > 0) {\n await writeFile(wranglerPath, patch.text, \"utf8\");\n for (const c of patch.changes) {\n changes.push(`wrangler.jsonc: ${c}`);\n }\n }\n\n const devVarsPath = resolve(opts.outDir, \".dev.vars\");\n if (!(await fileExists(devVarsPath))) {\n await writeFile(devVarsPath, `SHARED_SECRET=${DEV_SHARED_SECRET}\\n`, \"utf8\");\n changes.push(\".dev.vars: seeded SHARED_SECRET (dev-only placeholder; replace before deploy)\");\n }\n\n const gitignorePath = resolve(opts.outDir, \".gitignore\");\n let gitignoreText = \"\";\n if (await fileExists(gitignorePath)) {\n gitignoreText = await readFile(gitignorePath, \"utf8\");\n }\n if (!gitignoreCovers(gitignoreText, \".dev.vars\")) {\n const suffix = gitignoreText.length === 0 || gitignoreText.endsWith(\"\\n\") ? \"\" : \"\\n\";\n await appendFile(gitignorePath, `${suffix}.dev.vars\\n`, \"utf8\");\n changes.push(\".gitignore: added .dev.vars\");\n }\n\n const configPath = resolve(opts.outDir, \"baerly.config.ts\");\n const configExists = await fileExists(configPath);\n if (!configExists || opts.force === true) {\n await writeFile(configPath, configTemplate(app, opts.tenant), \"utf8\");\n changes.push(`baerly.config.ts: ${configExists ? \"rewrote\" : \"wrote\"}`);\n }\n\n const pkgJsonPath = resolve(opts.outDir, \"package.json\");\n if (await fileExists(pkgJsonPath)) {\n await appendBaerlyStorageDep(pkgJsonPath, changes);\n }\n\n let agentRules: AgentRulesResult | undefined;\n if (opts.agentRules === true) {\n agentRules = await writeAgentRulesBlock(opts.outDir);\n const relPath = agentRules.path.startsWith(opts.outDir)\n ? agentRules.path.slice(opts.outDir.length + 1)\n : agentRules.path;\n changes.push(`${relPath}: ${agentRules.action} agent-rules block`);\n }\n\n if (opts.runInstall === true) {\n const pm = opts.pm ?? detectPm();\n const installer = opts.installer ?? defaultInstaller;\n await installer.run(pm, opts.outDir);\n changes.push(`${pm} install`);\n }\n\n const snippet = renderWorkerEntrySnippet({\n tenant: opts.tenant,\n wranglerMain: detectedMain,\n });\n\n return {\n app,\n tenant: opts.tenant,\n changes,\n snippet,\n snippetTarget: detectedMain,\n nextSteps: [\n `Paste the snippet above into ${detectedMain}, replacing the stock handler.`,\n `Before deploy: \\`wrangler secret put SHARED_SECRET\\` (the .dev.vars value is dev-only).`,\n ],\n ...(agentRules !== undefined && { agentRules }),\n };\n};\n","/**\n * `create-baerly-storage` command logic — citty `defineCommand` plus the\n * programmatic `runCreateBaerly` entry consumed by tests. The bin\n * shim at `./index.ts` imports `main` from here and invokes citty's\n * `runMain`. Tests import `runCreateBaerly` so they can drive the\n * CLI in-process without `runMain` calling `process.exit` inside\n * vitest.\n *\n * That `npm create` invocation is the **post-publish** form; until\n * the package ships to npm, stage locally from a clone via\n * `pnpm pack` + `pnpm dlx file:.../create-baerly-0.1.0.tgz` — see\n * the repo `README.md` Quick Start.\n *\n * Citty arg shape matches `@baerly/cli`'s `defineCommand` pattern\n * (see `packages/cli/src/init.ts`).\n *\n * Two flows live here:\n * - **Interactive wizard** — enters `runWizard` from `./prompts.ts`\n * when stdin is a TTY *and* `--json` is not set *and* either\n * `projectName` or `target` was omitted.\n * - **Flag-driven** — unchanged: CI, agents, piped stdin, and any\n * TTY invocation with `--json` keep the existing behavior and\n * the existing JSON envelope shape (part of the agent contract).\n */\nimport { defineCommand, parseArgs, type ArgsDef, type ParsedArgs } from \"citty\";\nimport { outro } from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { runWizard } from \"./prompts.ts\";\nimport { type Addon, KNOWN_ADDONS, scaffold } from \"./scaffold.ts\";\nimport { boltOnExistingWrangler } from \"./bolt-on.ts\";\nimport { defaultInstaller, type Installer } from \"./install.ts\";\nimport { detectPm, probePmVersion } from \"./pm-detect.ts\";\nimport { defaultGitRunner, type GitRunner, initRepoAndCommit } from \"./git.ts\";\n\nexport const CREATE_BAERLY_ARGS = {\n projectName: {\n type: \"positional\",\n description: \"Output directory name (or '.' to scaffold into the current directory)\",\n // Optional at the citty layer so a bare `create-baerly-storage` on a\n // TTY can fall into the wizard. The flag-driven branch below\n // re-validates when wizard mode is suppressed (non-TTY / --json).\n required: false,\n valueHint: \"name\",\n },\n target: {\n type: \"enum\",\n options: [\"cloudflare\", \"node\"],\n description: 'Deploy target — \"cloudflare\" or \"node\".',\n // Optional at the citty layer so a bare `create-baerly-storage` on a\n // TTY can fall into the wizard. The flag-driven branch below\n // re-validates when wizard mode is suppressed (non-TTY / --json).\n required: false,\n },\n starter: {\n type: \"enum\",\n options: [\"minimal\", \"react\"],\n description: 'Starter template — \"minimal\" (default) or \"react\".',\n },\n tenant: {\n type: \"string\",\n description: 'Default tenant pin (default \"default\").',\n valueHint: \"string\",\n },\n domain: {\n type: \"string\",\n description: \"Custom domain for the deployed service.\",\n valueHint: \"host\",\n },\n install: {\n type: \"boolean\",\n description: \"Run <pm> install after writing files (default false).\",\n },\n force: {\n type: \"boolean\",\n description:\n \"In bolt-on mode, overwrite an existing baerly.config.ts (no-op in scaffold mode).\",\n },\n git: {\n type: \"boolean\",\n description:\n \"Initialise a git repo + create the initial commit after scaffold (default true in wizard, false in flag-driven mode). Negate with --no-git.\",\n },\n with: {\n type: \"string\",\n description:\n 'Comma-separated add-ons. Scaffold mode: \"docker\" (requires --target=node). ' +\n \"The bolt-on AGENTS.md block is its own default-on flag — see --agent-rules.\",\n valueHint: \"docker\",\n },\n \"agent-rules\": {\n type: \"boolean\",\n description:\n \"Bolt-on mode: write/refresh the AGENTS.md router pointing at the baerly API (default true; negate with --no-agent-rules). Ignored in scaffold mode.\",\n },\n pm: {\n type: \"string\",\n description: 'Override package manager — \"npm\", \"pnpm\", or \"yarn\".',\n valueHint: \"pm\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit JSON envelope to stdout (success) or stderr (error).\",\n },\n} as const satisfies ArgsDef;\n\nconst resolveOutDir = (projectName: string): string =>\n projectName === \".\" ? process.cwd() : resolve(process.cwd(), projectName);\n\ninterface DispatchBoltOnOpts {\n readonly outDir: string;\n readonly tenant: string;\n readonly force: boolean;\n readonly install: boolean;\n readonly pm: \"npm\" | \"pnpm\" | \"yarn\" | undefined;\n readonly json: boolean;\n readonly isInteractive: boolean;\n readonly installer: Installer | undefined;\n readonly agentRules: boolean;\n}\n\nconst dispatchBoltOn = async (opts: DispatchBoltOnOpts): Promise<number> => {\n try {\n const result = await boltOnExistingWrangler({\n outDir: opts.outDir,\n tenant: opts.tenant,\n ...(opts.force && { force: true }),\n runInstall: opts.install,\n ...(opts.pm !== undefined && { pm: opts.pm }),\n ...(opts.installer !== undefined && { installer: opts.installer }),\n ...(opts.agentRules && { agentRules: true }),\n });\n if (opts.json) {\n process.stdout.write(\n `${JSON.stringify({\n result: {\n command: \"create-baerly-storage\",\n status: \"ok\",\n mode: \"bolt-on\",\n outDir: opts.outDir,\n app: result.app,\n tenant: result.tenant,\n changes: result.changes,\n snippet: result.snippet,\n snippetTarget: result.snippetTarget,\n nextSteps: result.nextSteps,\n ...(result.agentRules !== undefined && { agentRules: result.agentRules }),\n },\n })}\\n`,\n );\n } else if (opts.isInteractive) {\n const changesBlock =\n result.changes.length === 0\n ? \" (no changes — already bolted on)\"\n : result.changes.map((c) => ` ${c}`).join(\"\\n\");\n outro(\n `${pc.green(\"✓\")} bolted baerly onto ${opts.outDir}\\n\\n` +\n `Changes:\\n${changesBlock}\\n\\n` +\n `Paste this into ${result.snippetTarget}, replacing the stock handler:\\n\\n` +\n result.snippet +\n `\\nNext steps:\\n` +\n result.nextSteps.map((s) => ` ${s}`).join(\"\\n\"),\n );\n } else {\n process.stdout.write(`${pc.green(\"✓\")} bolted baerly onto ${opts.outDir}\\n`);\n if (result.changes.length > 0) {\n process.stdout.write(`\\n Changes:\\n`);\n for (const c of result.changes) {\n process.stdout.write(` ${c}\\n`);\n }\n }\n process.stdout.write(\n `\\n Paste this into ${result.snippetTarget}, replacing the stock handler:\\n\\n`,\n );\n process.stdout.write(result.snippet);\n process.stdout.write(`\\n Next steps:\\n`);\n for (const s of result.nextSteps) {\n process.stdout.write(` ${s}\\n`);\n }\n process.stdout.write(\"\\n\");\n }\n return 0;\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (opts.json) {\n process.stderr.write(\n `${JSON.stringify({ error: { code: \"InvalidConfig\", message: msg, command: \"create-baerly-storage\" } })}\\n`,\n );\n } else {\n process.stderr.write(`${pc.red(\"create-baerly-storage:\")} ${msg}\\n`);\n }\n return 1;\n }\n};\n\nconst handleCreateBaerly = async (\n args: ParsedArgs<typeof CREATE_BAERLY_ARGS>,\n opts: { readonly installer?: Installer; readonly gitRunner?: GitRunner } = {},\n): Promise<number> => {\n const jsonMode = args.json === true;\n try {\n const isInteractive = process.stdin.isTTY === true && !jsonMode;\n const wantWizard =\n isInteractive && (args.projectName === undefined || args.target === undefined);\n // Parse `--with=docker,…` early so both the flag-driven and\n // wizard-driven paths can use the same parsed value. Unknown\n // add-on names reject here with a list of valid choices.\n let withAddonsFromFlag: readonly Addon[] | undefined;\n if (args.with !== undefined) {\n const parts = args.with\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n const seen = new Set<Addon>();\n for (const p of parts) {\n if (!(KNOWN_ADDONS as readonly string[]).includes(p)) {\n throw new Error(\n `Unknown add-on ${JSON.stringify(p)}. Available add-ons: ${KNOWN_ADDONS.join(\", \")}.`,\n );\n }\n seen.add(p as Addon);\n }\n withAddonsFromFlag = [...seen];\n }\n let projectName: string;\n let target: \"cloudflare\" | \"node\";\n let starter: \"minimal\" | \"react\";\n let withAddons: readonly Addon[];\n let install: boolean;\n let git: boolean;\n if (wantWizard) {\n const w = await runWizard({\n projectName: args.projectName,\n target: args.target,\n starter: args.starter,\n withAddons: withAddonsFromFlag,\n install: args.install,\n git: args.git,\n ...(args.tenant !== undefined && { tenant: args.tenant }),\n });\n if (w.mode === \"bolt-on\") {\n return await dispatchBoltOn({\n outDir: resolveOutDir(w.projectName),\n tenant: w.tenant,\n force: args.force === true,\n install: w.install,\n pm: args.pm as \"npm\" | \"pnpm\" | \"yarn\" | undefined,\n json: jsonMode,\n isInteractive,\n installer: opts.installer,\n agentRules: args[\"agent-rules\"] !== false,\n });\n }\n projectName = w.projectName;\n target = w.target;\n starter = w.starter;\n withAddons = w.withAddons;\n install = w.install;\n git = w.git;\n } else {\n if (args.projectName === undefined) {\n throw new Error(\"projectName is required (positional)\");\n }\n projectName = args.projectName;\n const outDir = resolveOutDir(projectName);\n if (args.target === \"node\" && existsSync(resolve(outDir, \"wrangler.jsonc\"))) {\n throw new Error(\n \"create-baerly-storage: detected wrangler.jsonc but --target=node was passed. \" +\n \"Bolt-on only supports Cloudflare. Remove --target=node, or move out of this directory to scaffold a Node app.\",\n );\n }\n if (existsSync(resolve(outDir, \"wrangler.jsonc\"))) {\n return await dispatchBoltOn({\n outDir,\n tenant: args.tenant ?? \"default\",\n force: args.force === true,\n install: args.install === true,\n pm: args.pm as \"npm\" | \"pnpm\" | \"yarn\" | undefined,\n json: jsonMode,\n isInteractive,\n installer: opts.installer,\n agentRules: args[\"agent-rules\"] !== false,\n });\n }\n if (args.target === undefined) {\n throw new Error(`--target is required when not running in wizard mode (got undefined)`);\n }\n target = args.target;\n // Flag-driven path: scaffold() defaults to \"minimal\" internally,\n // so the explicit fallback here keeps the local `starter` type\n // tight without changing observed behavior.\n starter = args.starter ?? \"minimal\";\n withAddons = withAddonsFromFlag ?? [];\n // Flag-driven path: no wizard, so default to false unless the user\n // explicitly passed --install. Today's CI/agent callers see no\n // behavior change because they never pass --install.\n install = args.install === true;\n // Same shape as `install`: in flag-driven mode the default is off\n // so CI / agents see no behavior change unless they opt in with\n // `--git`. The wizard branch defaults to `true` because a fresh\n // scaffold without a baseline commit is a strict downgrade for\n // anyone iterating against `git diff`.\n git = args.git === true;\n }\n // Cross-field validation: each add-on's mode/target constraint\n // is checked here. Control only reaches this block in scaffold\n // mode — bolt-on dispatch already returned above.\n if (withAddons.includes(\"docker\") && target !== \"node\") {\n throw new Error(\n `--with=docker only applies to --target=node. The Docker add-on adds a ` +\n `Dockerfile to the Node template. Use --target=node --with=docker, or ` +\n `drop --with=docker to scaffold for --target=${target}.`,\n );\n }\n if (withAddons.includes(\"agent-rules\")) {\n throw new Error(\n `--with=agent-rules is unnecessary in scaffold mode. Bolt-on mode writes ` +\n `agent rules by default and supports --no-agent-rules to opt out. ` +\n `Scaffolded apps already include an AGENTS.md preamble — drop --with=agent-rules.`,\n );\n }\n const result = await scaffold({\n projectName,\n target,\n starter,\n ...(args.tenant !== undefined && { tenant: args.tenant }),\n ...(args.domain !== undefined && { domain: args.domain }),\n ...(args.pm !== undefined && { pm: args.pm as \"npm\" | \"pnpm\" | \"yarn\" }),\n ...(withAddons.length > 0 && { withAddons }),\n });\n // Resolve the package manager once; both the git commit body and\n // the optional install step read it.\n const pm = (args.pm as \"npm\" | \"pnpm\" | \"yarn\" | undefined) ?? detectPm();\n // Git init runs BEFORE install so the initial commit captures the\n // scaffold contents only — `node_modules/` is gitignored by the\n // template, but committing pre-install also keeps `git diff` from\n // the start matching exactly what `scaffold()` wrote.\n if (git) {\n const gitRunner = opts.gitRunner ?? defaultGitRunner;\n const pmVersion = probePmVersion(pm);\n const outcome = initRepoAndCommit(\n {\n outDir: result.outDir,\n cliVersion: result.cliVersion,\n appName: result.appName,\n target,\n starter,\n pm,\n ...(pmVersion !== undefined && { pmVersion }),\n },\n gitRunner,\n );\n if (!outcome.initialized && outcome.reason !== \"already-in-repo\") {\n // `already-in-repo` is a *silent* skip — the user opted into\n // scaffold-in-place inside an existing repo, so init would be\n // an error. Every other skip is worth surfacing so the user\n // knows the scaffold succeeded but the git step did not.\n const detail =\n outcome.message === undefined || outcome.message.length === 0\n ? \"\"\n : `: ${outcome.message}`;\n let hint = `${outcome.reason}${detail}`;\n if (outcome.reason === \"git-not-available\") {\n hint = `git is not installed; install it then run \\`git init && git add . && git commit -m '…'\\` in ${result.outDir}.`;\n } else if (outcome.reason === \"no-identity\") {\n 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.`;\n }\n process.stderr.write(`${pc.yellow(\"create-baerly-storage:\")} git init skipped — ${hint}\\n`);\n }\n }\n if (install) {\n const installer = opts.installer ?? defaultInstaller;\n const { code } = await installer.run(pm, result.outDir);\n if (code !== 0) {\n process.stderr.write(\n `${pc.yellow(\"create-baerly-storage:\")} install exited with code ${code}. ` +\n `Run \\`${pm} install\\` in ${result.outDir} manually.\\n`,\n );\n }\n }\n if (jsonMode) {\n process.stdout.write(\n `${JSON.stringify({\n result: {\n command: \"create-baerly-storage\",\n status: \"ok\",\n outDir: result.outDir,\n filesWritten: result.filesWritten.length,\n nextSteps: result.nextSteps,\n },\n })}\\n`,\n );\n } else if (isInteractive) {\n outro(\n `${pc.green(\"✓\")} ${result.outDir}\\n` +\n `\\n Next steps:\\n` +\n result.nextSteps.map((s) => ` ${s}`).join(\"\\n\"),\n );\n } else {\n // Non-TTY, non-JSON: keep the existing plaintext output\n // bit-for-bit so any scripts parsing it don't break.\n process.stdout.write(`${pc.green(\"✓\")} scaffolded ${result.outDir}\\n`);\n process.stdout.write(`\\n Next steps:\\n`);\n for (const s of result.nextSteps) {\n process.stdout.write(` ${s}\\n`);\n }\n process.stdout.write(\"\\n\");\n }\n return 0;\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (jsonMode) {\n process.stderr.write(\n `${JSON.stringify({ error: { code: \"InvalidConfig\", message: msg, command: \"create-baerly-storage\" } })}\\n`,\n );\n } else {\n process.stderr.write(`${pc.red(\"create-baerly-storage:\")} ${msg}\\n`);\n }\n return 1;\n }\n};\n\nexport const main = defineCommand({\n meta: {\n name: \"create-baerly-storage\",\n version: \"0.0.0\",\n description: \"Scaffold a new baerly app (Cloudflare Worker or self-hosted Node).\",\n },\n args: CREATE_BAERLY_ARGS,\n run: async ({ args }) => {\n const code = await handleCreateBaerly(args);\n if (code !== 0) {\n process.exit(code);\n }\n },\n});\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runCreateBaerly = async (\n argv: readonly string[],\n opts: { readonly installer?: Installer; readonly gitRunner?: GitRunner } = {},\n): Promise<number> => {\n let parsed: ParsedArgs<typeof CREATE_BAERLY_ARGS>;\n try {\n parsed = parseArgs<typeof CREATE_BAERLY_ARGS>(argv as string[], CREATE_BAERLY_ARGS);\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (argv.includes(\"--json\")) {\n process.stderr.write(\n `${JSON.stringify({ error: { code: \"InvalidConfig\", message: msg, command: \"create-baerly-storage\" } })}\\n`,\n );\n } else {\n process.stderr.write(`${pc.red(\"create-baerly-storage:\")} ${msg}\\n`);\n }\n return 1;\n }\n return handleCreateBaerly(parsed, opts);\n};\n","/**\n * `create-baerly-storage` bin entry. Imports the citty command from `./runner.ts`\n * and dispatches via an inline `runBin` shim. Kept as a thin shim so\n * the runner module has no import-time side effects — tests can\n * import `runCreateBaerly` from `./runner.ts` directly without citty\n * running and calling `process.exit` inside vitest.\n *\n * The shim mirrors the shape of `@baerly/cli`'s `bin-runner.ts`\n * (same `--help` / `--version` interception, same `CLIError →\n * InvalidConfig` translation). Inlined here rather than imported\n * cross-package because `create-baerly-storage` is a separate publishable\n * with its own dependency surface — the cross-package import\n * overhead beats the dedup at this scale.\n */\nimport { runCommand, showUsage, type CommandMeta, type Resolvable } from \"citty\";\nimport pc from \"picocolors\";\nimport { main } from \"./runner.ts\";\n\nconst resolve = async <T>(v: Resolvable<T>): Promise<T> => {\n if (typeof v === \"function\") {\n return (v as () => T | Promise<T>)();\n }\n return v;\n};\n\nconst writeError = (json: boolean, code: string, message: string): void => {\n if (json) {\n process.stderr.write(\n `${JSON.stringify({ error: { code, message, command: \"create-baerly-storage\" } })}\\n`,\n );\n } else {\n process.stderr.write(`${pc.red(\"create-baerly-storage:\")} ${code}: ${message}\\n`);\n }\n};\n\nconst argv = process.argv.slice(2);\nconst wantJson = argv.includes(\"--json\");\n\nconst run = async (): Promise<void> => {\n if (argv.includes(\"--help\") || argv.includes(\"-h\")) {\n // create-baerly-storage has no subCommands, so the top-level command is\n // always the showUsage target.\n await showUsage(main);\n process.exit(0);\n }\n if (argv.includes(\"--version\") || argv.includes(\"-v\")) {\n const meta = (await resolve(main.meta as Resolvable<CommandMeta>)) ?? {};\n const version = meta.version;\n if (typeof version !== \"string\" || version.length === 0) {\n writeError(wantJson, \"InvalidConfig\", \"no version declared on this command\");\n process.exit(1);\n }\n process.stdout.write(`${version}\\n`);\n process.exit(0);\n }\n try {\n await runCommand(main, { rawArgs: [...argv] });\n process.exit(0);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n writeError(wantJson, \"InvalidConfig\", message);\n process.exit(1);\n }\n};\n\nvoid run();\n"],"x_google_ignoreList":[6,7,8,9,10,11],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAa,mBAA8B,EACzC,MAAM,MAAM,QAAQ;CAClB,MAAM,MAAM,UAAU,OAAO,CAAC,GAAG,IAAI,GAAG;EAAE;EAAK,UAAU;CAAO,CAAC;CACjE,IAAI,IAAI,UAAU,KAAA,GAChB,OAAO;EAAE,MAAM;EAAK,QAAQ;EAAI,QAAQ,IAAI,MAAM;CAAQ;CAE5D,OAAO;EACL,MAAM,IAAI,UAAU;EACpB,QAAQ,IAAI,UAAU;EACtB,QAAQ,IAAI,UAAU;CACxB;AACF,EACF;AA8BA,MAAM,QAAQ,MAAsB,EAAE,KAAK;AAE3C,MAAM,uBAAuB,KAAa,WAA+B;CACvE,MAAM,MAAM,OAAO,IAAI,CAAC,aAAa,uBAAuB,GAAG,GAAG;CAClE,OAAO,IAAI,SAAS,KAAK,KAAK,IAAI,MAAM,MAAM;AAChD;AAEA,MAAM,mBAAmB,KAAa,WAA0C;CAC9E,MAAM,MAAM,OAAO,IAAI,CAAC,WAAW,GAAG,GAAG;CACzC,IAAI,IAAI,SAAS,GACf;CAIF,MAAM,IAAI,qBAAqB,KAAK,KAAK,IAAI,MAAM,CAAC;CACpD,OAAO,MAAM,OAAO,KAAK,IAAI,MAAM,IAAI,EAAE;AAC3C;AAEA,MAAM,eAAe,KAAa,WAA+B;CAC/D,MAAM,OAAO,OAAO,IAAI,CAAC,UAAU,WAAW,GAAG,GAAG;CACpD,MAAM,QAAQ,OAAO,IAAI,CAAC,UAAU,YAAY,GAAG,GAAG;CACtD,OACE,KAAK,SAAS,KACd,MAAM,SAAS,KACf,KAAK,KAAK,MAAM,CAAC,CAAC,SAAS,KAC3B,KAAK,MAAM,MAAM,CAAC,CAAC,SAA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AS,CAAC,GAAG,IAAI,EAAE,CAAC;EAC7C,QAAQ,KAAK,CAAC;CAChB,SAAS,OAAO;EAEd,WAAW,UAAU,iBADL,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CACxB;EAC7C,QAAQ,KAAK,CAAC;CAChB;AACF;AAEK,IAAI"}
1
+ {"version":3,"file":"index.js","names":["runCommand","NO_TRUNCATION","fastStringTruncatedWidth","ESC","CSI","stringWidth","x","ConfirmPrompt","l","SelectPrompt","TextPrompt","resolve","resolve","parse","parser.parse","edit.setProperty","edit.applyEdit","dirname","fileExists","resolve","resolve","resolve","runCommand"],"sources":["../../../node_modules/.pnpm/citty@0.2.2/node_modules/citty/dist/_chunks/libs/scule.mjs","../../../node_modules/.pnpm/citty@0.2.2/node_modules/citty/dist/index.mjs","../../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/utils.js","../../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/index.js","../../../node_modules/.pnpm/fast-string-width@3.0.2/node_modules/fast-string-width/dist/index.js","../../../node_modules/.pnpm/fast-wrap-ansi@0.2.2/node_modules/fast-wrap-ansi/lib/main.js","../../../node_modules/.pnpm/sisteransi@2.0.0/node_modules/sisteransi/dist/index.js","../../../node_modules/.pnpm/@clack+core@1.6.0/node_modules/@clack/core/dist/index.mjs","../../../node_modules/.pnpm/@clack+prompts@1.9.0/node_modules/@clack/prompts/dist/index.mjs","../package.json","../src/git.ts","../src/prompts.ts","../src/pm-detect.ts","../src/substitute.ts","../src/scaffold.ts","../../protocol/src/errors.ts","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/format.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/edit.js","../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js","../../cli/src/wrangler-patch.ts","../src/init-snippet.ts","../src/install.ts","../src/agent-rules.ts","../src/bolt-on.ts","../src/runner.ts","../src/index.ts"],"sourcesContent":["//#region node_modules/.pnpm/scule@1.3.0/node_modules/scule/dist/index.mjs\nconst NUMBER_CHAR_RE = /\\d/;\nconst STR_SPLITTERS = [\n\t\"-\",\n\t\"_\",\n\t\"/\",\n\t\".\"\n];\nfunction isUppercase(char = \"\") {\n\tif (NUMBER_CHAR_RE.test(char)) return;\n\treturn char !== char.toLowerCase();\n}\nfunction splitByCase(str, separators) {\n\tconst splitters = separators ?? STR_SPLITTERS;\n\tconst parts = [];\n\tif (!str || typeof str !== \"string\") return parts;\n\tlet buff = \"\";\n\tlet previousUpper;\n\tlet previousSplitter;\n\tfor (const char of str) {\n\t\tconst isSplitter = splitters.includes(char);\n\t\tif (isSplitter === true) {\n\t\t\tparts.push(buff);\n\t\t\tbuff = \"\";\n\t\t\tpreviousUpper = void 0;\n\t\t\tcontinue;\n\t\t}\n\t\tconst isUpper = isUppercase(char);\n\t\tif (previousSplitter === false) {\n\t\t\tif (previousUpper === false && isUpper === true) {\n\t\t\t\tparts.push(buff);\n\t\t\t\tbuff = char;\n\t\t\t\tpreviousUpper = isUpper;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (previousUpper === true && isUpper === false && buff.length > 1) {\n\t\t\t\tconst lastChar = buff.at(-1);\n\t\t\t\tparts.push(buff.slice(0, Math.max(0, buff.length - 1)));\n\t\t\t\tbuff = lastChar + char;\n\t\t\t\tpreviousUpper = isUpper;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tbuff += char;\n\t\tpreviousUpper = isUpper;\n\t\tpreviousSplitter = isSplitter;\n\t}\n\tparts.push(buff);\n\treturn parts;\n}\nfunction upperFirst(str) {\n\treturn str ? str[0].toUpperCase() + str.slice(1) : \"\";\n}\nfunction lowerFirst(str) {\n\treturn str ? str[0].toLowerCase() + str.slice(1) : \"\";\n}\nfunction pascalCase(str, opts) {\n\treturn str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => upperFirst(opts?.normalize ? p.toLowerCase() : p)).join(\"\") : \"\";\n}\nfunction camelCase(str, opts) {\n\treturn lowerFirst(pascalCase(str || \"\", opts));\n}\nfunction kebabCase(str, joiner) {\n\treturn str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => p.toLowerCase()).join(joiner ?? \"-\") : \"\";\n}\nfunction snakeCase(str) {\n\treturn kebabCase(str || \"\", \"_\");\n}\n//#endregion\nexport { kebabCase as n, snakeCase as r, camelCase as t };\n","import { n as kebabCase, r as snakeCase, t as camelCase } from \"./_chunks/libs/scule.mjs\";\nimport { parseArgs as parseArgs$1 } from \"node:util\";\n//#region src/_utils.ts\nfunction toArray(val) {\n\tif (Array.isArray(val)) return val;\n\treturn val === void 0 ? [] : [val];\n}\nfunction formatLineColumns(lines, linePrefix = \"\") {\n\tconst maxLength = [];\n\tfor (const line of lines) for (const [i, element] of line.entries()) maxLength[i] = Math.max(maxLength[i] || 0, element.length);\n\treturn lines.map((l) => l.map((c, i) => linePrefix + c[i === 0 ? \"padStart\" : \"padEnd\"](maxLength[i])).join(\" \")).join(\"\\n\");\n}\nfunction resolveValue(input) {\n\treturn typeof input === \"function\" ? input() : input;\n}\nvar CLIError = class extends Error {\n\tcode;\n\tconstructor(message, code) {\n\t\tsuper(message);\n\t\tthis.name = \"CLIError\";\n\t\tthis.code = code;\n\t}\n};\n//#endregion\n//#region src/_parser.ts\nfunction parseRawArgs(args = [], opts = {}) {\n\tconst booleans = new Set(opts.boolean || []);\n\tconst strings = new Set(opts.string || []);\n\tconst aliasMap = opts.alias || {};\n\tconst defaults = opts.default || {};\n\tconst aliasToMain = /* @__PURE__ */ new Map();\n\tconst mainToAliases = /* @__PURE__ */ new Map();\n\tfor (const [key, value] of Object.entries(aliasMap)) {\n\t\tconst targets = value;\n\t\tfor (const target of targets) {\n\t\t\taliasToMain.set(key, target);\n\t\t\tif (!mainToAliases.has(target)) mainToAliases.set(target, []);\n\t\t\tmainToAliases.get(target).push(key);\n\t\t\taliasToMain.set(target, key);\n\t\t\tif (!mainToAliases.has(key)) mainToAliases.set(key, []);\n\t\t\tmainToAliases.get(key).push(target);\n\t\t}\n\t}\n\tconst options = {};\n\tfunction getType(name) {\n\t\tif (booleans.has(name)) return \"boolean\";\n\t\tconst aliases = mainToAliases.get(name) || [];\n\t\tfor (const alias of aliases) if (booleans.has(alias)) return \"boolean\";\n\t\treturn \"string\";\n\t}\n\tfunction isStringType(name) {\n\t\tif (strings.has(name)) return true;\n\t\tconst aliases = mainToAliases.get(name) || [];\n\t\tfor (const alias of aliases) if (strings.has(alias)) return true;\n\t\treturn false;\n\t}\n\tconst allOptions = new Set([\n\t\t...booleans,\n\t\t...strings,\n\t\t...Object.keys(aliasMap),\n\t\t...Object.values(aliasMap).flat(),\n\t\t...Object.keys(defaults)\n\t]);\n\tfor (const name of allOptions) if (!options[name]) options[name] = {\n\t\ttype: getType(name),\n\t\tdefault: defaults[name]\n\t};\n\tfor (const [alias, main] of aliasToMain.entries()) if (alias.length === 1 && options[main] && !options[main].short) options[main].short = alias;\n\tconst processedArgs = [];\n\tconst negatedFlags = {};\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\t\tif (arg === \"--\") {\n\t\t\tprocessedArgs.push(...args.slice(i));\n\t\t\tbreak;\n\t\t}\n\t\tif (arg.startsWith(\"--no-\")) {\n\t\t\tconst flagName = arg.slice(5);\n\t\t\tnegatedFlags[flagName] = true;\n\t\t\tcontinue;\n\t\t}\n\t\tprocessedArgs.push(arg);\n\t}\n\tlet parsed;\n\ttry {\n\t\tparsed = parseArgs$1({\n\t\t\targs: processedArgs,\n\t\t\toptions: Object.keys(options).length > 0 ? options : void 0,\n\t\t\tallowPositionals: true,\n\t\t\tstrict: false\n\t\t});\n\t} catch {\n\t\tparsed = {\n\t\t\tvalues: {},\n\t\t\tpositionals: processedArgs\n\t\t};\n\t}\n\tconst out = { _: [] };\n\tout._ = parsed.positionals;\n\tfor (const [key, value] of Object.entries(parsed.values)) {\n\t\tlet coerced = value;\n\t\tif (getType(key) === \"boolean\" && typeof value === \"string\") coerced = value !== \"false\";\n\t\telse if (isStringType(key) && typeof value === \"boolean\") coerced = \"\";\n\t\tout[key] = coerced;\n\t}\n\tfor (const [name] of Object.entries(negatedFlags)) {\n\t\tout[name] = false;\n\t\tconst mainName = aliasToMain.get(name);\n\t\tif (mainName) out[mainName] = false;\n\t\tconst aliases = mainToAliases.get(name);\n\t\tif (aliases) for (const alias of aliases) out[alias] = false;\n\t}\n\tfor (const [alias, main] of aliasToMain.entries()) {\n\t\tif (out[alias] !== void 0 && out[main] === void 0) out[main] = out[alias];\n\t\tif (out[main] !== void 0 && out[alias] === void 0) out[alias] = out[main];\n\t\tif (out[alias] !== out[main] && defaults[main] === out[main]) out[main] = out[alias];\n\t}\n\treturn out;\n}\n//#endregion\n//#region src/_color.ts\nconst noColor = /* @__PURE__ */ (() => {\n\tconst env = globalThis.process?.env ?? {};\n\treturn env.NO_COLOR === \"1\" || env.TERM === \"dumb\" || env.TEST || env.CI;\n})();\nconst _c = (c, r = 39) => (t) => noColor ? t : `\\u001B[${c}m${t}\\u001B[${r}m`;\nconst bold = /* @__PURE__ */ _c(1, 22);\nconst cyan = /* @__PURE__ */ _c(36);\nconst gray = /* @__PURE__ */ _c(90);\nconst underline = /* @__PURE__ */ _c(4, 24);\n//#endregion\n//#region src/args.ts\nfunction parseArgs(rawArgs, argsDef) {\n\tconst parseOptions = {\n\t\tboolean: [],\n\t\tstring: [],\n\t\talias: {},\n\t\tdefault: {}\n\t};\n\tconst args = resolveArgs(argsDef);\n\tfor (const arg of args) {\n\t\tif (arg.type === \"positional\") continue;\n\t\tif (arg.type === \"string\" || arg.type === \"enum\") parseOptions.string.push(arg.name);\n\t\telse if (arg.type === \"boolean\") parseOptions.boolean.push(arg.name);\n\t\tif (arg.default !== void 0) parseOptions.default[arg.name] = arg.default;\n\t\tif (arg.alias) parseOptions.alias[arg.name] = arg.alias;\n\t\tconst camelName = camelCase(arg.name);\n\t\tconst kebabName = kebabCase(arg.name);\n\t\tif (camelName !== arg.name || kebabName !== arg.name) {\n\t\t\tconst existingAliases = toArray(parseOptions.alias[arg.name] || []);\n\t\t\tif (camelName !== arg.name && !existingAliases.includes(camelName)) existingAliases.push(camelName);\n\t\t\tif (kebabName !== arg.name && !existingAliases.includes(kebabName)) existingAliases.push(kebabName);\n\t\t\tif (existingAliases.length > 0) parseOptions.alias[arg.name] = existingAliases;\n\t\t}\n\t}\n\tconst parsed = parseRawArgs(rawArgs, parseOptions);\n\tconst [ ...positionalArguments] = parsed._;\n\tconst parsedArgsProxy = new Proxy(parsed, { get(target, prop) {\n\t\treturn target[prop] ?? target[camelCase(prop)] ?? target[kebabCase(prop)];\n\t} });\n\tfor (const [, arg] of args.entries()) if (arg.type === \"positional\") {\n\t\tconst nextPositionalArgument = positionalArguments.shift();\n\t\tif (nextPositionalArgument !== void 0) parsedArgsProxy[arg.name] = nextPositionalArgument;\n\t\telse if (arg.default === void 0 && arg.required !== false) throw new CLIError(`Missing required positional argument: ${arg.name.toUpperCase()}`, \"EARG\");\n\t\telse parsedArgsProxy[arg.name] = arg.default;\n\t} else if (arg.type === \"enum\") {\n\t\tconst argument = parsedArgsProxy[arg.name];\n\t\tconst options = arg.options || [];\n\t\tif (argument !== void 0 && options.length > 0 && !options.includes(argument)) throw new CLIError(`Invalid value for argument: ${cyan(`--${arg.name}`)} (${cyan(argument)}). Expected one of: ${options.map((o) => cyan(o)).join(\", \")}.`, \"EARG\");\n\t} else if (arg.required && parsedArgsProxy[arg.name] === void 0) throw new CLIError(`Missing required argument: --${arg.name}`, \"EARG\");\n\treturn parsedArgsProxy;\n}\nfunction resolveArgs(argsDef) {\n\tconst args = [];\n\tfor (const [name, argDef] of Object.entries(argsDef || {})) args.push({\n\t\t...argDef,\n\t\tname,\n\t\talias: toArray(argDef.alias)\n\t});\n\treturn args;\n}\n//#endregion\n//#region src/plugin.ts\nfunction defineCittyPlugin(plugin) {\n\treturn plugin;\n}\nasync function resolvePlugins(plugins) {\n\treturn Promise.all(plugins.map((p) => resolveValue(p)));\n}\n//#endregion\n//#region src/command.ts\nfunction defineCommand(def) {\n\treturn def;\n}\nasync function runCommand(cmd, opts) {\n\tconst cmdArgs = await resolveValue(cmd.args || {});\n\tconst parsedArgs = parseArgs(opts.rawArgs, cmdArgs);\n\tconst context = {\n\t\trawArgs: opts.rawArgs,\n\t\targs: parsedArgs,\n\t\tdata: opts.data,\n\t\tcmd\n\t};\n\tconst plugins = await resolvePlugins(cmd.plugins ?? []);\n\tlet result;\n\tlet runError;\n\ttry {\n\t\tfor (const plugin of plugins) await plugin.setup?.(context);\n\t\tif (typeof cmd.setup === \"function\") await cmd.setup(context);\n\t\tconst subCommands = await resolveValue(cmd.subCommands);\n\t\tif (subCommands && Object.keys(subCommands).length > 0) {\n\t\t\tconst subCommandArgIndex = findSubCommandIndex(opts.rawArgs, cmdArgs);\n\t\t\tconst explicitName = opts.rawArgs[subCommandArgIndex];\n\t\t\tif (explicitName) {\n\t\t\t\tconst subCommand = await _findSubCommand(subCommands, explicitName);\n\t\t\t\tif (!subCommand) throw new CLIError(`Unknown command ${cyan(explicitName)}`, \"E_UNKNOWN_COMMAND\");\n\t\t\t\tawait runCommand(subCommand, { rawArgs: opts.rawArgs.slice(subCommandArgIndex + 1) });\n\t\t\t} else {\n\t\t\t\tconst defaultSubCommand = await resolveValue(cmd.default);\n\t\t\t\tif (defaultSubCommand) {\n\t\t\t\t\tif (cmd.run) throw new CLIError(`Cannot specify both 'run' and 'default' on the same command.`, \"E_DEFAULT_CONFLICT\");\n\t\t\t\t\tconst subCommand = await _findSubCommand(subCommands, defaultSubCommand);\n\t\t\t\t\tif (!subCommand) throw new CLIError(`Default sub command ${cyan(defaultSubCommand)} not found in subCommands.`, \"E_UNKNOWN_COMMAND\");\n\t\t\t\t\tawait runCommand(subCommand, { rawArgs: opts.rawArgs });\n\t\t\t\t} else if (!cmd.run) throw new CLIError(`No command specified.`, \"E_NO_COMMAND\");\n\t\t\t}\n\t\t}\n\t\tif (typeof cmd.run === \"function\") result = await cmd.run(context);\n\t} catch (error) {\n\t\trunError = error;\n\t}\n\tconst cleanupErrors = [];\n\tif (typeof cmd.cleanup === \"function\") try {\n\t\tawait cmd.cleanup(context);\n\t} catch (error) {\n\t\tcleanupErrors.push(error);\n\t}\n\tfor (const plugin of [...plugins].reverse()) try {\n\t\tawait plugin.cleanup?.(context);\n\t} catch (error) {\n\t\tcleanupErrors.push(error);\n\t}\n\tif (runError) throw runError;\n\tif (cleanupErrors.length === 1) throw cleanupErrors[0];\n\tif (cleanupErrors.length > 1) throw new Error(\"Multiple cleanup errors\", { cause: cleanupErrors });\n\treturn { result };\n}\nasync function resolveSubCommand(cmd, rawArgs, parent) {\n\tconst subCommands = await resolveValue(cmd.subCommands);\n\tif (subCommands && Object.keys(subCommands).length > 0) {\n\t\tconst subCommandArgIndex = findSubCommandIndex(rawArgs, await resolveValue(cmd.args || {}));\n\t\tconst subCommandName = rawArgs[subCommandArgIndex];\n\t\tconst subCommand = await _findSubCommand(subCommands, subCommandName);\n\t\tif (subCommand) return resolveSubCommand(subCommand, rawArgs.slice(subCommandArgIndex + 1), cmd);\n\t}\n\treturn [cmd, parent];\n}\nasync function _findSubCommand(subCommands, name) {\n\tif (name in subCommands) return resolveValue(subCommands[name]);\n\tfor (const sub of Object.values(subCommands)) {\n\t\tconst resolved = await resolveValue(sub);\n\t\tconst meta = await resolveValue(resolved?.meta);\n\t\tif (meta?.alias) {\n\t\t\tif (toArray(meta.alias).includes(name)) return resolved;\n\t\t}\n\t}\n}\nfunction findSubCommandIndex(rawArgs, argsDef) {\n\tfor (let i = 0; i < rawArgs.length; i++) {\n\t\tconst arg = rawArgs[i];\n\t\tif (arg === \"--\") return -1;\n\t\tif (arg.startsWith(\"-\")) {\n\t\t\tif (!arg.includes(\"=\") && _isValueFlag(arg, argsDef)) i++;\n\t\t\tcontinue;\n\t\t}\n\t\treturn i;\n\t}\n\treturn -1;\n}\nfunction _isValueFlag(flag, argsDef) {\n\tconst name = flag.replace(/^-{1,2}/, \"\");\n\tconst normalized = camelCase(name);\n\tfor (const [key, def] of Object.entries(argsDef)) {\n\t\tif (def.type !== \"string\" && def.type !== \"enum\") continue;\n\t\tif (normalized === camelCase(key)) return true;\n\t\tif ((Array.isArray(def.alias) ? def.alias : def.alias ? [def.alias] : []).includes(name)) return true;\n\t}\n\treturn false;\n}\n//#endregion\n//#region src/usage.ts\nasync function showUsage(cmd, parent) {\n\ttry {\n\t\tconsole.log(await renderUsage(cmd, parent) + \"\\n\");\n\t} catch (error) {\n\t\tconsole.error(error);\n\t}\n}\nconst negativePrefixRe = /^no[-A-Z]/;\nasync function renderUsage(cmd, parent) {\n\tconst cmdMeta = await resolveValue(cmd.meta || {});\n\tconst cmdArgs = resolveArgs(await resolveValue(cmd.args || {}));\n\tconst parentMeta = await resolveValue(parent?.meta || {});\n\tconst commandName = `${parentMeta.name ? `${parentMeta.name} ` : \"\"}` + (cmdMeta.name || process.argv[1]);\n\tconst argLines = [];\n\tconst posLines = [];\n\tconst commandsLines = [];\n\tconst usageLine = [];\n\tfor (const arg of cmdArgs) if (arg.type === \"positional\") {\n\t\tconst name = arg.name.toUpperCase();\n\t\tconst isRequired = arg.required !== false && arg.default === void 0;\n\t\tposLines.push([cyan(name + renderValueHint(arg)), renderDescription(arg, isRequired)]);\n\t\tusageLine.push(isRequired ? `<${name}>` : `[${name}]`);\n\t} else {\n\t\tconst isRequired = arg.required === true && arg.default === void 0;\n\t\tconst argStr = [...(arg.alias || []).map((a) => `-${a}`), `--${arg.name}`].join(\", \") + renderValueHint(arg);\n\t\targLines.push([cyan(argStr), renderDescription(arg, isRequired)]);\n\t\t/**\n\t\t* print negative boolean arg variant usage when\n\t\t* - enabled by default or has `negativeDescription`\n\t\t* - not prefixed with `no-` or `no[A-Z]`\n\t\t*/\n\t\tif (arg.type === \"boolean\" && (arg.default === true || arg.negativeDescription) && !negativePrefixRe.test(arg.name)) {\n\t\t\tconst negativeArgStr = [...(arg.alias || []).map((a) => `--no-${a}`), `--no-${arg.name}`].join(\", \");\n\t\t\targLines.push([cyan(negativeArgStr), [arg.negativeDescription, isRequired ? gray(\"(Required)\") : \"\"].filter(Boolean).join(\" \")]);\n\t\t}\n\t\tif (isRequired) usageLine.push(`--${arg.name}` + renderValueHint(arg));\n\t}\n\tif (cmd.subCommands) {\n\t\tconst commandNames = [];\n\t\tconst subCommands = await resolveValue(cmd.subCommands);\n\t\tfor (const [name, sub] of Object.entries(subCommands)) {\n\t\t\tconst meta = await resolveValue((await resolveValue(sub))?.meta);\n\t\t\tif (meta?.hidden) continue;\n\t\t\tconst aliases = toArray(meta?.alias);\n\t\t\tconst label = [name, ...aliases].join(\", \");\n\t\t\tcommandsLines.push([cyan(label), meta?.description || \"\"]);\n\t\t\tcommandNames.push(name, ...aliases);\n\t\t}\n\t\tusageLine.push(commandNames.join(\"|\"));\n\t}\n\tconst usageLines = [];\n\tconst version = cmdMeta.version || parentMeta.version;\n\tusageLines.push(gray(`${cmdMeta.description} (${commandName + (version ? ` v${version}` : \"\")})`), \"\");\n\tconst hasOptions = argLines.length > 0 || posLines.length > 0;\n\tusageLines.push(`${underline(bold(\"USAGE\"))} ${cyan(`${commandName}${hasOptions ? \" [OPTIONS]\" : \"\"} ${usageLine.join(\" \")}`)}`, \"\");\n\tif (posLines.length > 0) {\n\t\tusageLines.push(underline(bold(\"ARGUMENTS\")), \"\");\n\t\tusageLines.push(formatLineColumns(posLines, \" \"));\n\t\tusageLines.push(\"\");\n\t}\n\tif (argLines.length > 0) {\n\t\tusageLines.push(underline(bold(\"OPTIONS\")), \"\");\n\t\tusageLines.push(formatLineColumns(argLines, \" \"));\n\t\tusageLines.push(\"\");\n\t}\n\tif (commandsLines.length > 0) {\n\t\tusageLines.push(underline(bold(\"COMMANDS\")), \"\");\n\t\tusageLines.push(formatLineColumns(commandsLines, \" \"));\n\t\tusageLines.push(\"\", `Use ${cyan(`${commandName} <command> --help`)} for more information about a command.`);\n\t}\n\treturn usageLines.filter((l) => typeof l === \"string\").join(\"\\n\");\n}\nfunction renderValueHint(arg) {\n\tconst valueHint = arg.valueHint ? `=<${arg.valueHint}>` : \"\";\n\tconst fallbackValueHint = valueHint || `=<${snakeCase(arg.name)}>`;\n\tif (!arg.type || arg.type === \"positional\" || arg.type === \"boolean\") return valueHint;\n\tif (arg.type === \"enum\" && arg.options?.length) return `=<${arg.options.join(\"|\")}>`;\n\treturn fallbackValueHint;\n}\nfunction renderDescription(arg, required) {\n\tconst requiredHint = required ? gray(\"(Required)\") : \"\";\n\tconst defaultHint = arg.default === void 0 ? \"\" : gray(`(Default: ${arg.default})`);\n\treturn [\n\t\targ.description,\n\t\trequiredHint,\n\t\tdefaultHint\n\t].filter(Boolean).join(\" \");\n}\n//#endregion\n//#region src/main.ts\nasync function runMain(cmd, opts = {}) {\n\tconst rawArgs = opts.rawArgs || process.argv.slice(2);\n\tconst showUsage$1 = opts.showUsage || showUsage;\n\ttry {\n\t\tconst builtinFlags = await _resolveBuiltinFlags(cmd);\n\t\tif (builtinFlags.help.length > 0 && rawArgs.some((arg) => builtinFlags.help.includes(arg))) {\n\t\t\tawait showUsage$1(...await resolveSubCommand(cmd, rawArgs));\n\t\t\tprocess.exit(0);\n\t\t} else if (rawArgs.length === 1 && builtinFlags.version.includes(rawArgs[0])) {\n\t\t\tconst meta = typeof cmd.meta === \"function\" ? await cmd.meta() : await cmd.meta;\n\t\t\tif (!meta?.version) throw new CLIError(\"No version specified\", \"E_NO_VERSION\");\n\t\t\tconsole.log(meta.version);\n\t\t} else await runCommand(cmd, { rawArgs });\n\t} catch (error) {\n\t\tif (error instanceof CLIError) {\n\t\t\tawait showUsage$1(...await resolveSubCommand(cmd, rawArgs));\n\t\t\tconsole.error(error.message);\n\t\t} else console.error(error, \"\\n\");\n\t\tprocess.exit(1);\n\t}\n}\nfunction createMain(cmd) {\n\treturn (opts = {}) => runMain(cmd, opts);\n}\nasync function _resolveBuiltinFlags(cmd) {\n\tconst argsDef = await resolveValue(cmd.args || {});\n\tconst userNames = /* @__PURE__ */ new Set();\n\tconst userAliases = /* @__PURE__ */ new Set();\n\tfor (const [name, def] of Object.entries(argsDef)) {\n\t\tuserNames.add(name);\n\t\tfor (const alias of toArray(def.alias)) userAliases.add(alias);\n\t}\n\treturn {\n\t\thelp: _getBuiltinFlags(\"help\", \"h\", userNames, userAliases),\n\t\tversion: _getBuiltinFlags(\"version\", \"v\", userNames, userAliases)\n\t};\n}\nfunction _getBuiltinFlags(long, short, userNames, userAliases) {\n\tif (userNames.has(long) || userAliases.has(long)) return [];\n\tif (userNames.has(short) || userAliases.has(short)) return [`--${long}`];\n\treturn [`--${long}`, `-${short}`];\n}\n//#endregion\nexport { createMain, defineCittyPlugin, defineCommand, parseArgs, renderUsage, runCommand, runMain, showUsage };\n","/* MAIN */\nconst getCodePointsLength = (() => {\n const SURROGATE_PAIR_RE = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g;\n return (input) => {\n let surrogatePairsNr = 0;\n SURROGATE_PAIR_RE.lastIndex = 0;\n while (SURROGATE_PAIR_RE.test(input)) {\n surrogatePairsNr += 1;\n }\n return input.length - surrogatePairsNr;\n };\n})();\nconst isFullWidth = (x) => {\n return x === 0x3000 || x >= 0xFF01 && x <= 0xFF60 || x >= 0xFFE0 && x <= 0xFFE6;\n};\nconst isWideNotCJKTNotEmoji = (x) => {\n return x === 0x231B || x === 0x2329 || x >= 0x2FF0 && x <= 0x2FFF || x >= 0x3001 && x <= 0x303E || x >= 0x3099 && x <= 0x30FF || x >= 0x3105 && x <= 0x312F || x >= 0x3131 && x <= 0x318E || x >= 0x3190 && x <= 0x31E3 || x >= 0x31EF && x <= 0x321E || x >= 0x3220 && x <= 0x3247 || x >= 0x3250 && x <= 0x4DBF || x >= 0xFE10 && x <= 0xFE19 || x >= 0xFE30 && x <= 0xFE52 || x >= 0xFE54 && x <= 0xFE66 || x >= 0xFE68 && x <= 0xFE6B || x >= 0x1F200 && x <= 0x1F202 || x >= 0x1F210 && x <= 0x1F23B || x >= 0x1F240 && x <= 0x1F248 || x >= 0x20000 && x <= 0x2FFFD || x >= 0x30000 && x <= 0x3FFFD;\n};\n/* EXPORT */\nexport { getCodePointsLength, isFullWidth, isWideNotCJKTNotEmoji };\n","/* IMPORT */\nimport { getCodePointsLength, isFullWidth, isWideNotCJKTNotEmoji } from './utils.js';\n/* HELPERS */\nconst ANSI_RE = /[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\\u001b\\]8;[^;]*;.*?(?:\\u0007|\\u001b\\u005c)/y;\nconst CONTROL_RE = /[\\x00-\\x08\\x0A-\\x1F\\x7F-\\x9F]{1,1000}/y;\nconst CJKT_WIDE_RE = /(?:(?![\\uFF61-\\uFF9F\\uFF00-\\uFFEF])[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}\\p{Script=Tangut}]){1,1000}/yu;\nconst TAB_RE = /\\t{1,1000}/y;\nconst EMOJI_RE = /[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*/yu;\nconst LATIN_RE = /(?:[\\x20-\\x7E\\xA0-\\xFF](?!\\uFE0F)){1,1000}/y;\nconst MODIFIER_RE = /\\p{M}+/gu;\nconst NO_TRUNCATION = { limit: Infinity, ellipsis: '' };\n/* MAIN */\nconst getStringTruncatedWidth = (input, truncationOptions = {}, widthOptions = {}) => {\n /* CONSTANTS */\n const LIMIT = truncationOptions.limit ?? Infinity;\n const ELLIPSIS = truncationOptions.ellipsis ?? '';\n const ELLIPSIS_WIDTH = truncationOptions?.ellipsisWidth ?? (ELLIPSIS ? getStringTruncatedWidth(ELLIPSIS, NO_TRUNCATION, widthOptions).width : 0);\n const ANSI_WIDTH = 0;\n const CONTROL_WIDTH = widthOptions.controlWidth ?? 0;\n const TAB_WIDTH = widthOptions.tabWidth ?? 8;\n const EMOJI_WIDTH = widthOptions.emojiWidth ?? 2;\n const FULL_WIDTH_WIDTH = 2;\n const REGULAR_WIDTH = widthOptions.regularWidth ?? 1;\n const WIDE_WIDTH = widthOptions.wideWidth ?? FULL_WIDTH_WIDTH;\n const PARSE_BLOCKS = [\n [LATIN_RE, REGULAR_WIDTH],\n [ANSI_RE, ANSI_WIDTH],\n [CONTROL_RE, CONTROL_WIDTH],\n [TAB_RE, TAB_WIDTH],\n [EMOJI_RE, EMOJI_WIDTH],\n [CJKT_WIDE_RE, WIDE_WIDTH],\n ];\n /* STATE */\n let indexPrev = 0;\n let index = 0;\n let length = input.length;\n let lengthExtra = 0;\n let truncationEnabled = false;\n let truncationIndex = length;\n let truncationLimit = Math.max(0, LIMIT - ELLIPSIS_WIDTH);\n let unmatchedStart = 0;\n let unmatchedEnd = 0;\n let width = 0;\n let widthExtra = 0;\n /* PARSE LOOP */\n outer: while (true) {\n /* UNMATCHED */\n if ((unmatchedEnd > unmatchedStart) || (index >= length && index > indexPrev)) {\n const unmatched = input.slice(unmatchedStart, unmatchedEnd) || input.slice(indexPrev, index);\n lengthExtra = 0;\n for (const char of unmatched.replaceAll(MODIFIER_RE, '')) {\n const codePoint = char.codePointAt(0) || 0;\n if (isFullWidth(codePoint)) {\n widthExtra = FULL_WIDTH_WIDTH;\n }\n else if (isWideNotCJKTNotEmoji(codePoint)) {\n widthExtra = WIDE_WIDTH;\n }\n else {\n widthExtra = REGULAR_WIDTH;\n }\n if ((width + widthExtra) > truncationLimit) {\n truncationIndex = Math.min(truncationIndex, Math.max(unmatchedStart, indexPrev) + lengthExtra);\n }\n if ((width + widthExtra) > LIMIT) {\n truncationEnabled = true;\n break outer;\n }\n lengthExtra += char.length;\n width += widthExtra;\n }\n unmatchedStart = unmatchedEnd = 0;\n }\n /* EXITING */\n if (index >= length) {\n break outer;\n }\n /* PARSE BLOCKS */\n for (let i = 0, l = PARSE_BLOCKS.length; i < l; i++) {\n const [BLOCK_RE, BLOCK_WIDTH] = PARSE_BLOCKS[i];\n BLOCK_RE.lastIndex = index;\n if (BLOCK_RE.test(input)) {\n lengthExtra = BLOCK_RE === CJKT_WIDE_RE ? getCodePointsLength(input.slice(index, BLOCK_RE.lastIndex)) : BLOCK_RE === EMOJI_RE ? 1 : BLOCK_RE.lastIndex - index;\n widthExtra = lengthExtra * BLOCK_WIDTH;\n if ((width + widthExtra) > truncationLimit) {\n truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / BLOCK_WIDTH));\n }\n if ((width + widthExtra) > LIMIT) {\n truncationEnabled = true;\n break outer;\n }\n width += widthExtra;\n unmatchedStart = indexPrev;\n unmatchedEnd = index;\n index = indexPrev = BLOCK_RE.lastIndex;\n continue outer;\n }\n }\n /* UNMATCHED INDEX */\n index += 1;\n }\n /* RETURN */\n return {\n width: truncationEnabled ? truncationLimit : width,\n index: truncationEnabled ? truncationIndex : length,\n truncated: truncationEnabled,\n ellipsed: truncationEnabled && LIMIT >= ELLIPSIS_WIDTH\n };\n};\n/* EXPORT */\nexport default getStringTruncatedWidth;\n","/* IMPORT */\nimport fastStringTruncatedWidth from 'fast-string-truncated-width';\n/* HELPERS */\nconst NO_TRUNCATION = {\n limit: Infinity,\n ellipsis: '',\n ellipsisWidth: 0,\n};\n/* MAIN */\nconst fastStringWidth = (input, options = {}) => {\n return fastStringTruncatedWidth(input, NO_TRUNCATION, options).width;\n};\n/* EXPORT */\nexport default fastStringWidth;\n","import stringWidth from 'fast-string-width';\nconst ESC = '\\x1B';\nconst CSI = '\\x9B';\nconst END_CODE = 39;\nconst ANSI_ESCAPE_BELL = '\\u0007';\nconst ANSI_CSI = '[';\nconst ANSI_OSC = ']';\nconst ANSI_SGR_TERMINATOR = 'm';\nconst ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;\nconst GROUP_REGEX = new RegExp(`(?:\\\\${ANSI_CSI}(?<code>\\\\d+)m|\\\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`, 'y');\nconst getClosingCode = (openingCode) => {\n if (openingCode >= 30 && openingCode <= 37)\n return 39;\n if (openingCode >= 90 && openingCode <= 97)\n return 39;\n if (openingCode >= 40 && openingCode <= 47)\n return 49;\n if (openingCode >= 100 && openingCode <= 107)\n return 49;\n if (openingCode === 1 || openingCode === 2)\n return 22;\n if (openingCode === 3)\n return 23;\n if (openingCode === 4)\n return 24;\n if (openingCode === 7)\n return 27;\n if (openingCode === 8)\n return 28;\n if (openingCode === 9)\n return 29;\n if (openingCode === 0)\n return 0;\n return undefined;\n};\nconst wrapAnsiCode = (code) => `${ESC}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;\nconst wrapAnsiHyperlink = (url) => `${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;\nconst wrapWord = (rows, word, columns) => {\n const characters = word[Symbol.iterator]();\n let isInsideEscape = false;\n let isInsideLinkEscape = false;\n let lastRow = rows.at(-1);\n let visible = lastRow === undefined ? 0 : stringWidth(lastRow);\n let currentCharacter = characters.next();\n let nextCharacter = characters.next();\n let rawCharacterIndex = 0;\n while (!currentCharacter.done) {\n const character = currentCharacter.value;\n const characterLength = stringWidth(character);\n if (visible + characterLength <= columns) {\n rows[rows.length - 1] += character;\n }\n else {\n rows.push(character);\n visible = 0;\n }\n if (character === ESC || character === CSI) {\n isInsideEscape = true;\n isInsideLinkEscape = word.startsWith(ANSI_ESCAPE_LINK, rawCharacterIndex + 1);\n }\n if (isInsideEscape) {\n if (isInsideLinkEscape) {\n if (character === ANSI_ESCAPE_BELL) {\n isInsideEscape = false;\n isInsideLinkEscape = false;\n }\n }\n else if (character === ANSI_SGR_TERMINATOR) {\n isInsideEscape = false;\n }\n }\n else {\n visible += characterLength;\n if (visible === columns && !nextCharacter.done) {\n rows.push('');\n visible = 0;\n }\n }\n currentCharacter = nextCharacter;\n nextCharacter = characters.next();\n rawCharacterIndex += character.length;\n }\n lastRow = rows.at(-1);\n if (!visible && lastRow !== undefined && lastRow.length && rows.length > 1) {\n rows[rows.length - 2] += rows.pop();\n }\n};\nconst stringVisibleTrimSpacesRight = (string) => {\n const words = string.split(' ');\n let last = words.length;\n while (last) {\n if (stringWidth(words[last - 1])) {\n break;\n }\n last--;\n }\n if (last === words.length) {\n return string;\n }\n return words.slice(0, last).join(' ') + words.slice(last).join('');\n};\nconst exec = (string, columns, options = {}) => {\n if (options.trim !== false && string.trim() === '') {\n return '';\n }\n let returnValue = '';\n let escapeCode;\n let escapeUrl;\n const words = string.split(' ');\n let rows = [''];\n let rowLength = 0;\n for (let index = 0; index < words.length; index++) {\n const word = words[index];\n if (options.trim !== false) {\n const row = rows.at(-1) ?? '';\n const trimmed = row.trimStart();\n if (row.length !== trimmed.length) {\n rows[rows.length - 1] = trimmed;\n rowLength = stringWidth(trimmed);\n }\n }\n if (index !== 0) {\n if (rowLength >= columns &&\n (options.wordWrap === false || options.trim === false)) {\n rows.push('');\n rowLength = 0;\n }\n if (rowLength || options.trim === false) {\n rows[rows.length - 1] += ' ';\n rowLength++;\n }\n }\n const wordLength = stringWidth(word);\n if (options.hard && wordLength > columns) {\n const remainingColumns = columns - rowLength;\n const breaksStartingThisLine = 1 + Math.floor((wordLength - remainingColumns - 1) / columns);\n const breaksStartingNextLine = Math.floor((wordLength - 1) / columns);\n if (breaksStartingNextLine < breaksStartingThisLine) {\n rows.push('');\n }\n wrapWord(rows, word, columns);\n rowLength = stringWidth(rows.at(-1) ?? '');\n continue;\n }\n if (rowLength + wordLength > columns && rowLength && wordLength) {\n if (options.wordWrap === false && rowLength < columns) {\n wrapWord(rows, word, columns);\n rowLength = stringWidth(rows.at(-1) ?? '');\n continue;\n }\n rows.push('');\n rowLength = 0;\n }\n if (rowLength + wordLength > columns && options.wordWrap === false) {\n wrapWord(rows, word, columns);\n rowLength = stringWidth(rows.at(-1) ?? '');\n continue;\n }\n rows[rows.length - 1] += word;\n rowLength += wordLength;\n }\n if (options.trim !== false) {\n rows = rows.map((row) => stringVisibleTrimSpacesRight(row));\n }\n const preString = rows.join('\\n');\n let inSurrogate = false;\n for (let i = 0; i < preString.length; i++) {\n const character = preString[i];\n returnValue += character;\n if (!inSurrogate) {\n inSurrogate = character >= '\\ud800' && character <= '\\udbff';\n if (inSurrogate) {\n continue;\n }\n }\n else {\n inSurrogate = false;\n }\n if (character === ESC || character === CSI) {\n GROUP_REGEX.lastIndex = i + 1;\n const groupsResult = GROUP_REGEX.exec(preString);\n const groups = groupsResult?.groups;\n if (groups?.code !== undefined) {\n const code = Number.parseFloat(groups.code);\n escapeCode = code === END_CODE ? undefined : code;\n }\n else if (groups?.uri !== undefined) {\n escapeUrl = groups.uri.length === 0 ? undefined : groups.uri;\n }\n }\n if (preString[i + 1] === '\\n') {\n if (escapeUrl) {\n returnValue += wrapAnsiHyperlink('');\n }\n const closingCode = escapeCode ? getClosingCode(escapeCode) : undefined;\n if (escapeCode && closingCode) {\n returnValue += wrapAnsiCode(closingCode);\n }\n }\n else if (character === '\\n') {\n if (escapeCode && getClosingCode(escapeCode)) {\n returnValue += wrapAnsiCode(escapeCode);\n }\n if (escapeUrl) {\n returnValue += wrapAnsiHyperlink(escapeUrl);\n }\n }\n }\n return returnValue;\n};\nconst CRLF_OR_LF = /\\r?\\n/;\nexport function wrapAnsi(string, columns, options) {\n return String(string)\n .normalize()\n .split(CRLF_OR_LF)\n .map((line) => exec(line, columns, options))\n .join('\\n');\n}\n","const ESC = '\\x1B';\nconst CSI = `${ESC}[`;\nconst beep = '\\u0007';\nconst cursor = {\n to(x, y) {\n if (!y)\n return `${CSI}${x + 1}G`;\n return `${CSI}${y + 1};${x + 1}H`;\n },\n move(x, y) {\n let ret = '';\n if (x < 0)\n ret += `${CSI}${-x}D`;\n else if (x > 0)\n ret += `${CSI}${x}C`;\n if (y < 0)\n ret += `${CSI}${-y}A`;\n else if (y > 0)\n ret += `${CSI}${y}B`;\n return ret;\n },\n up: (count = 1) => `${CSI}${count}A`,\n down: (count = 1) => `${CSI}${count}B`,\n forward: (count = 1) => `${CSI}${count}C`,\n backward: (count = 1) => `${CSI}${count}D`,\n nextLine: (count = 1) => `${CSI}E`.repeat(count),\n prevLine: (count = 1) => `${CSI}F`.repeat(count),\n left: `${CSI}G`,\n hide: `${CSI}?25l`,\n show: `${CSI}?25h`,\n save: `${ESC}7`,\n restore: `${ESC}8`\n};\nconst scroll = {\n up: (count = 1) => `${CSI}S`.repeat(count),\n down: (count = 1) => `${CSI}T`.repeat(count)\n};\nconst erase = {\n screen: `${CSI}2J`,\n up: (count = 1) => `${CSI}1J`.repeat(count),\n down: (count = 1) => `${CSI}J`.repeat(count),\n line: `${CSI}2K`,\n lineEnd: `${CSI}K`,\n lineStart: `${CSI}1K`,\n lines(count) {\n let clear = '';\n for (let i = 0; i < count; i++)\n clear += this.line + (i < count - 1 ? cursor.up() : '');\n if (count)\n clear += cursor.left;\n return clear;\n }\n};\nconst clear = {\n screen: `${ESC}c`\n};\nexport { cursor, scroll, erase, beep, clear };\n","import { styleText } from 'node:util';\nimport { stdout, stdin } from 'node:process';\nimport * as f$1 from 'node:readline';\nimport f__default from 'node:readline';\nimport { wrapAnsi } from 'fast-wrap-ansi';\nimport { cursor, erase } from 'sisteransi';\nimport { ReadStream } from 'node:tty';\nimport x from 'fast-string-width';\n\nfunction findCursor(o, s, l) {\n if (!l.some((r) => !r.disabled))\n return o;\n const t = o + s, n = Math.max(l.length - 1, 0), e = t < 0 ? n : t > n ? 0 : t;\n return l[e]?.disabled ? findCursor(e, s < 0 ? -1 : 1, l) : e;\n}\nfunction findTextCursor(o, s, l, i) {\n const t = i.split(`\n`);\n let n = 0, e = o;\n for (const r of t) {\n if (e <= r.length)\n break;\n e -= r.length + 1, n++;\n }\n for (n = Math.max(0, Math.min(t.length - 1, n + l)), e = Math.min(e, t[n].length) + s; e < 0 && n > 0; )\n n--, e += t[n].length + 1;\n for (; e > t[n].length && n < t.length - 1; )\n e -= t[n].length + 1, n++;\n e = Math.max(0, Math.min(t[n].length, e));\n let h = 0;\n for (let r = 0; r < n; r++)\n h += t[r].length + 1;\n return h + e;\n}\n\nconst a$1 = [\"up\", \"down\", \"left\", \"right\", \"space\", \"enter\", \"cancel\"], t = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n];\nconst settings = {\n actions: new Set(a$1),\n aliases: /* @__PURE__ */ new Map([\n // vim support\n [\"k\", \"up\"],\n [\"j\", \"down\"],\n [\"h\", \"left\"],\n [\"l\", \"right\"],\n [\"\u0003\", \"cancel\"],\n // opinionated defaults!\n [\"escape\", \"cancel\"]\n ]),\n messages: {\n cancel: \"Canceled\",\n error: \"Something went wrong\"\n },\n withGuide: true,\n accessible: void 0,\n date: {\n monthNames: [...t],\n messages: {\n required: \"Please enter a valid date\",\n invalidMonth: \"There are only 12 months in a year\",\n invalidDay: (n, e) => `There are only ${n} days in ${e}`,\n afterMin: (n) => `Date must be on or after ${n.toISOString().slice(0, 10)}`,\n beforeMax: (n) => `Date must be on or before ${n.toISOString().slice(0, 10)}`\n }\n }\n};\nfunction updateSettings(n) {\n if (n.aliases !== void 0) {\n const e = n.aliases;\n for (const s in e) {\n if (!Object.hasOwn(e, s)) continue;\n const i = e[s];\n i === void 0 || !settings.actions.has(i) || settings.aliases.has(s) || settings.aliases.set(s, i);\n }\n }\n if (n.messages !== void 0) {\n const e = n.messages;\n e.cancel !== void 0 && (settings.messages.cancel = e.cancel), e.error !== void 0 && (settings.messages.error = e.error);\n }\n if (n.withGuide !== void 0 && (settings.withGuide = n.withGuide !== false), n.accessible !== void 0 && (settings.accessible = n.accessible === true), n.date !== void 0) {\n const e = n.date;\n e.monthNames !== void 0 && (settings.date.monthNames = [...e.monthNames]), e.messages !== void 0 && (e.messages.required !== void 0 && (settings.date.messages.required = e.messages.required), e.messages.invalidMonth !== void 0 && (settings.date.messages.invalidMonth = e.messages.invalidMonth), e.messages.invalidDay !== void 0 && (settings.date.messages.invalidDay = e.messages.invalidDay), e.messages.afterMin !== void 0 && (settings.date.messages.afterMin = e.messages.afterMin), e.messages.beforeMax !== void 0 && (settings.date.messages.beforeMax = e.messages.beforeMax));\n }\n}\nfunction isAccessible(n) {\n if (n !== void 0) return n;\n if (settings.accessible !== void 0) return settings.accessible;\n const e = process.env.ACCESSIBLE;\n return e !== void 0 && e !== \"\" && e !== \"0\" && e !== \"false\";\n}\nfunction isActionKey(n, e) {\n if (typeof n == \"string\")\n return settings.aliases.get(n) === e;\n for (const s of n)\n if (s !== void 0 && isActionKey(s, e))\n return true;\n return false;\n}\n\nfunction diffLines(i, s) {\n if (i === s) return;\n const e = i.split(`\n`), t = s.split(`\n`), r = Math.max(e.length, t.length), f = [];\n for (let n = 0; n < r; n++)\n e[n] !== t[n] && f.push(n);\n return {\n lines: f,\n numLinesBefore: e.length,\n numLinesAfter: t.length,\n numLines: r\n };\n}\n\nconst R = globalThis.process.platform.startsWith(\"win\");\nconst CANCEL_SYMBOL = Symbol(\"clack:cancel\");\nfunction isCancel(e) {\n return e === CANCEL_SYMBOL;\n}\nfunction setRawMode(e, r) {\n const o = e;\n o.isTTY && o.setRawMode(r);\n}\nfunction block({\n input: e = stdin,\n output: r = stdout,\n overwrite: o = true,\n hideCursor: n = true\n} = {}) {\n const s = f$1.createInterface({\n input: e,\n output: r,\n prompt: \"\",\n tabSize: 1\n });\n f$1.emitKeypressEvents(e, s), e instanceof ReadStream && e.isTTY && e.setRawMode(true);\n const t = (l, { name: i, sequence: p }) => {\n const w = String(l);\n if (isActionKey([w, i, p], \"cancel\")) {\n n && r.write(cursor.show), process.exit(0);\n return;\n }\n if (!o) return;\n const c = i === \"return\" ? 0 : -1, a = i === \"return\" ? -1 : 0;\n f$1.moveCursor(r, c, a, () => {\n f$1.clearLine(r, 1, () => {\n e.once(\"keypress\", t);\n });\n });\n };\n return n && r.write(cursor.hide), e.once(\"keypress\", t), () => {\n e.off(\"keypress\", t), n && r.write(cursor.show), e instanceof ReadStream && e.isTTY && !R && e.setRawMode(false), s.terminal = false, s.close();\n };\n}\nconst getColumns = (e) => \"columns\" in e && typeof e.columns == \"number\" ? e.columns : 80, getRows = (e) => \"rows\" in e && typeof e.rows == \"number\" ? e.rows : 20;\nfunction wrapTextWithPrefix(e, r, o, n = o, s = o, t) {\n const l = getColumns(e ?? stdout), i = x(o);\n return wrapAnsi(r, l - i, {\n hard: true,\n trim: false\n }).split(`\n`).map((c, a, g) => {\n const m = t ? t(c, a) : c;\n return a === 0 ? `${n}${m}` : a === g.length - 1 ? `${s}${m}` : `${o}${m}`;\n }).join(`\n`);\n}\n\nfunction runValidation(e, a) {\n if (\"~standard\" in e) {\n const n = e[\"~standard\"].validate(a);\n return n instanceof Promise ? n.then((r) => r.issues?.at(0)?.message) : n.issues?.at(0)?.message;\n }\n return e(a);\n}\n\nlet C$1 = class C {\n input;\n output;\n _abortSignal;\n rl;\n opts;\n _render;\n _track = false;\n _prevFrame = \"\";\n _subscribers = /* @__PURE__ */ new Map();\n _cursor = 0;\n state = \"initial\";\n error = \"\";\n value;\n userInput = \"\";\n /**\n * Whether accessible (static, screen-reader friendly) output is enabled for\n * this prompt, resolved from the `accessible` option, the global setting,\n * and the `ACCESSIBLE` env var.\n */\n get accessible() {\n return isAccessible(this.opts.accessible);\n }\n constructor(t, e = true) {\n const { input: i = stdin, output: s = stdout, render: r, signal: n, ...o } = t;\n this.opts = o, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = r.bind(this), this._track = e, this._abortSignal = n, this.input = i, this.output = s;\n }\n /**\n * Unsubscribe all listeners\n */\n unsubscribe() {\n this._subscribers.clear();\n }\n /**\n * Set a subscriber with opts\n * @param event - The event name\n */\n setSubscriber(t, e) {\n const i = this._subscribers.get(t) ?? [];\n i.push(e), this._subscribers.set(t, i);\n }\n /**\n * Subscribe to an event\n * @param event - The event name\n * @param cb - The callback\n */\n on(t, e) {\n this.setSubscriber(t, { cb: e });\n }\n /**\n * Subscribe to an event once\n * @param event - The event name\n * @param cb - The callback\n */\n once(t, e) {\n this.setSubscriber(t, { cb: e, once: true });\n }\n /**\n * Emit an event with data\n * @param event - The event name\n * @param data - The data to pass to the callback\n */\n emit(t, ...e) {\n const i = this._subscribers.get(t) ?? [], s = [];\n for (const r of i)\n r.cb(...e), r.once && s.push(() => i.splice(i.indexOf(r), 1));\n for (const r of s)\n r();\n }\n prompt() {\n return new Promise((t) => {\n if (this._abortSignal) {\n if (this._abortSignal.aborted)\n return this.state = \"cancel\", this.close(), t(CANCEL_SYMBOL);\n this._abortSignal.addEventListener(\n \"abort\",\n () => {\n this.state = \"cancel\", this.close();\n },\n { once: true }\n );\n }\n this.rl = f__default.createInterface({\n input: this.input,\n tabSize: 2,\n prompt: \"\",\n escapeCodeTimeout: 50,\n terminal: true\n }), this.rl.prompt(), this.opts.initialUserInput !== void 0 && this._setUserInput(this.opts.initialUserInput, true), this.input.on(\"keypress\", this.onKeypress), setRawMode(this.input, true), this.output.on(\"resize\", this.render), this.render(), this.once(\"submit\", () => {\n this.output.write(cursor.show), this.output.off(\"resize\", this.render), setRawMode(this.input, false), t(this.value);\n }), this.once(\"cancel\", () => {\n this.output.write(cursor.show), this.output.off(\"resize\", this.render), setRawMode(this.input, false), t(CANCEL_SYMBOL);\n });\n });\n }\n _isActionKey(t, e) {\n return t === \"\t\";\n }\n _shouldSubmit(t, e) {\n return true;\n }\n _setValue(t) {\n this.value = t, this.emit(\"value\", this.value);\n }\n _setUserInput(t, e) {\n this.userInput = t ?? \"\", this.emit(\"userInput\", this.userInput), e && this._track && this.rl && (this.rl.write(this.userInput), this._cursor = this.rl.cursor);\n }\n _clearUserInput() {\n this.rl?.write(null, { ctrl: true, name: \"u\" }), this._setUserInput(\"\");\n }\n async onKeypress(t, e) {\n if (this.state !== \"validating\") {\n if (this._track && e.name !== \"return\" && (e.name && this._isActionKey(t, e) && this.rl?.write(null, { ctrl: true, name: \"h\" }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === \"error\" && (this.state = \"active\"), e?.name && (!this._track && settings.aliases.has(e.name) && this.emit(\"cursor\", settings.aliases.get(e.name)), settings.actions.has(e.name) && this.emit(\"cursor\", e.name)), t && (t.toLowerCase() === \"y\" || t.toLowerCase() === \"n\") && this.emit(\"confirm\", t.toLowerCase() === \"y\"), this.emit(\"key\", t, e), e?.name === \"return\" && this._shouldSubmit(t, e)) {\n if (this.opts.validate) {\n const i = runValidation(this.opts.validate, this.value);\n let s;\n i instanceof Promise ? (this.state = \"validating\", this.render(), s = await i) : s = i, s && (this.error = s instanceof Error ? s.message : s, this.state = \"error\", this.rl?.write(this.userInput));\n }\n this.state !== \"error\" && (this.state = \"submit\");\n }\n isActionKey([t, e?.name, e?.sequence], \"cancel\") && (this.state = \"cancel\"), (this.state === \"submit\" || this.state === \"cancel\") && this.emit(\"finalize\"), this.render(), (this.state === \"submit\" || this.state === \"cancel\") && this.close();\n }\n }\n close() {\n this.input.unpipe(), this.input.removeListener(\"keypress\", this.onKeypress), this.output.write(`\n`), setRawMode(this.input, false), this.rl?.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();\n }\n restoreCursor() {\n const t = wrapAnsi(this._prevFrame, getColumns(this.output), { hard: true, trim: false }).split(`\n`).length - 1;\n this.output.write(cursor.move(-999, t * -1));\n }\n render() {\n const t = wrapAnsi(this._render(this) ?? \"\", getColumns(this.output), {\n hard: true,\n trim: false\n });\n if (t !== this._prevFrame) {\n if (this.state === \"initial\")\n this.output.write(cursor.hide);\n else {\n const e = diffLines(this._prevFrame, t), i = getRows(this.output);\n if (this.restoreCursor(), e) {\n const s = Math.max(0, e.numLinesAfter - i), r = Math.max(0, e.numLinesBefore - i);\n let n = e.lines.find((o) => o >= s);\n if (n === void 0) {\n this._prevFrame = t;\n return;\n }\n if (e.lines.length === 1) {\n this.output.write(cursor.move(0, n - r)), this.output.write(erase.lines(1));\n const o = t.split(`\n`);\n this.output.write(o[n]), this._prevFrame = t, this.output.write(cursor.move(0, o.length - n - 1));\n return;\n } else if (e.lines.length > 1) {\n if (s < r)\n n = s;\n else {\n const h = n - r;\n h > 0 && this.output.write(cursor.move(0, h));\n }\n this.output.write(erase.down());\n const m = t.split(`\n`).slice(n);\n this.output.write(m.join(`\n`)), this._prevFrame = t;\n return;\n }\n }\n this.output.write(erase.down());\n }\n this.output.write(t), this.state === \"initial\" && (this.state = \"active\"), this._prevFrame = t;\n }\n }\n};\n\nfunction p$1(l, e) {\n if (l === void 0 || e.length === 0)\n return 0;\n const i = e.findIndex((s) => s.value === l);\n return i !== -1 ? i : 0;\n}\nfunction m(l, e) {\n return (e.label ?? String(e.value)).toLowerCase().includes(l.toLowerCase());\n}\nfunction g(l, e) {\n if (e)\n return l ? e : e[0];\n}\nlet T$1 = class T extends C$1 {\n filteredOptions;\n multiple;\n isNavigating = false;\n selectedValues = [];\n focusedValue;\n #e = 0;\n #s = \"\";\n #t;\n #i;\n #n;\n #l;\n get cursor() {\n return this.#e;\n }\n get userInputWithCursor() {\n if (!this.userInput)\n return styleText([\"inverse\", \"hidden\"], \"_\");\n if (this._cursor >= this.userInput.length)\n return `${this.userInput}\\u2588`;\n const e = this.userInput.slice(0, this.cursor), t = this.userInput.slice(this.cursor, this.cursor + 1), i = this.userInput.slice(this.cursor + 1);\n return `${e}${styleText(\"inverse\", t)}${i}`;\n }\n get options() {\n return typeof this.#i == \"function\" ? this.#i() : this.#i;\n }\n constructor(e) {\n super(e), this.#i = e.options, this.#n = e.placeholder, this.#l = e.completeOnTab === true;\n const t = this.options;\n this.filteredOptions = [...t], this.multiple = e.multiple === true, this.#t = typeof e.options == \"function\" ? e.filter : e.filter ?? m;\n let i;\n if (e.initialValue && Array.isArray(e.initialValue) ? this.multiple ? i = e.initialValue : i = e.initialValue.slice(0, 1) : !this.multiple && this.options.length > 0 && (i = [this.options[0]?.value]), i)\n for (const s of i) {\n const n = t.findIndex((r) => r.value === s);\n n !== -1 && (this.toggleSelected(s), this.#e = n);\n }\n this.focusedValue = this.options[this.#e]?.value, this.on(\"key\", (s, n) => this.#u(s, n)), this.on(\"userInput\", (s) => this.#o(s));\n }\n _isActionKey(e, t) {\n return e === \"\t\" || this.multiple && this.isNavigating && t.name === \"space\" && e !== void 0 && e !== \"\";\n }\n #u(e, t) {\n const i = t.name === \"up\", s = t.name === \"down\", n = t.name === \"return\", r = this.userInput === \"\" || this.userInput === \"\t\", u = this.#n, d = this.options, c = u !== void 0 && u !== \"\" && d.some(\n (o) => !o.disabled && (this.#t ? this.#t(u, o) : true)\n );\n if (t.name === \"tab\" && r && c) {\n this.userInput === \"\t\" && this._clearUserInput(), this._setUserInput(u, true), this.isNavigating = false;\n return;\n }\n if (t.name === \"tab\" && this.#l && !this.multiple && this.focusedValue !== void 0) {\n const o = String(this.focusedValue);\n this._clearUserInput(), this._setUserInput(o, true), this.isNavigating = false;\n return;\n }\n i || s ? (this.#e = findCursor(this.#e, i ? -1 : 1, this.filteredOptions), this.focusedValue = this.filteredOptions[this.#e]?.value, this.multiple || (this.selectedValues = [this.focusedValue]), this.isNavigating = true) : n ? this.value = g(this.multiple, this.selectedValues) : this.multiple ? this.focusedValue !== void 0 && (t.name === \"tab\" || this.isNavigating && t.name === \"space\") ? this.toggleSelected(this.focusedValue) : this.isNavigating = false : (this.focusedValue && (this.selectedValues = [this.focusedValue]), this.isNavigating = false);\n }\n deselectAll() {\n this.selectedValues = [];\n }\n toggleSelected(e) {\n this.filteredOptions.length !== 0 && (this.multiple ? this.selectedValues.includes(e) ? this.selectedValues = this.selectedValues.filter((t) => t !== e) : this.selectedValues = [...this.selectedValues, e] : this.selectedValues = [e]);\n }\n #o(e) {\n if (e !== this.#s) {\n this.#s = e;\n const t = this.options;\n e && this.#t ? this.filteredOptions = t.filter((n) => this.#t?.(e, n)) : this.filteredOptions = [...t];\n const i = p$1(this.focusedValue, this.filteredOptions);\n this.#e = findCursor(i, 0, this.filteredOptions);\n const s = this.filteredOptions[this.#e];\n s && !s.disabled ? this.focusedValue = s.value : this.focusedValue = void 0, this.multiple || (this.focusedValue !== void 0 ? this.toggleSelected(this.focusedValue) : this.deselectAll());\n }\n }\n};\n\nclass r extends C$1 {\n get cursor() {\n return this.value ? 0 : 1;\n }\n get _value() {\n return this.cursor === 0;\n }\n constructor(t) {\n super(t, false), this.value = !!t.initialValue, this.on(\"userInput\", () => {\n this.value = this._value;\n }), this.on(\"confirm\", (i) => {\n this.output.write(cursor.move(0, -1)), this.value = i, this.state = \"submit\", this.close();\n }), this.on(\"cursor\", () => {\n this.value = !this.value;\n });\n }\n}\n\nconst _ = {\n Y: { type: \"year\", len: 4 },\n M: { type: \"month\", len: 2 },\n D: { type: \"day\", len: 2 }\n};\nfunction M(r) {\n return [...r].map((t) => _[t]);\n}\nfunction P(r) {\n const i = new Intl.DateTimeFormat(r, {\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\"\n }).formatToParts(new Date(2e3, 0, 15)), s = [];\n let n = \"/\";\n for (const e of i)\n e.type === \"literal\" ? n = e.value.trim() || e.value : (e.type === \"year\" || e.type === \"month\" || e.type === \"day\") && s.push({ type: e.type, len: e.type === \"year\" ? 4 : 2 });\n return { segments: s, separator: n };\n}\nfunction p(r) {\n return Number.parseInt((r || \"0\").replace(/_/g, \"0\"), 10) || 0;\n}\nfunction f(r) {\n return {\n year: p(r.year),\n month: p(r.month),\n day: p(r.day)\n };\n}\nfunction c$1(r, t) {\n return new Date(r || 2001, t || 1, 0).getDate();\n}\nfunction b(r) {\n const { year: t, month: i, day: s } = f(r);\n if (!t || t < 0 || t > 9999 || !i || i < 1 || i > 12 || !s || s < 1) return;\n const n = new Date(Date.UTC(t, i - 1, s));\n if (!(n.getUTCFullYear() !== t || n.getUTCMonth() !== i - 1 || n.getUTCDate() !== s))\n return { year: t, month: i, day: s };\n}\nfunction C(r) {\n const t = b(r);\n return t ? new Date(Date.UTC(t.year, t.month - 1, t.day)) : void 0;\n}\nfunction T(r, t, i, s) {\n const n = i ? {\n year: i.getUTCFullYear(),\n month: i.getUTCMonth() + 1,\n day: i.getUTCDate()\n } : null, e = s ? {\n year: s.getUTCFullYear(),\n month: s.getUTCMonth() + 1,\n day: s.getUTCDate()\n } : null;\n return r === \"year\" ? { min: n?.year ?? 1, max: e?.year ?? 9999 } : r === \"month\" ? {\n min: n && t.year === n.year ? n.month : 1,\n max: e && t.year === e.year ? e.month : 12\n } : {\n min: n && t.year === n.year && t.month === n.month ? n.day : 1,\n max: e && t.year === e.year && t.month === e.month ? e.day : c$1(t.year, t.month)\n };\n}\nclass U extends C$1 {\n #i;\n #o;\n #t;\n #h;\n #u;\n #e = { segmentIndex: 0, positionInSegment: 0 };\n #n = true;\n #s = null;\n inlineError = \"\";\n get segmentCursor() {\n return { ...this.#e };\n }\n get segmentValues() {\n return { ...this.#t };\n }\n get segments() {\n return this.#i;\n }\n get separator() {\n return this.#o;\n }\n get formattedValue() {\n return this.#l(this.#t);\n }\n #l(t) {\n return this.#i.map((i) => t[i.type]).join(this.#o);\n }\n #r() {\n this._setUserInput(this.#l(this.#t)), this._setValue(C(this.#t) ?? void 0);\n }\n constructor(t) {\n const i = t.format ? { segments: M(t.format), separator: t.separator ?? \"/\" } : P(t.locale), s = t.separator ?? i.separator, n = t.format ? M(t.format) : i.segments, e = t.initialValue ?? t.defaultValue, m = e ? {\n year: String(e.getUTCFullYear()).padStart(4, \"0\"),\n month: String(e.getUTCMonth() + 1).padStart(2, \"0\"),\n day: String(e.getUTCDate()).padStart(2, \"0\")\n } : { year: \"____\", month: \"__\", day: \"__\" }, o = n.map((a) => m[a.type]).join(s);\n super({ ...t, initialUserInput: o }, false), this.#i = n, this.#o = s, this.#t = m, this.#h = t.minDate, this.#u = t.maxDate, this.#r(), this.on(\"cursor\", (a) => this.#f(a)), this.on(\"key\", (a, u) => this.#y(a, u)), this.on(\"finalize\", () => this.#p(t));\n }\n #a() {\n const t = Math.max(0, Math.min(this.#e.segmentIndex, this.#i.length - 1)), i = this.#i[t];\n if (i)\n return this.#e.positionInSegment = Math.max(\n 0,\n Math.min(this.#e.positionInSegment, i.len - 1)\n ), { segment: i, index: t };\n }\n #m(t) {\n this.inlineError = \"\", this.#s = null;\n const i = this.#a();\n i && (this.#e.segmentIndex = Math.max(\n 0,\n Math.min(this.#i.length - 1, i.index + t)\n ), this.#e.positionInSegment = 0, this.#n = true);\n }\n #d(t) {\n const i = this.#a();\n if (!i) return;\n const { segment: s } = i, n = this.#t[s.type], e = !n || n.replace(/_/g, \"\") === \"\", m = Number.parseInt((n || \"0\").replace(/_/g, \"0\"), 10) || 0, o = T(\n s.type,\n f(this.#t),\n this.#h,\n this.#u\n );\n let a;\n e ? a = t === 1 ? o.min : o.max : a = Math.max(Math.min(o.max, m + t), o.min), this.#t = {\n ...this.#t,\n [s.type]: a.toString().padStart(s.len, \"0\")\n }, this.#n = true, this.#s = null, this.#r();\n }\n #f(t) {\n if (t)\n switch (t) {\n case \"right\":\n return this.#m(1);\n case \"left\":\n return this.#m(-1);\n case \"up\":\n return this.#d(1);\n case \"down\":\n return this.#d(-1);\n }\n }\n #y(t, i) {\n if (i?.name === \"backspace\" || i?.sequence === \"\\x7F\" || i?.sequence === \"\\b\" || t === \"\\x7F\" || t === \"\\b\") {\n this.inlineError = \"\";\n const n = this.#a();\n if (!n) return;\n if (!this.#t[n.segment.type].replace(/_/g, \"\")) {\n this.#m(-1);\n return;\n }\n this.#t[n.segment.type] = \"_\".repeat(n.segment.len), this.#n = true, this.#e.positionInSegment = 0, this.#r();\n return;\n }\n if (i?.name === \"tab\") {\n this.inlineError = \"\";\n const n = this.#a();\n if (!n) return;\n const e = i.shift ? -1 : 1, m = n.index + e;\n m >= 0 && m < this.#i.length && (this.#e.segmentIndex = m, this.#e.positionInSegment = 0, this.#n = true);\n return;\n }\n if (t && /^[0-9]$/.test(t)) {\n const n = this.#a();\n if (!n) return;\n const { segment: e } = n, m = !this.#t[e.type].replace(/_/g, \"\");\n if (this.#n && this.#s !== null && !m) {\n const h = this.#s + t, d = { ...this.#t, [e.type]: h }, g = this.#g(d, e);\n if (g) {\n this.inlineError = g, this.#s = null, this.#n = false;\n return;\n }\n this.inlineError = \"\", this.#t[e.type] = h, this.#s = null, this.#n = false, this.#r(), n.index < this.#i.length - 1 && (this.#e.segmentIndex = n.index + 1, this.#e.positionInSegment = 0, this.#n = true);\n return;\n }\n this.#n && !m && (this.#t[e.type] = \"_\".repeat(e.len), this.#e.positionInSegment = 0), this.#n = false, this.#s = null;\n const o = this.#t[e.type], a = o.indexOf(\"_\"), u = a >= 0 ? a : Math.min(this.#e.positionInSegment, e.len - 1);\n if (u < 0 || u >= e.len) return;\n let l = o.slice(0, u) + t + o.slice(u + 1), D = false;\n if (u === 0 && o === \"__\" && (e.type === \"month\" || e.type === \"day\")) {\n const h = Number.parseInt(t, 10);\n l = `0${t}`, D = h <= (e.type === \"month\" ? 1 : 2);\n }\n if (e.type === \"year\" && (l = (o.replace(/_/g, \"\") + t).padStart(e.len, \"_\")), !l.includes(\"_\")) {\n const h = { ...this.#t, [e.type]: l }, d = this.#g(h, e);\n if (d) {\n this.inlineError = d;\n return;\n }\n }\n this.inlineError = \"\", this.#t[e.type] = l;\n const y = l.includes(\"_\") ? void 0 : b(this.#t);\n if (y) {\n const { year: h, month: d } = y, g = c$1(h, d);\n this.#t = {\n year: String(Math.max(0, Math.min(9999, h))).padStart(4, \"0\"),\n month: String(Math.max(1, Math.min(12, d))).padStart(2, \"0\"),\n day: String(Math.max(1, Math.min(g, y.day))).padStart(2, \"0\")\n };\n }\n this.#r();\n const S = l.indexOf(\"_\");\n D ? (this.#n = true, this.#s = t) : S >= 0 ? this.#e.positionInSegment = S : a >= 0 && n.index < this.#i.length - 1 ? (this.#e.segmentIndex = n.index + 1, this.#e.positionInSegment = 0, this.#n = true) : this.#e.positionInSegment = Math.min(u + 1, e.len - 1);\n }\n }\n #g(t, i) {\n const { month: s, day: n } = f(t);\n if (i.type === \"month\" && (s < 0 || s > 12))\n return settings.date.messages.invalidMonth;\n if (i.type === \"day\" && (n < 0 || n > 31))\n return settings.date.messages.invalidDay(31, \"any month\");\n }\n #p(t) {\n const { year: i, month: s, day: n } = f(this.#t);\n if (i && s && n) {\n const e = c$1(i, s);\n this.#t = {\n ...this.#t,\n day: String(Math.min(n, e)).padStart(2, \"0\")\n };\n }\n this.value = C(this.#t) ?? t.defaultValue ?? void 0;\n }\n}\n\nlet u$1 = class u extends C$1 {\n options;\n cursor = 0;\n #e;\n getGroupItems(t) {\n return this.options.filter((i) => i.group === t);\n }\n isGroupSelected(t) {\n const i = this.getGroupItems(t), e = this.value;\n return e === void 0 ? false : i.every((s) => e.includes(s.value));\n }\n toggleValue() {\n const t = this.options[this.cursor];\n if (t !== void 0)\n if (this.value === void 0 && (this.value = []), t.group === true) {\n const i = t.value, e = this.getGroupItems(i);\n this.isGroupSelected(i) ? this.value = this.value.filter(\n (s) => e.findIndex((r) => r.value === s) === -1\n ) : this.value = [...this.value, ...e.map((s) => s.value)], this.value = Array.from(new Set(this.value));\n } else {\n const i = this.value.includes(t.value);\n this.value = i ? this.value.filter((e) => e !== t.value) : [...this.value, t.value];\n }\n }\n constructor(t) {\n super(t, false);\n const { options: i } = t;\n this.#e = t.selectableGroups !== false, this.options = Object.entries(i).flatMap(([e, s]) => [\n { value: e, group: true, label: e },\n ...s.map((r) => ({ ...r, group: e }))\n ]), this.value = [...t.initialValues ?? []], this.cursor = Math.max(\n this.options.findIndex(({ value: e }) => e === t.cursorAt),\n this.#e ? 0 : 1\n ), this.on(\"key\", (e, s) => {\n s.name === void 0 && e === \"\\u3000\" && this.toggleValue();\n }), this.on(\"cursor\", (e) => {\n switch (e) {\n case \"left\":\n case \"up\": {\n this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n const s = this.options[this.cursor]?.group === true;\n !this.#e && s && (this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1);\n break;\n }\n case \"down\":\n case \"right\": {\n this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n const s = this.options[this.cursor]?.group === true;\n !this.#e && s && (this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1);\n break;\n }\n case \"space\":\n this.toggleValue();\n break;\n }\n });\n }\n};\n\nconst o = /* @__PURE__ */ new Set([\"up\", \"down\", \"left\", \"right\"]);\nclass h extends C$1 {\n #t = false;\n #s;\n focused = \"editor\";\n get userInputWithCursor() {\n if (this.state === \"submit\")\n return this.userInput;\n const t = this.userInput;\n if (this.cursor >= t.length)\n return `${t}\\u2588`;\n const s = t.slice(0, this.cursor), r = t.slice(this.cursor, this.cursor + 1), i = t.slice(this.cursor + 1);\n return r === `\n` ? `${s}\\u2588\n${i}` : `${s}${styleText(\"inverse\", r)}${i}`;\n }\n get cursor() {\n return this._cursor;\n }\n #r(t) {\n if (this.userInput.length === 0) {\n this._setUserInput(t);\n return;\n }\n this._setUserInput(\n this.userInput.slice(0, this.cursor) + t + this.userInput.slice(this.cursor)\n );\n }\n #i(t) {\n const s = this.value ?? \"\";\n switch (t) {\n case \"up\":\n this._cursor = findTextCursor(this._cursor, 0, -1, s);\n return;\n case \"down\":\n this._cursor = findTextCursor(this._cursor, 0, 1, s);\n return;\n case \"left\":\n this._cursor = findTextCursor(this._cursor, -1, 0, s);\n return;\n case \"right\":\n this._cursor = findTextCursor(this._cursor, 1, 0, s);\n return;\n }\n }\n _shouldSubmit(t, s) {\n if (this.#s)\n return this.focused === \"submit\" ? true : (this.#r(`\n`), this._cursor++, false);\n const r = this.#t;\n return this.#t = true, r && this.cursor === this.userInput.length ? (this.userInput[this.cursor - 1] === `\n` && (this._setUserInput(\n this.userInput.slice(0, this.cursor - 1) + this.userInput.slice(this.cursor)\n ), this._cursor--), true) : (this.#r(`\n`), this._cursor++, false);\n }\n constructor(t) {\n const s = t.initialUserInput ?? t.initialValue;\n super(\n {\n ...t,\n initialUserInput: s\n },\n false\n ), s !== void 0 && (this._cursor = s.length), this.#s = t.showSubmit ?? false, this.on(\"key\", (r, i) => {\n if (i?.name && o.has(i.name)) {\n this.#t = false, this.#i(i.name);\n return;\n }\n if (r === \"\t\" && this.#s) {\n this.focused = this.focused === \"editor\" ? \"submit\" : \"editor\";\n return;\n }\n if (i?.name !== \"return\") {\n if (this.#t = false, i?.name === \"backspace\" && this.cursor > 0) {\n this._setUserInput(\n this.userInput.slice(0, this.cursor - 1) + this.userInput.slice(this.cursor)\n ), this._cursor--;\n return;\n }\n if (i?.name === \"delete\" && this.cursor < this.userInput.length) {\n this._setUserInput(\n this.userInput.slice(0, this.cursor) + this.userInput.slice(this.cursor + 1)\n );\n return;\n }\n r && (this.#s && this.focused === \"submit\" && (this.focused = \"editor\"), this.#r(r ?? \"\"), this._cursor++);\n }\n }), this.on(\"userInput\", (r) => {\n this._setValue(r);\n }), this.on(\"finalize\", () => {\n this.value || (this.value = t.defaultValue), this.value === void 0 && (this.value = \"\");\n });\n }\n}\n\nclass a extends C$1 {\n options;\n cursor = 0;\n get _value() {\n return this.options[this.cursor]?.value;\n }\n get _enabledOptions() {\n return this.options.filter((e) => e.disabled !== true);\n }\n toggleAll() {\n const e = this._enabledOptions, i = this.value !== void 0 && this.value.length === e.length;\n this.value = i ? [] : e.map((t) => t.value);\n }\n toggleInvert() {\n const e = this.value;\n if (!e)\n return;\n const i = this._enabledOptions.filter((t) => !e.includes(t.value));\n this.value = i.map((t) => t.value);\n }\n toggleValue() {\n this.value === void 0 && (this.value = []);\n const e = this.value.includes(this._value);\n this.value = e ? this.value.filter((i) => i !== this._value) : [...this.value, this._value];\n }\n constructor(e) {\n super(e, false), this.options = e.options, this.value = [...e.initialValues ?? []];\n const i = Math.max(\n this.options.findIndex(({ value: t }) => t === e.cursorAt),\n 0\n );\n this.cursor = this.options[i]?.disabled ? findCursor(i, 1, this.options) : i, this.on(\"key\", (t, s) => {\n s.name === \"a\" && this.toggleAll(), s.name === \"i\" && this.toggleInvert(), s.name === void 0 && t === \"\\u3000\" && this.toggleValue();\n }), this.on(\"cursor\", (t) => {\n switch (t) {\n case \"left\":\n case \"up\":\n this.cursor = findCursor(this.cursor, -1, this.options);\n break;\n case \"down\":\n case \"right\":\n this.cursor = findCursor(this.cursor, 1, this.options);\n break;\n case \"space\":\n this.toggleValue();\n break;\n }\n });\n }\n}\n\nclass u extends C$1 {\n _mask = \"\\u2022\";\n get cursor() {\n return this._cursor;\n }\n get masked() {\n return this.userInput.replaceAll(/./g, this._mask);\n }\n get userInputWithCursor() {\n if (this.state === \"submit\" || this.state === \"cancel\")\n return this.masked;\n const t = this.userInput;\n if (this.cursor >= t.length)\n return `${this.masked}${styleText([\"inverse\", \"hidden\"], \"_\")}`;\n const s = this.masked, r = s.slice(0, this.cursor), i = s.slice(this.cursor, this.cursor + 1), o = s.slice(this.cursor + 1);\n return `${r}${styleText(\"inverse\", i)}${o}`;\n }\n clear() {\n this._clearUserInput();\n }\n constructor({ mask: t, ...s }) {\n super(s), this._mask = t ?? \"\\u2022\", this.on(\"userInput\", (r) => {\n this._setValue(r);\n }), this.on(\"finalize\", () => {\n this.value === void 0 && (this.value = \"\");\n });\n }\n}\n\nlet n$1 = class n extends C$1 {\n options;\n cursor = 0;\n get _selectedValue() {\n return this.options[this.cursor];\n }\n changeValue() {\n const e = this._selectedValue;\n this.value = e === void 0 ? void 0 : e.value;\n }\n constructor(e) {\n super(e, false), this.options = e.options;\n const o = this.options.findIndex(({ value: s }) => s === e.initialValue), t = o === -1 ? 0 : o;\n this.cursor = this.options[t]?.disabled ? findCursor(t, 1, this.options) : t, this.changeValue(), this.on(\"cursor\", (s) => {\n switch (s) {\n case \"left\":\n case \"up\":\n this.cursor = findCursor(this.cursor, -1, this.options);\n break;\n case \"down\":\n case \"right\":\n this.cursor = findCursor(this.cursor, 1, this.options);\n break;\n }\n this.changeValue();\n });\n }\n};\n\nclass c extends C$1 {\n options;\n cursor = 0;\n constructor(t) {\n super(t, false), this.options = t.options;\n const s = t.caseSensitive === true, i = this.options.map(({ value: [e] }) => s ? e : e?.toLowerCase()), n = Math.max(i.indexOf(t.initialValue), 0);\n this.cursor = this.options[n]?.disabled ? 0 : n, this.on(\"key\", (e) => {\n if (!e)\n return;\n const o = s ? e : e.toLowerCase();\n if (!i.includes(o))\n return;\n const r = this.options.find(({ value: [a], disabled: u }) => u ? false : s ? a === o : a?.toLowerCase() === o);\n r && (this.value = r.value, this.state = \"submit\", this.emit(\"submit\"));\n });\n }\n}\n\nclass n extends C$1 {\n get userInputWithCursor() {\n if (this.state === \"submit\")\n return this.userInput;\n const t = this.userInput;\n if (this.cursor >= t.length)\n return `${this.userInput}\\u2588`;\n const r = t.slice(0, this.cursor), s = t.slice(this.cursor, this.cursor + 1), e = t.slice(this.cursor + 1);\n return `${r}${styleText(\"inverse\", s)}${e}`;\n }\n get cursor() {\n return this._cursor;\n }\n constructor(t) {\n super({\n ...t,\n initialUserInput: t.initialUserInput ?? t.initialValue\n }), this.on(\"userInput\", (r) => {\n this._setValue(r);\n }), this.on(\"finalize\", () => {\n this.value || (this.value = t.defaultValue), this.value === void 0 && (this.value = \"\");\n });\n }\n}\n\nexport { T$1 as AutocompletePrompt, CANCEL_SYMBOL, r as ConfirmPrompt, U as DatePrompt, u$1 as GroupMultiSelectPrompt, h as MultiLinePrompt, a as MultiSelectPrompt, u as PasswordPrompt, C$1 as Prompt, c as SelectKeyPrompt, n$1 as SelectPrompt, n as TextPrompt, block, getColumns, getRows, isAccessible, isCancel, runValidation, settings, updateSettings, wrapTextWithPrefix };\n","import { wrapTextWithPrefix, getColumns, getRows, AutocompletePrompt, settings, ConfirmPrompt, DatePrompt, runValidation, isCancel, MultiSelectPrompt, GroupMultiSelectPrompt, MultiLinePrompt, PasswordPrompt, isAccessible, block, SelectPrompt, SelectKeyPrompt, TextPrompt } from '@clack/core';\nexport { CANCEL_SYMBOL, isCancel, settings, updateSettings } from '@clack/core';\nimport { styleText, stripVTControlCharacters } from 'node:util';\nimport process$1 from 'node:process';\nimport { wrapAnsi } from 'fast-wrap-ansi';\nimport l from 'fast-string-width';\nimport { existsSync, lstatSync, readdirSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { cursor, erase } from 'sisteransi';\n\nfunction isUnicodeSupported() {\n\tif (process$1.platform !== 'win32') {\n\t\treturn process$1.env.TERM !== 'linux'; // Linux console (kernel)\n\t}\n\n\treturn Boolean(process$1.env.CI)\n\t\t|| Boolean(process$1.env.WT_SESSION) // Windows Terminal\n\t\t|| Boolean(process$1.env.TERMINUS_SUBLIME) // Terminus (<0.2.27)\n\t\t|| process$1.env.ConEmuTask === '{cmd::Cmder}' // ConEmu and cmder\n\t\t|| process$1.env.TERM_PROGRAM === 'Terminus-Sublime'\n\t\t|| process$1.env.TERM_PROGRAM === 'vscode'\n\t\t|| process$1.env.TERM === 'xterm-256color'\n\t\t|| process$1.env.TERM === 'alacritty'\n\t\t|| process$1.env.TERMINAL_EMULATOR === 'JetBrains-JediTerm';\n}\n\nconst unicode = isUnicodeSupported(), isCI = () => process.env.CI === \"true\", isTTY = (e) => e.isTTY === true, unicodeOr = (e, o) => unicode ? e : o, S_STEP_ACTIVE = unicodeOr(\"\\u25C6\", \"*\"), S_STEP_CANCEL = unicodeOr(\"\\u25A0\", \"x\"), S_STEP_ERROR = unicodeOr(\"\\u25B2\", \"x\"), S_STEP_SUBMIT = unicodeOr(\"\\u25C7\", \"o\"), S_BAR_START = unicodeOr(\"\\u250C\", \"T\"), S_BAR = unicodeOr(\"\\u2502\", \"|\"), S_BAR_END = unicodeOr(\"\\u2514\", \"\\u2014\"), S_BAR_START_RIGHT = unicodeOr(\"\\u2510\", \"T\"), S_BAR_END_RIGHT = unicodeOr(\"\\u2518\", \"\\u2014\"), S_RADIO_ACTIVE = unicodeOr(\"\\u25CF\", \">\"), S_RADIO_INACTIVE = unicodeOr(\"\\u25CB\", \" \"), S_CHECKBOX_ACTIVE = unicodeOr(\"\\u25FB\", \"[\\u2022]\"), S_CHECKBOX_SELECTED = unicodeOr(\"\\u25FC\", \"[+]\"), S_CHECKBOX_INACTIVE = unicodeOr(\"\\u25FB\", \"[ ]\"), S_PASSWORD_MASK = unicodeOr(\"\\u25AA\", \"\\u2022\"), S_BAR_H = unicodeOr(\"\\u2500\", \"-\"), S_CORNER_TOP_RIGHT = unicodeOr(\"\\u256E\", \"+\"), S_CONNECT_LEFT = unicodeOr(\"\\u251C\", \"+\"), S_CORNER_BOTTOM_RIGHT = unicodeOr(\"\\u256F\", \"+\"), S_CORNER_BOTTOM_LEFT = unicodeOr(\"\\u2570\", \"+\"), S_CORNER_TOP_LEFT = unicodeOr(\"\\u256D\", \"+\"), S_INFO = unicodeOr(\"\\u25CF\", \"\\u2022\"), S_SUCCESS = unicodeOr(\"\\u25C6\", \"*\"), S_WARN = unicodeOr(\"\\u25B2\", \"!\"), S_ERROR = unicodeOr(\"\\u25A0\", \"x\"), symbol = (e) => {\n switch (e) {\n case \"initial\":\n case \"active\":\n return styleText(\"cyan\", S_STEP_ACTIVE);\n case \"cancel\":\n return styleText(\"red\", S_STEP_CANCEL);\n case \"error\":\n return styleText(\"yellow\", S_STEP_ERROR);\n case \"submit\":\n return styleText(\"green\", S_STEP_SUBMIT);\n case \"validating\":\n return styleText(\"dim\", S_STEP_ACTIVE);\n }\n}, symbolBar = (e) => {\n switch (e) {\n case \"initial\":\n case \"active\":\n return styleText(\"cyan\", S_BAR);\n case \"cancel\":\n return styleText(\"red\", S_BAR);\n case \"error\":\n return styleText(\"yellow\", S_BAR);\n case \"submit\":\n return styleText(\"green\", S_BAR);\n }\n};\nfunction formatInstructionFooter(e, o, r) {\n const s = r ? `${styleText(\"cyan\", S_BAR)} ` : \"\", n = wrapTextWithPrefix(e, o.join(\" \\u2022 \"), s).split(`\n`);\n return r && n.push(styleText(\"cyan\", S_BAR_END)), n;\n}\n\nconst E$1 = (l, e, w, p, b, C = false) => {\n let r = e, O = 0;\n if (C)\n for (let i = p - 1; i >= w; i--) {\n const m = l[i];\n if (m && (r -= m.length), O++, r <= b) break;\n }\n else\n for (let i = w; i < p; i++) {\n const m = l[i];\n if (m && (r -= m.length), O++, r <= b) break;\n }\n return { lineCount: r, removals: O };\n};\nconst limitOptions = ({\n cursor: l,\n options: e,\n style: w,\n output: p = process.stdout,\n maxItems: b = Number.POSITIVE_INFINITY,\n columnPadding: C = 0,\n rowPadding: r = 4\n}) => {\n const i = getColumns(p) - C, m = getRows(p), M = styleText(\"dim\", \"...\"), v = Math.max(m - r, 0), a = Math.max(Math.min(b, v), 5);\n let f = 0;\n l >= a - 3 && (f = Math.max(\n Math.min(l - a + 3, e.length - a),\n 0\n ));\n let d = a < e.length && f > 0, c = a < e.length && f + a < e.length;\n const I = Math.min(\n f + a,\n e.length\n ), s = [];\n let g = 0;\n d && g++, c && g++;\n const T = f + (d ? 1 : 0), W = I - (c ? 1 : 0);\n for (let t = T; t < W; t++) {\n const n = e[t], o = n !== void 0 ? w(n, t === l) : \"\", h = wrapAnsi(o, i, {\n hard: true,\n trim: false\n }).split(`\n`);\n s.push(h), g += h.length;\n }\n if (g > v) {\n let t = 0, n = 0, o = g;\n const h = l - T;\n let u = v;\n const L = () => E$1(s, o, 0, h, u), y = () => E$1(\n s,\n o,\n h + 1,\n s.length,\n u,\n true\n );\n d ? ({ lineCount: o, removals: t } = L(), o > u && (c || (u -= 1), { lineCount: o, removals: n } = y())) : (c || (u -= 1), { lineCount: o, removals: n } = y(), o > u && (u -= 1, { lineCount: o, removals: t } = L())), t > 0 && (d = true, s.splice(0, t)), n > 0 && (c = true, s.splice(s.length - n, n));\n }\n const x = [];\n d && x.push(M);\n for (const t of s)\n for (const n of t)\n x.push(n);\n return c && x.push(M), x;\n};\n\nfunction E(t) {\n return t.label ?? String(t.value ?? \"\");\n}\nfunction P(t, c) {\n if (!t)\n return true;\n const n = (c.label ?? String(c.value ?? \"\")).toLowerCase(), i = (c.hint ?? \"\").toLowerCase(), r = String(c.value).toLowerCase(), o = t.toLowerCase();\n return n.includes(o) || i.includes(o) || r.includes(o);\n}\nfunction j(t, c) {\n const n = [];\n for (const i of c)\n t.includes(i.value) && n.push(i);\n return n;\n}\nconst autocomplete = (t) => new AutocompletePrompt({\n options: t.options,\n initialValue: t.initialValue !== void 0 ? [t.initialValue] : void 0,\n initialUserInput: t.initialUserInput,\n placeholder: t.placeholder,\n completeOnTab: t.completeOnTab,\n filter: t.filter ?? ((n, i) => P(n, i)),\n signal: t.signal,\n input: t.input,\n output: t.output,\n validate: t.validate,\n render() {\n const n = t.withGuide ?? settings.withGuide, i = n ? [`${styleText(\"gray\", S_BAR)}`, `${symbol(this.state)} ${t.message}`] : [`${symbol(this.state)} ${t.message}`], r = this.userInput, o = this.options, m = t.placeholder, p = r === \"\" && m !== void 0, $ = (l, s) => {\n const a = E(l), u = l.hint && l.value === this.focusedValue ? styleText(\"dim\", ` (${l.hint})`) : \"\";\n switch (s) {\n case \"active\":\n return `${styleText(\"green\", S_RADIO_ACTIVE)} ${a}${u}`;\n case \"inactive\":\n return `${styleText(\"dim\", S_RADIO_INACTIVE)} ${styleText(\"dim\", a)}`;\n case \"disabled\":\n return `${styleText(\"gray\", S_RADIO_INACTIVE)} ${styleText([\"strikethrough\", \"gray\"], a)}`;\n }\n };\n switch (this.state) {\n case \"submit\": {\n const l = j(this.selectedValues, o), s = l.length > 0 ? ` ${styleText(\"dim\", l.map(E).join(\", \"))}` : \"\", a = n ? styleText(\"gray\", S_BAR) : \"\";\n return `${i.join(`\n`)}\n${a}${s}`;\n }\n case \"cancel\": {\n const l = r ? ` ${styleText([\"strikethrough\", \"dim\"], r)}` : \"\", s = n ? styleText(\"gray\", S_BAR) : \"\";\n return `${i.join(`\n`)}\n${s}${l}`;\n }\n default: {\n const l = this.state === \"error\" ? \"yellow\" : \"cyan\", s = n ? `${styleText(l, S_BAR)} ` : \"\", a = n ? styleText(l, S_BAR_END) : \"\";\n let u = \"\";\n if (this.isNavigating || p) {\n const d = p ? m : r;\n u = d !== \"\" ? ` ${styleText(\"dim\", d)}` : \"\";\n } else\n u = ` ${this.userInputWithCursor}`;\n const V = this.filteredOptions.length !== o.length ? styleText(\n \"dim\",\n ` (${this.filteredOptions.length} match${this.filteredOptions.length === 1 ? \"\" : \"es\"})`\n ) : \"\", b = this.filteredOptions.length === 0 && r ? [`${s}${styleText(\"yellow\", \"No matches found\")}`] : [], y = this.state === \"error\" ? [`${s}${styleText(\"yellow\", this.error)}`] : [];\n n && i.push(`${s.trimEnd()}`), i.push(\n `${s}${styleText(\"dim\", \"Search:\")}${u}${V}`,\n ...b,\n ...y\n );\n const S = [\n `${styleText(\"dim\", \"\\u2191/\\u2193\")} to select`,\n ...t.completeOnTab ? [`${styleText(\"dim\", \"Tab:\")} complete`] : [],\n `${styleText(\"dim\", \"Enter:\")} confirm`,\n `${styleText(\"dim\", \"Type:\")} to search`\n ], g = [`${s}${S.join(\" \\u2022 \")}`, a], O = this.filteredOptions.length === 0 ? [] : limitOptions({\n cursor: this.cursor,\n options: this.filteredOptions,\n columnPadding: n ? 3 : 0,\n // for `| ` when guide is shown\n rowPadding: i.length + g.length,\n style: (d, f) => $(\n d,\n d.disabled ? \"disabled\" : f ? \"active\" : \"inactive\"\n ),\n maxItems: t.maxItems,\n output: t.output\n });\n return [\n ...i,\n ...O.map((d) => `${s}${d}`),\n ...g\n ].join(`\n`);\n }\n }\n }\n}).prompt(), autocompleteMultiselect = (t) => {\n const c = (i, r, o, m) => {\n const p = o.includes(i.value), $ = i.label ?? String(i.value ?? \"\"), l = i.hint && m !== void 0 && i.value === m ? styleText(\"dim\", ` (${i.hint})`) : \"\", s = p ? styleText(\"green\", S_CHECKBOX_SELECTED) : styleText(\"dim\", S_CHECKBOX_INACTIVE);\n return i.disabled ? `${styleText(\"gray\", S_CHECKBOX_INACTIVE)} ${styleText([\"strikethrough\", \"gray\"], $)}` : r ? `${s} ${$}${l}` : `${s} ${styleText(\"dim\", $)}`;\n }, n = new AutocompletePrompt({\n options: t.options,\n multiple: true,\n placeholder: t.placeholder,\n filter: t.filter ?? ((i, r) => P(i, r)),\n validate: () => {\n if (t.required && n.selectedValues.length === 0)\n return \"Please select at least one item\";\n },\n initialValue: t.initialValues,\n signal: t.signal,\n input: t.input,\n output: t.output,\n render() {\n const i = t.withGuide ?? settings.withGuide, r = `${i ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)} ${t.message}\n`, o = this.userInput, m = t.placeholder, p = o === \"\" && m !== void 0, $ = this.isNavigating || p ? styleText(\"dim\", p ? m : o) : this.userInputWithCursor, l = this.options, s = this.filteredOptions.length !== l.length ? styleText(\n \"dim\",\n ` (${this.filteredOptions.length} match${this.filteredOptions.length === 1 ? \"\" : \"es\"})`\n ) : \"\";\n switch (this.state) {\n case \"submit\":\n return `${r}${i ? `${styleText(\"gray\", S_BAR)} ` : \"\"}${styleText(\n \"dim\",\n `${this.selectedValues.length} items selected`\n )}`;\n case \"cancel\":\n return `${r}${i ? `${styleText(\"gray\", S_BAR)} ` : \"\"}${styleText(\n [\"strikethrough\", \"dim\"],\n o\n )}`;\n default: {\n const a = this.state === \"error\" ? \"yellow\" : \"cyan\", u = i ? `${styleText(a, S_BAR)} ` : \"\", V = i ? styleText(a, S_BAR_END) : \"\", b = [\n `${styleText(\"dim\", \"\\u2191/\\u2193\")} to navigate`,\n `${styleText(\"dim\", this.isNavigating ? \"Space/Tab:\" : \"Tab:\")} select`,\n `${styleText(\"dim\", \"Enter:\")} confirm`,\n `${styleText(\"dim\", \"Type:\")} to search`\n ], y = this.filteredOptions.length === 0 && o ? [`${u}${styleText(\"yellow\", \"No matches found\")}`] : [], S = this.state === \"error\" ? [`${u}${styleText(\"yellow\", this.error)}`] : [], g = [\n ...`${r}${i ? styleText(a, S_BAR) : \"\"}`.split(`\n`),\n `${u}${styleText(\"dim\", \"Search:\")} ${$}${s}`,\n ...y,\n ...S\n ], O = [`${u}${b.join(\" \\u2022 \")}`, V], d = limitOptions({\n cursor: this.cursor,\n options: this.filteredOptions,\n style: (f, L) => c(f, L, this.selectedValues, this.focusedValue),\n maxItems: t.maxItems,\n output: t.output,\n rowPadding: g.length + O.length\n });\n return [\n ...g,\n ...d.map((f) => `${u}${f}`),\n ...O\n ].join(`\n`);\n }\n }\n }\n });\n return n.prompt();\n};\n\nconst K = [\n S_CORNER_TOP_LEFT,\n S_CORNER_TOP_RIGHT,\n S_CORNER_BOTTOM_LEFT,\n S_CORNER_BOTTOM_RIGHT\n], Q = [S_BAR_START, S_BAR_START_RIGHT, S_BAR_END, S_BAR_END_RIGHT];\nfunction A$1(n, e, t, o) {\n let i = t, f = t;\n return o === \"center\" ? i = Math.floor((e - n) / 2) : o === \"right\" && (i = e - n - t), f = e - i - n, [i, f];\n}\nconst U = (n) => n;\nconst box = (n = \"\", e = \"\", t) => {\n const o = t?.output ?? process.stdout, i = getColumns(o), R = 1 * 2, u = t?.titlePadding ?? 1, h = t?.contentPadding ?? 2, w = t?.width === void 0 || t.width === \"auto\" ? 1 : Math.min(1, t.width), m = t?.withGuide ?? settings.withGuide ? `${styleText(\"gray\", S_BAR)} ` : \"\", b = t?.formatBorder ?? U, a = (t?.rounded ? K : Q).map(b), _ = b(S_BAR_H), p = b(S_BAR), x = l(m), B = l(e), y = i - x;\n let r = Math.floor(i * w) - x;\n if (t?.width === \"auto\") {\n const c = n.split(`\n`);\n let s = B + u * 2;\n for (const G of c) {\n const P = l(G) + h * 2;\n P > s && (s = P);\n }\n const g = s + R;\n g < r && (r = g);\n }\n r % 2 !== 0 && (r < y ? r++ : r--);\n const d = r - R, T = d - u * 2, S = B > T ? `${e.slice(0, T - 3)}...` : e, [O, W] = A$1(\n l(S),\n d,\n u,\n t?.titleAlign\n ), L = wrapAnsi(n, d - h * 2, {\n hard: true,\n trim: false\n });\n o.write(\n `${m}${a[0]}${_.repeat(O)}${S}${_.repeat(W)}${a[1]}\n`\n );\n const E = L.split(`\n`);\n for (const c of E) {\n const [s, g] = A$1(\n l(c),\n d,\n h,\n t?.contentAlign\n );\n o.write(\n `${m}${p}${\" \".repeat(s)}${c}${\" \".repeat(g)}${p}\n`\n );\n }\n o.write(`${m}${a[2]}${_.repeat(d)}${a[3]}\n`);\n};\n\nconst confirm = (e) => {\n const a = e.active ?? \"Yes\", o = e.inactive ?? \"No\";\n return new ConfirmPrompt({\n active: a,\n inactive: o,\n signal: e.signal,\n input: e.input,\n output: e.output,\n initialValue: e.initialValue ?? true,\n render() {\n const i = e.withGuide ?? settings.withGuide, u = `${symbol(this.state)} `, l = i ? `${styleText(\"gray\", S_BAR)} ` : \"\", f = wrapTextWithPrefix(\n e.output,\n e.message,\n l,\n u\n ), s = `${i ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${f}\n`, c = this.value ? a : o;\n switch (this.state) {\n case \"submit\": {\n const r = i ? `${styleText(\"gray\", S_BAR)} ` : \"\";\n return `${s}${r}${styleText(\"dim\", c)}`;\n }\n case \"cancel\": {\n const r = i ? `${styleText(\"gray\", S_BAR)} ` : \"\";\n return `${s}${r}${styleText([\"strikethrough\", \"dim\"], c)}${i ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n }\n default: {\n const r = i ? `${styleText(\"cyan\", S_BAR)} ` : \"\", g = i ? styleText(\"cyan\", S_BAR_END) : \"\";\n return `${s}${r}${this.value ? `${styleText(\"green\", S_RADIO_ACTIVE)} ${a}` : `${styleText(\"dim\", S_RADIO_INACTIVE)} ${styleText(\"dim\", a)}`}${e.vertical ? i ? `\n${styleText(\"cyan\", S_BAR)} ` : `\n` : ` ${styleText(\"dim\", \"/\")} `}${this.value ? `${styleText(\"dim\", S_RADIO_INACTIVE)} ${styleText(\"dim\", o)}` : `${styleText(\"green\", S_RADIO_ACTIVE)} ${o}`}\n${g}\n`;\n }\n }\n }\n }).prompt();\n};\n\nconst date = (e) => {\n const r = e.validate;\n return new DatePrompt({\n ...e,\n validate(t) {\n if (t === void 0)\n return e.defaultValue !== void 0 ? void 0 : r ? runValidation(r, t) : settings.date.messages.required;\n const o = (i) => i.toISOString().slice(0, 10);\n if (e.minDate && o(t) < o(e.minDate))\n return settings.date.messages.afterMin(e.minDate);\n if (e.maxDate && o(t) > o(e.maxDate))\n return settings.date.messages.beforeMax(e.maxDate);\n if (r) return runValidation(r, t);\n },\n render() {\n const t = (e?.withGuide ?? settings.withGuide) !== false, i = `${`${t ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)} `}${e.message}\n`, l = this.state !== \"initial\" ? this.state : \"active\", d = b(this, l), c = this.value instanceof Date ? this.formattedValue : \"\";\n switch (this.state) {\n case \"error\": {\n const a = this.error ? ` ${styleText(\"yellow\", this.error)}` : \"\", s = t ? `${styleText(\"yellow\", S_BAR)} ` : \"\", f = t ? styleText(\"yellow\", S_BAR_END) : \"\";\n return `${i.trim()}\n${s}${d}\n${f}${a}\n`;\n }\n case \"submit\": {\n const a = c ? ` ${styleText(\"dim\", c)}` : \"\", s = t ? styleText(\"gray\", S_BAR) : \"\";\n return `${i}${s}${a}`;\n }\n case \"cancel\": {\n const a = c ? ` ${styleText([\"strikethrough\", \"dim\"], c)}` : \"\", s = t ? styleText(\"gray\", S_BAR) : \"\";\n return `${i}${s}${a}${c.trim() ? `\n${s}` : \"\"}`;\n }\n default: {\n const a = t ? `${styleText(\"cyan\", S_BAR)} ` : \"\", s = t ? styleText(\"cyan\", S_BAR_END) : \"\", f = t ? `${styleText(\"cyan\", S_BAR)} ` : \"\", g = this.inlineError ? `\n${f}${styleText(\"yellow\", this.inlineError)}` : \"\";\n return `${i}${a}${d}${g}\n${s}\n`;\n }\n }\n }\n }).prompt();\n};\nfunction b(e, r) {\n const t = e.segmentValues, o = e.segmentCursor;\n if (r === \"submit\" || r === \"cancel\")\n return e.formattedValue;\n const i = styleText(\"gray\", e.separator);\n return e.segments.map((l, d) => {\n const c = d === o.segmentIndex && ![\"submit\", \"cancel\"].includes(r), a = p[l.type];\n return x(t[l.type], { isActive: c, label: a });\n }).join(i);\n}\nfunction x(e, r) {\n const t = !e || e.replace(/_/g, \"\") === \"\";\n return r.isActive ? styleText(\"inverse\", t ? r.label : e.replace(/_/g, \" \")) : t ? styleText(\"dim\", r.label) : e.replace(/_/g, styleText(\"dim\", \" \"));\n}\nconst p = {\n year: \"yyyy\",\n month: \"mm\",\n day: \"dd\"\n};\n\nconst group = async (o, r) => {\n const t = {}, p = Object.keys(o);\n for (const e of p) {\n const i = o[e], n = await i({ results: t })?.catch((a) => {\n throw a;\n });\n if (typeof r?.onCancel == \"function\" && isCancel(n)) {\n t[e] = \"canceled\", r.onCancel({ results: t });\n continue;\n }\n t[e] = n;\n }\n return t;\n};\n\nconst MULTISELECT_INSTRUCTIONS = [\n `${styleText(\"dim\", \"\\u2191/\\u2193\")} to navigate`,\n `${styleText(\"dim\", \"Space:\")} select`,\n `${styleText(\"dim\", \"Enter:\")} confirm`\n];\nconst m = (n, u) => n.split(`\n`).map((d) => u(d)).join(`\n`);\nconst multiselect = (n) => {\n const u = (t, a) => {\n const r = t.label ?? String(t.value);\n return a === \"disabled\" ? `${styleText(\"gray\", S_CHECKBOX_INACTIVE)} ${m(r, (o) => styleText([\"strikethrough\", \"gray\"], o))}${t.hint ? ` ${styleText(\"dim\", `(${t.hint ?? \"disabled\"})`)}` : \"\"}` : a === \"active\" ? `${styleText(\"cyan\", S_CHECKBOX_ACTIVE)} ${r}${t.hint ? ` ${styleText(\"dim\", `(${t.hint})`)}` : \"\"}` : a === \"selected\" ? `${styleText(\"green\", S_CHECKBOX_SELECTED)} ${m(r, (o) => styleText(\"dim\", o))}${t.hint ? ` ${styleText(\"dim\", `(${t.hint})`)}` : \"\"}` : a === \"cancelled\" ? `${m(r, (o) => styleText([\"strikethrough\", \"dim\"], o))}` : a === \"active-selected\" ? `${styleText(\"green\", S_CHECKBOX_SELECTED)} ${r}${t.hint ? ` ${styleText(\"dim\", `(${t.hint})`)}` : \"\"}` : a === \"submitted\" ? `${m(r, (o) => styleText(\"dim\", o))}` : `${styleText(\"dim\", S_CHECKBOX_INACTIVE)} ${m(r, (o) => styleText(\"dim\", o))}`;\n }, d = n.required ?? true, x = n.showInstructions ?? true;\n return new MultiSelectPrompt({\n options: n.options,\n signal: n.signal,\n input: n.input,\n output: n.output,\n initialValues: n.initialValues,\n required: d,\n cursorAt: n.cursorAt,\n validate(t) {\n if (d && (t === void 0 || t.length === 0))\n return `Please select at least one option.\n${styleText(\n \"reset\",\n styleText(\n \"dim\",\n `Press ${styleText([\"gray\", \"bgWhite\", \"inverse\"], \" space \")} to select, ${styleText(\n \"gray\",\n styleText(\"bgWhite\", styleText(\"inverse\", \" enter \"))\n )} to submit`\n )\n )}`;\n },\n render() {\n const t = n.withGuide ?? settings.withGuide, a = wrapTextWithPrefix(\n n.output,\n n.message,\n t ? `${symbolBar(this.state)} ` : \"\",\n `${symbol(this.state)} `\n ), r = `${t ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${a}\n`, o = this.value ?? [], g = (i, l) => {\n if (i.disabled)\n return u(i, \"disabled\");\n const s = o.includes(i.value);\n return l && s ? u(i, \"active-selected\") : s ? u(i, \"selected\") : u(i, l ? \"active\" : \"inactive\");\n };\n switch (this.state) {\n case \"submit\": {\n const i = this.options.filter(({ value: s }) => o.includes(s)).map((s) => u(s, \"submitted\")).join(styleText(\"dim\", \", \")) || styleText(\"dim\", \"none\"), l = wrapTextWithPrefix(\n n.output,\n i,\n t ? `${styleText(\"gray\", S_BAR)} ` : \"\"\n );\n return `${r}${l}`;\n }\n case \"cancel\": {\n const i = this.options.filter(({ value: s }) => o.includes(s)).map((s) => u(s, \"cancelled\")).join(styleText(\"dim\", \", \"));\n if (i.trim() === \"\")\n return `${r}${styleText(\"gray\", S_BAR)}`;\n const l = wrapTextWithPrefix(\n n.output,\n i,\n t ? `${styleText(\"gray\", S_BAR)} ` : \"\"\n );\n return `${r}${l}${t ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n }\n case \"error\": {\n const i = t ? `${styleText(\"yellow\", S_BAR)} ` : \"\", l = this.error.split(`\n`).map(\n ($, v) => v === 0 ? `${t ? `${styleText(\"yellow\", S_BAR_END)} ` : \"\"}${styleText(\"yellow\", $)}` : ` ${$}`\n ).join(`\n`), s = r.split(`\n`).length, h = l.split(`\n`).length + 1;\n return `${r}${i}${limitOptions({\n output: n.output,\n options: this.options,\n cursor: this.cursor,\n maxItems: n.maxItems,\n columnPadding: i.length,\n rowPadding: s + h,\n style: g\n }).join(`\n${i}`)}\n${l}\n`;\n }\n default: {\n const i = t ? `${styleText(\"cyan\", S_BAR)} ` : \"\", l = r.split(`\n`).length, s = x ? formatInstructionFooter(n.output, MULTISELECT_INSTRUCTIONS, t) : t ? [styleText(\"cyan\", S_BAR_END)] : [], h = s.join(`\n`), $ = s.length + 1;\n return `${r}${i}${limitOptions({\n output: n.output,\n options: this.options,\n cursor: this.cursor,\n maxItems: n.maxItems,\n columnPadding: i.length,\n rowPadding: l + $,\n style: g\n }).join(`\n${i}`)}\n${h}\n`;\n }\n }\n }\n }).prompt();\n};\n\nconst groupMultiselect = (r) => {\n const { selectableGroups: f = true, groupSpacing: x = 0 } = r, d = (n, l, p = []) => {\n const a = n.label ?? String(n.value), t = typeof n.group == \"string\", u = t && (p[p.indexOf(n) + 1] ?? { group: true }), s = t && u && u.group === true;\n let o = \"\", c = \"\";\n t && (f ? (o = s ? `${S_BAR_END} ` : `${S_BAR} `, c = s ? \" \" : `${S_BAR} `) : o = \" \");\n let i = \"\";\n if (x > 0 && !t && (i = `\n`.repeat(x)), l === \"active\")\n return wrapTextWithPrefix(\n r.output,\n `${a}${n.hint ? ` ${styleText(\"dim\", `(${n.hint})`)}` : \"\"}`,\n `${i}${styleText(\"dim\", o)} `,\n `${i}${styleText(\"dim\", o)}${styleText(\"cyan\", S_CHECKBOX_ACTIVE)} `,\n `${i}${styleText(\"dim\", c)} `\n );\n if (l === \"group-active\")\n return wrapTextWithPrefix(\n r.output,\n a,\n `${i}${o} `,\n `${i}${o}${styleText(\"cyan\", S_CHECKBOX_ACTIVE)} `,\n `${i}${c} `,\n (m) => styleText(\"dim\", m)\n );\n if (l === \"group-active-selected\")\n return wrapTextWithPrefix(\n r.output,\n a,\n `${i}${o} `,\n `${i}${o}${styleText(\"green\", S_CHECKBOX_SELECTED)} `,\n `${i}${c} `,\n (m) => styleText(\"dim\", m)\n );\n if (l === \"selected\") {\n const m = t || f ? styleText(\"green\", S_CHECKBOX_SELECTED) : \"\";\n return wrapTextWithPrefix(\n r.output,\n `${a}${n.hint ? ` (${n.hint})` : \"\"}`,\n `${i}${styleText(\"dim\", o)} `,\n `${i}${styleText(\"dim\", o)}${m} `,\n `${i}${styleText(\"dim\", c)} `,\n (I) => styleText(\"dim\", I)\n );\n }\n if (l === \"cancelled\")\n return `${styleText([\"strikethrough\", \"dim\"], a)}`;\n if (l === \"active-selected\")\n return wrapTextWithPrefix(\n r.output,\n `${a}${n.hint ? ` ${styleText(\"dim\", `(${n.hint})`)}` : \"\"}`,\n `${i}${styleText(\"dim\", o)} `,\n `${i}${styleText(\"dim\", o)}${styleText(\"green\", S_CHECKBOX_SELECTED)} `,\n `${i}${styleText(\"dim\", c)} `\n );\n if (l === \"submitted\")\n return `${styleText(\"dim\", a)}`;\n const h = t || f ? styleText(\"dim\", S_CHECKBOX_INACTIVE) : \"\";\n return wrapTextWithPrefix(\n r.output,\n a,\n `${i}${styleText(\"dim\", o)} `,\n `${i}${styleText(\"dim\", o)}${h} `,\n `${i}${styleText(\"dim\", c)} `,\n (m) => styleText(\"dim\", m)\n );\n }, y = r.required ?? true, S = r.showInstructions ?? true;\n return new GroupMultiSelectPrompt({\n options: r.options,\n signal: r.signal,\n input: r.input,\n output: r.output,\n initialValues: r.initialValues,\n required: y,\n cursorAt: r.cursorAt,\n selectableGroups: f,\n validate(n) {\n if (y && (n === void 0 || n.length === 0))\n return `Please select at least one option.\n${styleText(\n \"reset\",\n styleText(\n \"dim\",\n `Press ${styleText([\"gray\", \"bgWhite\", \"inverse\"], \" space \")} to select, ${styleText(\n \"gray\",\n styleText([\"bgWhite\", \"inverse\"], \" enter \")\n )} to submit`\n )\n )}`;\n },\n render() {\n const n = r.withGuide ?? settings.withGuide, l = `${n ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)} ${r.message}\n`, p = this.value ?? [], a = (t, u) => {\n const s = this.options, o = p.includes(t.value) || t.group === true && this.isGroupSelected(`${t.value}`);\n return !u && typeof t.group == \"string\" && this.options[this.cursor]?.value === t.group ? d(t, o ? \"group-active-selected\" : \"group-active\", s) : u && o ? d(t, \"active-selected\", s) : o ? d(t, \"selected\", s) : d(t, u ? \"active\" : \"inactive\", s);\n };\n switch (this.state) {\n case \"submit\": {\n const t = this.options.filter(({ value: s }) => p.includes(s)).map((s) => d(s, \"submitted\")), u = t.length === 0 ? \"\" : ` ${t.join(styleText(\"dim\", \", \"))}`;\n return `${l}${n ? styleText(\"gray\", S_BAR) : \"\"}${u}`;\n }\n case \"cancel\": {\n const t = this.options.filter(({ value: u }) => p.includes(u)).map((u) => d(u, \"cancelled\")).join(styleText(\"dim\", \", \"));\n return `${l}${n ? `${styleText(\"gray\", S_BAR)} ` : \"\"}${t.trim() ? `${t}${n ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}` : \"\"}`;\n }\n case \"error\": {\n const t = n ? `${styleText(\"yellow\", S_BAR)} ` : \"\", u = this.error.split(`\n`).map(\n (i, h) => h === 0 ? `${n ? `${styleText(\"yellow\", S_BAR_END)} ` : \"\"}${styleText(\"yellow\", i)}` : ` ${i}`\n ).join(`\n`), s = l.split(`\n`).length, o = u.split(`\n`).length + 1, c = limitOptions({\n output: r.output,\n options: this.options,\n cursor: this.cursor,\n maxItems: r.maxItems,\n columnPadding: t.length,\n rowPadding: s + o,\n style: a\n }).join(`\n${t}`);\n return `${l}${t}${c}\n${u}\n`;\n }\n default: {\n const t = n ? `${styleText(\"cyan\", S_BAR)} ` : \"\", u = l.split(`\n`).length, s = S ? formatInstructionFooter(r.output, MULTISELECT_INSTRUCTIONS, n) : n ? [styleText(\"cyan\", S_BAR_END)] : [], o = s.join(`\n`), c = s.length + 1, i = limitOptions({\n output: r.output,\n options: this.options,\n cursor: this.cursor,\n maxItems: r.maxItems,\n columnPadding: t.length,\n rowPadding: u + c,\n style: a\n }).join(`\n${t}`);\n return `${l}${t}${i}\n${o}\n`;\n }\n }\n }\n }).prompt();\n};\n\nconst log = {\n message: (s = [], {\n symbol: e = styleText(\"gray\", S_BAR),\n secondarySymbol: r = styleText(\"gray\", S_BAR),\n output: m = process.stdout,\n spacing: l = 1,\n withGuide: c\n } = {}) => {\n const t = [], o = c ?? settings.withGuide, f = o ? r : \"\", O = o ? `${e} ` : \"\", u = o ? `${r} ` : \"\";\n for (let i = 0; i < l; i++)\n t.push(f);\n const g = Array.isArray(s) ? s : s.split(`\n`);\n if (g.length > 0) {\n const [i, ...y] = g;\n i.length > 0 ? t.push(`${O}${i}`) : t.push(o ? e : \"\");\n for (const p of y)\n p.length > 0 ? t.push(`${u}${p}`) : t.push(o ? r : \"\");\n }\n m.write(`${t.join(`\n`)}\n`);\n },\n info: (s, e) => {\n log.message(s, { ...e, symbol: styleText(\"blue\", S_INFO) });\n },\n success: (s, e) => {\n log.message(s, { ...e, symbol: styleText(\"green\", S_SUCCESS) });\n },\n step: (s, e) => {\n log.message(s, { ...e, symbol: styleText(\"green\", S_STEP_SUBMIT) });\n },\n warn: (s, e) => {\n log.message(s, { ...e, symbol: styleText(\"yellow\", S_WARN) });\n },\n /** alias for `log.warn()`. */\n warning: (s, e) => {\n log.warn(s, e);\n },\n error: (s, e) => {\n log.message(s, { ...e, symbol: styleText(\"red\", S_ERROR) });\n }\n};\n\nconst cancel = (o = \"\", t) => {\n const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText(\"gray\", S_BAR_END)} ` : \"\";\n i.write(`${e}${styleText(\"red\", o)}\n\n`);\n}, intro = (o = \"\", t) => {\n const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText(\"gray\", S_BAR_START)} ` : \"\";\n i.write(`${e}${o}\n`);\n}, outro = (o = \"\", t) => {\n const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText(\"gray\", S_BAR)}\n${styleText(\"gray\", S_BAR_END)} ` : \"\";\n i.write(`${e}${o}\n\n`);\n};\n\nconst multiline = (e) => new MultiLinePrompt({\n validate: e.validate,\n placeholder: e.placeholder,\n defaultValue: e.defaultValue,\n initialValue: e.initialValue,\n showSubmit: e.showSubmit,\n output: e.output,\n signal: e.signal,\n input: e.input,\n render() {\n const i = e?.withGuide ?? settings.withGuide, o = `${`${i ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)} `}${e.message}\n`, h = e.placeholder && e.placeholder.length > 0 ? (\n // biome-ignore lint/style/noNonNullAssertion: guarded by placeholder.length > 0\n styleText(\"inverse\", e.placeholder[0]) + styleText(\"dim\", e.placeholder.slice(1))\n ) : styleText([\"inverse\", \"hidden\"], \"_\"), a = this.userInput ? this.userInputWithCursor : h, l = this.value ?? \"\", d = e.showSubmit ? `\n ${styleText(this.focused === \"submit\" ? \"cyan\" : \"dim\", \"[ submit ]\")}` : \"\";\n switch (this.state) {\n case \"error\": {\n const n = `${styleText(\"yellow\", S_BAR)} `, r = i ? wrapTextWithPrefix(e.output, a, n, void 0) : a, u = styleText(\"yellow\", S_BAR_END);\n return `${o}${r}\n${u} ${styleText(\"yellow\", this.error)}${d}\n`;\n }\n case \"submit\": {\n const n = `${styleText(\"gray\", S_BAR)} `, r = i ? wrapTextWithPrefix(\n e.output,\n l,\n n,\n void 0,\n void 0,\n (u) => styleText(\"dim\", u)\n ) : l ? styleText(\"dim\", l) : \"\";\n return `${o}${r}`;\n }\n case \"cancel\": {\n const n = `${styleText(\"gray\", S_BAR)} `, r = i ? wrapTextWithPrefix(\n e.output,\n l,\n n,\n void 0,\n void 0,\n (u) => styleText([\"strikethrough\", \"dim\"], u)\n ) : l ? styleText([\"strikethrough\", \"dim\"], l) : \"\";\n return `${o}${r}`;\n }\n default: {\n const n = i ? `${styleText(\"cyan\", S_BAR)} ` : \"\", r = i ? styleText(\"cyan\", S_BAR_END) : \"\", u = i ? wrapTextWithPrefix(e.output, a, n) : a;\n return `${o}${u}\n${r}${d}\n`;\n }\n }\n }\n}).prompt();\n\nconst W = (o) => o, C = (o, e, s) => {\n const a = {\n hard: true,\n trim: false\n }, i = wrapAnsi(o, e, a).split(`\n`), c = i.reduce((n, t) => Math.max(l(t), n), 0), u = i.map(s).reduce((n, t) => Math.max(l(t), n), 0), g = e - (u - c);\n return wrapAnsi(o, g, a);\n};\nconst note = (o = \"\", e = \"\", s) => {\n const a = s?.output ?? process$1.stdout, i = s?.withGuide ?? settings.withGuide, c = s?.format ?? W, g = [\"\", ...C(o, getColumns(a) - 6, c).split(`\n`).map(c), \"\"], n = l(e), t = Math.max(\n g.reduce((m, F) => {\n const O = l(F);\n return O > m ? O : m;\n }, 0),\n n\n ) + 2, h = g.map(\n (m) => `${styleText(\"gray\", S_BAR)} ${m}${\" \".repeat(t - l(m))}${styleText(\"gray\", S_BAR)}`\n ).join(`\n`), T = i ? `${styleText(\"gray\", S_BAR)}\n` : \"\", l$1 = i ? S_CONNECT_LEFT : S_CORNER_BOTTOM_LEFT;\n a.write(\n `${T}${styleText(\"green\", S_STEP_SUBMIT)} ${styleText(\"reset\", e)} ${styleText(\n \"gray\",\n S_BAR_H.repeat(Math.max(t - n - 1, 1)) + S_CORNER_TOP_RIGHT\n )}\n${h}\n${styleText(\"gray\", l$1 + S_BAR_H.repeat(t + 2) + S_CORNER_BOTTOM_RIGHT)}\n`\n );\n};\n\nconst password = (e) => new PasswordPrompt({\n validate: e.validate,\n mask: e.mask ?? S_PASSWORD_MASK,\n signal: e.signal,\n input: e.input,\n output: e.output,\n render() {\n const r = e.withGuide ?? settings.withGuide, o = `${r ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)} ${e.message}\n`, m = this.userInputWithCursor, i = this.masked;\n switch (this.state) {\n case \"error\": {\n const s = r ? `${styleText(\"yellow\", S_BAR)} ` : \"\", n = r ? `${styleText(\"yellow\", S_BAR_END)} ` : \"\", d = i ?? \"\";\n return e.clearOnError && this.clear(), `${o.trim()}\n${s}${d}\n${n}${styleText(\"yellow\", this.error)}\n`;\n }\n case \"submit\": {\n const s = r ? `${styleText(\"gray\", S_BAR)} ` : \"\", n = i ? styleText(\"dim\", i) : \"\";\n return `${o}${s}${n}`;\n }\n case \"cancel\": {\n const s = r ? `${styleText(\"gray\", S_BAR)} ` : \"\", n = i ? styleText([\"strikethrough\", \"dim\"], i) : \"\";\n return `${o}${s}${n}${i && r ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n }\n default: {\n const s = r ? `${styleText(\"cyan\", S_BAR)} ` : \"\", n = r ? styleText(\"cyan\", S_BAR_END) : \"\";\n return `${o}${s}${m}\n${n}\n`;\n }\n }\n }\n}).prompt();\n\nconst path = (e) => {\n const a = e.validate;\n return autocomplete({\n ...e,\n initialUserInput: e.initialValue ?? e.root ?? process.cwd(),\n maxItems: 5,\n completeOnTab: true,\n validate(t) {\n if (!Array.isArray(t)) {\n if (!t)\n return \"Please select a path\";\n if (a)\n return runValidation(a, t);\n }\n },\n options() {\n const t = this.userInput;\n if (t === \"\")\n return [];\n try {\n let i;\n const o = t.endsWith(\"/\") || t.endsWith(\"\\\\\");\n existsSync(t) ? lstatSync(t).isDirectory() && (!e.directory || o) ? i = t : i = dirname(t) : i = dirname(t);\n const m = t.length > 1 && o ? t.slice(0, -1) : t;\n return readdirSync(i).map((r) => {\n const n = join(i, r), l = lstatSync(n);\n return {\n name: r,\n path: n,\n isDirectory: l.isDirectory()\n };\n }).filter(\n ({ path: r, isDirectory: n }) => r.startsWith(m) && (n || !e.directory)\n ).map((r) => ({\n value: r.path\n }));\n } catch {\n return [];\n }\n }\n });\n};\n\nconst Y = 3e4, Z = (c) => styleText(\"magenta\", c);\nconst spinner = ({\n indicator: c = \"dots\",\n onCancel: b,\n output: n = process.stdout,\n cancelMessage: _,\n errorMessage: C,\n frames: M = unicode ? [\"\\u25D2\", \"\\u25D0\", \"\\u25D3\", \"\\u25D1\"] : [\"\\u2022\", \"o\", \"O\", \"0\"],\n delay: O = unicode ? 80 : 120,\n signal: g,\n ...E\n} = {}) => {\n const u = isCI(), h = isAccessible(E.accessible);\n let x, I, p = false, l = false, r = \"\", v, w = performance.now();\n const y = getColumns(n), F = E?.styleFrame ?? Z, S = (e) => {\n const s = e > 1 ? C ?? settings.messages.error : _ ?? settings.messages.cancel;\n l = e === 1, p && (m(s, e), l && typeof b == \"function\" && b());\n }, $ = () => S(2), a = () => S(1), H = () => {\n process.on(\"uncaughtExceptionMonitor\", $), process.on(\"unhandledRejection\", $), process.on(\"SIGINT\", a), process.on(\"SIGTERM\", a), process.on(\"exit\", S), g && g.addEventListener(\"abort\", a);\n }, B = () => {\n process.removeListener(\"uncaughtExceptionMonitor\", $), process.removeListener(\"unhandledRejection\", $), process.removeListener(\"SIGINT\", a), process.removeListener(\"SIGTERM\", a), process.removeListener(\"exit\", S), g && g.removeEventListener(\"abort\", a);\n }, R = () => {\n if (v === void 0) return;\n u && n.write(`\n`);\n const s = wrapAnsi(v, y, {\n hard: true,\n trim: false\n }).split(`\n`);\n s.length > 1 && n.write(cursor.up(s.length - 1)), n.write(cursor.to(0)), n.write(erase.down());\n }, L = (e) => e.replace(/\\.+$/, \"\"), T = (e) => {\n const s = (performance.now() - e) / 1e3, i = Math.floor(s / 60), t = Math.floor(s % 60);\n return i > 0 ? `[${i}m ${t}s]` : `[${t}s]`;\n }, N = E.withGuide ?? settings.withGuide, P = (e = \"\") => {\n if (p = true, l = false, r = L(e), w = performance.now(), H(), h) {\n r !== \"\" && n.write(`${r}\n`), I = setInterval(() => {\n n.write(r === \"\" ? `still working\n` : `still working: ${r}\n`);\n }, Y);\n return;\n }\n x = block({ output: n }), N && n.write(`${styleText(\"gray\", S_BAR)}\n`);\n let s = 0, i = 0;\n I = setInterval(() => {\n if (u && r === v)\n return;\n R(), v = r;\n const t = F(M[s]);\n let o;\n if (u)\n o = `${t} ${r}...`;\n else if (c === \"timer\")\n o = `${t} ${r} ${T(w)}`;\n else {\n const j = \".\".repeat(Math.floor(i)).slice(0, 3);\n o = `${t} ${r}${j}`;\n }\n const D = wrapAnsi(o, y, {\n hard: true,\n trim: false\n });\n n.write(D), s = s + 1 < M.length ? s + 1 : 0, i = i < 4 ? i + 0.125 : 0;\n }, O);\n }, m = (e = \"\", s = 0, i = false) => {\n if (p) {\n if (p = false, l = s === 1, clearInterval(I), h || R(), r = e ?? r, !i)\n if (h) {\n const t = s === 1 ? _ ?? settings.messages.cancel : s === 2 ? C ?? settings.messages.error : \"Done\", o = r || t;\n c === \"timer\" ? n.write(`${o} ${T(w)}\n`) : n.write(`${o}\n`);\n } else {\n const t = s === 0 ? styleText(\"green\", S_STEP_SUBMIT) : s === 1 ? styleText(\"red\", S_STEP_CANCEL) : styleText(\"red\", S_STEP_ERROR);\n c === \"timer\" ? n.write(`${t} ${r} ${T(w)}\n`) : n.write(`${t} ${r}\n`);\n }\n B(), x?.();\n }\n };\n return {\n start: P,\n stop: (e = \"\") => m(e, 0),\n message: (e = \"\") => {\n r = L(e ?? r);\n },\n cancel: (e = \"\") => m(e, 1),\n error: (e = \"\") => m(e, 2),\n clear: () => m(\"\", 0, true),\n get isCancelled() {\n return l;\n }\n };\n};\n\nconst u = {\n light: unicodeOr(\"\\u2500\", \"-\"),\n heavy: unicodeOr(\"\\u2501\", \"=\"),\n block: unicodeOr(\"\\u2588\", \"#\")\n};\nfunction progress({\n style: o = \"heavy\",\n max: d = 100,\n size: v = 40,\n ...x\n} = {}) {\n const r = spinner(x);\n let a = 0, n = \"\";\n const c = Math.max(1, d), l = Math.max(1, v), S = (t) => {\n switch (t) {\n case \"initial\":\n case \"active\":\n return (e) => styleText(\"magenta\", e);\n case \"error\":\n case \"cancel\":\n return (e) => styleText(\"red\", e);\n case \"submit\":\n return (e) => styleText(\"green\", e);\n default:\n return (e) => styleText(\"magenta\", e);\n }\n }, p = (t, e) => {\n const m = Math.floor(a / c * l);\n return `${S(t)(u[o].repeat(m))}${styleText(\"dim\", u[o].repeat(l - m))} ${e}`;\n }, h = (t = \"\") => {\n n = t, r.start(p(\"initial\", t));\n }, g = (t = 1, e) => {\n a = Math.min(c, t + a), r.message(p(\"active\", e ?? n)), n = e ?? n;\n };\n return {\n start: h,\n stop: r.stop,\n cancel: r.cancel,\n error: r.error,\n clear: r.clear,\n advance: g,\n get isCancelled() {\n return r.isCancelled;\n },\n message: (t) => g(0, t)\n };\n}\n\nconst SELECT_INSTRUCTIONS = [\n `${styleText(\"dim\", \"\\u2191/\\u2193\")} to navigate`,\n `${styleText(\"dim\", \"Enter:\")} confirm`\n];\nconst c = (t, o) => t.includes(`\n`) ? t.split(`\n`).map((d) => o(d)).join(`\n`) : o(t);\nconst select = (t) => {\n const o = (n, m) => {\n if (n === void 0)\n return \"\";\n const s = n.label ?? String(n.value);\n switch (m) {\n case \"disabled\":\n return `${styleText(\"gray\", S_RADIO_INACTIVE)} ${c(s, (i) => styleText(\"gray\", i))}${n.hint ? ` ${styleText(\"dim\", `(${n.hint ?? \"disabled\"})`)}` : \"\"}`;\n case \"selected\":\n return `${c(s, (i) => styleText(\"dim\", i))}`;\n case \"active\":\n return `${styleText(\"green\", S_RADIO_ACTIVE)} ${s}${n.hint ? ` ${styleText(\"dim\", `(${n.hint})`)}` : \"\"}`;\n case \"cancelled\":\n return `${c(s, (i) => styleText([\"strikethrough\", \"dim\"], i))}`;\n default:\n return `${styleText(\"dim\", S_RADIO_INACTIVE)} ${c(s, (i) => styleText(\"dim\", i))}`;\n }\n }, d = t.showInstructions ?? true;\n return new SelectPrompt({\n options: t.options,\n signal: t.signal,\n input: t.input,\n output: t.output,\n initialValue: t.initialValue,\n render() {\n const n = t.withGuide ?? settings.withGuide, m = `${symbol(this.state)} `, s = `${symbolBar(this.state)} `, i = wrapTextWithPrefix(\n t.output,\n t.message,\n s,\n m\n ), u = `${n ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${i}\n`;\n switch (this.state) {\n case \"submit\": {\n const r = n ? `${styleText(\"gray\", S_BAR)} ` : \"\", a = wrapTextWithPrefix(\n t.output,\n o(this.options[this.cursor], \"selected\"),\n r\n );\n return `${u}${a}`;\n }\n case \"cancel\": {\n const r = n ? `${styleText(\"gray\", S_BAR)} ` : \"\", a = wrapTextWithPrefix(\n t.output,\n o(this.options[this.cursor], \"cancelled\"),\n r\n );\n return `${u}${a}${n ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n }\n default: {\n const r = n ? `${styleText(\"cyan\", S_BAR)} ` : \"\", a = u.split(`\n`).length, p = d ? formatInstructionFooter(t.output, SELECT_INSTRUCTIONS, n) : n ? [styleText(\"cyan\", S_BAR_END)] : [], f = p.join(`\n`), b = p.length + 1;\n return `${u}${r}${limitOptions({\n output: t.output,\n cursor: this.cursor,\n options: this.options,\n maxItems: t.maxItems,\n columnPadding: r.length,\n rowPadding: a + b,\n style: (g, x) => o(g, g.disabled ? \"disabled\" : x ? \"active\" : \"inactive\")\n }).join(`\n${r}`)}\n${f}\n`;\n }\n }\n }\n }).prompt();\n};\n\nconst selectKey = (i) => {\n const c = (e, a = \"inactive\") => {\n if (e === void 0)\n return \"\";\n const n = e.label ?? String(e.value);\n return a === \"disabled\" ? `${styleText(\"dim\", ` ${e.value} `)} ${styleText(\"gray\", n)}${e.hint ? ` ${styleText(\"dim\", `(${e.hint})`)}` : \"\"}` : a === \"selected\" ? `${styleText(\"dim\", n)}` : a === \"cancelled\" ? `${styleText([\"strikethrough\", \"dim\"], n)}` : a === \"active\" ? `${styleText([\"bgCyan\", \"gray\"], ` ${e.value} `)} ${n}${e.hint ? ` ${styleText(\"dim\", `(${e.hint})`)}` : \"\"}` : `${styleText([\"gray\", \"bgWhite\", \"inverse\"], ` ${e.value} `)} ${n}${e.hint ? ` ${styleText(\"dim\", `(${e.hint})`)}` : \"\"}`;\n };\n return new SelectKeyPrompt({\n options: i.options,\n signal: i.signal,\n input: i.input,\n output: i.output,\n initialValue: i.initialValue,\n caseSensitive: i.caseSensitive,\n render() {\n const e = i.withGuide ?? settings.withGuide, a = `${e ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)} ${i.message}\n`;\n switch (this.state) {\n case \"submit\": {\n const n = e ? `${styleText(\"gray\", S_BAR)} ` : \"\", r = this.options.find((l) => l.value === this.value) ?? i.options[0], u = wrapTextWithPrefix(\n i.output,\n c(r, \"selected\"),\n n\n );\n return `${a}${u}`;\n }\n case \"cancel\": {\n const n = e ? `${styleText(\"gray\", S_BAR)} ` : \"\", r = wrapTextWithPrefix(\n i.output,\n c(this.options[0], \"cancelled\"),\n n\n );\n return `${a}${r}${e ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n }\n default: {\n const n = e ? `${styleText(\"cyan\", S_BAR)} ` : \"\", r = e ? styleText(\"cyan\", S_BAR_END) : \"\", u = this.options.map(\n (l, $) => wrapTextWithPrefix(\n i.output,\n c(\n l,\n l.disabled ? \"disabled\" : $ === this.cursor ? \"active\" : \"inactive\"\n ),\n n\n )\n ).join(`\n`);\n return `${a}${u}\n${r}\n`;\n }\n }\n }\n }).prompt();\n};\n\nconst i = `${styleText(\"gray\", S_BAR)} `;\nconst stream = {\n message: async (e, { symbol: l = styleText(\"gray\", S_BAR) } = {}) => {\n process.stdout.write(`${styleText(\"gray\", S_BAR)}\n${l} `);\n let s = 3;\n for await (let r of e) {\n r = r.replace(/\\n/g, `\n${i}`), r.includes(`\n`) && (s = 3 + stripVTControlCharacters(r.slice(r.lastIndexOf(`\n`))).length);\n const o = stripVTControlCharacters(r).length;\n s + o < process.stdout.columns ? (s += o, process.stdout.write(r)) : (process.stdout.write(`\n${i}${r.trimStart()}`), s = 3 + stripVTControlCharacters(r.trimStart()).length);\n }\n process.stdout.write(`\n`);\n },\n info: (e) => stream.message(e, { symbol: styleText(\"blue\", S_INFO) }),\n success: (e) => stream.message(e, { symbol: styleText(\"green\", S_SUCCESS) }),\n step: (e) => stream.message(e, { symbol: styleText(\"green\", S_STEP_SUBMIT) }),\n warn: (e) => stream.message(e, { symbol: styleText(\"yellow\", S_WARN) }),\n /** alias for `log.warn()`. */\n warning: (e) => stream.warn(e),\n error: (e) => stream.message(e, { symbol: styleText(\"red\", S_ERROR) })\n};\n\nconst tasks = async (o, e) => {\n for (const t of o) {\n if (t.enabled === false) continue;\n const s = spinner(e);\n s.start(t.title);\n const n = await t.task(s.message);\n s.stop(n || t.title);\n }\n};\n\nconst A = (l) => l.replace(/\\x1b\\[(?:\\d+;)*\\d*[ABCDEFGHfJKSTsu]|\\x1b\\[(s|u)/g, \"\");\nconst taskLog = (l) => {\n const r = l.output ?? process.stdout, O = getColumns(r), i = styleText(\"gray\", S_BAR), p = l.spacing ?? 1, k = 3, m = l.retainLog === true, d = !isCI() && isTTY(r);\n r.write(`${i}\n`), r.write(`${styleText(\"green\", S_STEP_SUBMIT)} ${l.title}\n`);\n for (let e = 0; e < p; e++)\n r.write(`${i}\n`);\n const n = [\n {\n value: \"\",\n full: \"\"\n }\n ];\n let v = false;\n const f = (e) => {\n if (n.length === 0)\n return;\n let s = 0;\n e && (s += p + 2);\n for (const t of n) {\n const { value: o, result: a } = t;\n let g = a?.message ?? o;\n if (g.length === 0)\n continue;\n a === void 0 && t.header !== void 0 && t.header !== \"\" && (g += `\n${t.header}`);\n const E = g.split(`\n`).reduce((b, w) => w === \"\" ? b + 1 : b + Math.ceil((w.length + k) / O), 0);\n s += E;\n }\n s > 0 && (s += 1, r.write(erase.lines(s)));\n }, h = (e, s, t) => {\n const o = t ? `${e.full}\n${e.value}` : e.value;\n e.header !== void 0 && e.header !== \"\" && log.message(\n e.header.split(`\n`).map((a) => styleText(\"bold\", a)),\n {\n output: r,\n secondarySymbol: i,\n symbol: i,\n spacing: 0\n }\n ), log.message(\n o.split(`\n`).map((a) => styleText(\"dim\", a)),\n {\n output: r,\n secondarySymbol: i,\n symbol: i,\n spacing: s ?? p\n }\n );\n }, T = () => {\n for (const e of n) {\n const { header: s, value: t, full: o } = e;\n (s === void 0 || s.length === 0) && t.length === 0 || h(e, void 0, m === true && o.length > 0);\n }\n }, L = (e, s, t) => {\n if (f(false), (t?.raw !== true || !v) && e.value !== \"\" && (e.value += `\n`), e.value += A(s), v = t?.raw === true, l.limit !== void 0) {\n const o = e.value.split(`\n`), a = o.length - l.limit;\n if (a > 0) {\n const g = o.splice(0, a);\n m && (e.full += (e.full === \"\" ? \"\" : `\n`) + g.join(`\n`));\n }\n e.value = o.join(`\n`);\n }\n d && y();\n }, y = () => {\n for (const e of n)\n e.result ? e.result.status === \"error\" ? log.error(e.result.message, { output: r, secondarySymbol: i, spacing: 0 }) : log.success(e.result.message, { output: r, secondarySymbol: i, spacing: 0 }) : e.value !== \"\" && h(e, 0);\n }, B = (e, s) => {\n f(false), e.result = s, d && y();\n };\n return {\n message(e, s) {\n L(n[0], e, s);\n },\n group(e) {\n const s = {\n header: e,\n value: \"\",\n full: \"\"\n };\n return n.push(s), {\n message(t, o) {\n L(s, t, o);\n },\n error(t) {\n B(s, {\n status: \"error\",\n message: t\n });\n },\n success(t) {\n B(s, {\n status: \"success\",\n message: t\n });\n }\n };\n },\n error(e, s) {\n f(true), log.error(e, { output: r, secondarySymbol: i, spacing: 1 }), s?.showLog !== false && T(), n.splice(1, n.length - 1), n[0].value = \"\", n[0].full = \"\";\n },\n success(e, s) {\n f(true), log.success(e, { output: r, secondarySymbol: i, spacing: 1 }), s?.showLog === true && T(), n.splice(1, n.length - 1), n[0].value = \"\", n[0].full = \"\";\n }\n };\n};\n\nconst text = (t) => new TextPrompt({\n validate: t.validate,\n placeholder: t.placeholder,\n defaultValue: t.defaultValue,\n initialValue: t.initialValue,\n output: t.output,\n signal: t.signal,\n input: t.input,\n render() {\n const r = t?.withGuide ?? settings.withGuide, l = `${`${r ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)} `}${t.message}\n`, d = t.placeholder && t.placeholder.length > 0 ? (\n // biome-ignore lint/style/noNonNullAssertion: guarded by placeholder.length > 0\n styleText(\"inverse\", t.placeholder[0]) + styleText(\"dim\", t.placeholder.slice(1))\n ) : styleText([\"inverse\", \"hidden\"], \"_\"), o = this.userInput ? this.userInputWithCursor : d, s = this.value ?? \"\";\n switch (this.state) {\n case \"validating\": {\n const n = r ? `${styleText(\"cyan\", S_BAR)} ` : \"\", i = r ? styleText(\"cyan\", S_BAR_END) : \"\", c = styleText(\"dim\", o), $ = styleText(\"dim\", \"Validating...\");\n return `${l}${n}${c}\n${i} ${$}\n`;\n }\n case \"error\": {\n const n = this.error ? ` ${styleText(\"yellow\", this.error)}` : \"\", i = r ? `${styleText(\"yellow\", S_BAR)} ` : \"\", c = r ? styleText(\"yellow\", S_BAR_END) : \"\";\n return `${l.trim()}\n${i}${o}\n${c}${n}\n`;\n }\n case \"submit\": {\n const n = s ? `${r ? \" \" : \"\"}${styleText(\"dim\", s)}` : \"\", i = r ? styleText(\"gray\", S_BAR) : \"\";\n return `${l}${i}${n}`;\n }\n case \"cancel\": {\n const n = s ? ` ${styleText([\"strikethrough\", \"dim\"], s)}` : \"\", i = r ? styleText(\"gray\", S_BAR) : \"\";\n return `${l}${i}${n}${s.trim() ? `\n${i}` : \"\"}`;\n }\n default: {\n const n = r ? `${styleText(\"cyan\", S_BAR)} ` : \"\", i = r ? styleText(\"cyan\", S_BAR_END) : \"\";\n return `${l}${n}${o}\n${i}\n`;\n }\n }\n }\n}).prompt();\n\nexport { MULTISELECT_INSTRUCTIONS, SELECT_INSTRUCTIONS, S_BAR, S_BAR_END, S_BAR_END_RIGHT, S_BAR_H, S_BAR_START, S_BAR_START_RIGHT, S_CHECKBOX_ACTIVE, S_CHECKBOX_INACTIVE, S_CHECKBOX_SELECTED, S_CONNECT_LEFT, S_CORNER_BOTTOM_LEFT, S_CORNER_BOTTOM_RIGHT, S_CORNER_TOP_LEFT, S_CORNER_TOP_RIGHT, S_ERROR, S_INFO, S_PASSWORD_MASK, S_RADIO_ACTIVE, S_RADIO_INACTIVE, S_STEP_ACTIVE, S_STEP_CANCEL, S_STEP_ERROR, S_STEP_SUBMIT, S_SUCCESS, S_WARN, autocomplete, autocompleteMultiselect, box, cancel, confirm, date, formatInstructionFooter, group, groupMultiselect, intro, isCI, isTTY, limitOptions, log, multiline, multiselect, note, outro, password, path, progress, select, selectKey, spinner, stream, symbol, symbolBar, taskLog, tasks, text, unicode, unicodeOr };\n","","/**\n * Optional post-scaffold `git init` + initial commit. Mirrors what\n * `create-vite`, `create-next-app`, and Cloudflare's `c3` already do\n * — gives the user (and any subsequent diff-driven workflow, human\n * or agent) a clean baseline-vs-HEAD diff for their first edits.\n *\n * Skips silently when:\n * - `outDir` is already inside a git work tree (nested repos confuse\n * more than they help; the user is scaffolding into an existing\n * workspace and the host repo owns the history).\n * - `git` is not installed (`git --version` fails).\n * - No global `user.name` / `user.email` is configured (the commit\n * would fail anyway; better to skip with a clear warning than to\n * leave a half-initialised `.git/` behind).\n *\n * DI'd via `GitRunner` so tests can stub spawning. The default impl\n * shells out via `spawnSync` (short calls; no need for the async\n * pump). Mirrors the `Installer` DI seam in `install.ts`.\n */\nimport { spawnSync } from \"node:child_process\";\nimport type { Pm } from \"./pm-detect.ts\";\n\nexport interface GitRunner {\n /**\n * Run `git <args>` in `cwd`. Returns the child's exit code and\n * captured stdout/stderr. Never throws on a non-zero exit — callers\n * branch on `code`. A missing `git` binary surfaces as `code: 127`\n * with the spawn error on `stderr`, so callers don't need a separate\n * try/catch for ENOENT.\n */\n run(args: readonly string[], cwd: string): { code: number; stdout: string; stderr: string };\n}\n\nexport const defaultGitRunner: GitRunner = {\n run: (args, cwd) => {\n const res = spawnSync(\"git\", [...args], { cwd, encoding: \"utf8\" });\n if (res.error !== undefined) {\n return { code: 127, stdout: \"\", stderr: res.error.message };\n }\n return {\n code: res.status ?? 1,\n stdout: res.stdout ?? \"\",\n stderr: res.stderr ?? \"\",\n };\n },\n};\n\nexport type GitInitOutcome =\n | { readonly initialized: true; readonly branch: \"main\" }\n | {\n readonly initialized: false;\n readonly reason:\n | \"already-in-repo\"\n | \"git-not-available\"\n | \"no-identity\"\n | \"init-failed\"\n | \"add-failed\"\n | \"commit-failed\";\n readonly message?: string;\n };\n\nexport interface GitInitDetails {\n /** Absolute path to the freshly-scaffolded directory. */\n readonly outDir: string;\n /** `create-baerly-storage` package version. Stamped into the commit body. */\n readonly cliVersion: string;\n /** Substituted `appName` sentinel from the scaffold. */\n readonly appName: string;\n readonly target: \"cloudflare\" | \"node\";\n readonly starter: \"minimal\" | \"react\";\n readonly pm: Pm;\n /** Optional; resolved by the runner via `probePmVersion()`. */\n readonly pmVersion?: string;\n}\n\nconst trim = (s: string): string => s.trim();\n\nconst isInsideGitWorkTree = (cwd: string, runner: GitRunner): boolean => {\n const res = runner.run([\"rev-parse\", \"--is-inside-work-tree\"], cwd);\n return res.code === 0 && trim(res.stdout) === \"true\";\n};\n\nconst probeGitVersion = (cwd: string, runner: GitRunner): string | undefined => {\n const res = runner.run([\"--version\"], cwd);\n if (res.code !== 0) {\n return undefined;\n }\n // \"git version 2.54.0\" — strip the prefix when present, otherwise\n // pass through whatever the shim emitted.\n const m = /^git version (\\S+)/.exec(trim(res.stdout));\n return m === null ? trim(res.stdout) : m[1];\n};\n\nconst hasIdentity = (cwd: string, runner: GitRunner): boolean => {\n const name = runner.run([\"config\", \"user.name\"], cwd);\n const email = runner.run([\"config\", \"user.email\"], cwd);\n return (\n name.code === 0 &&\n email.code === 0 &&\n trim(name.stdout).length > 0 &&\n trim(email.stdout).length > 0\n );\n};\n\nconst commitMessage = (details: GitInitDetails, gitVersion: string): string => {\n const pmLine =\n details.pmVersion === undefined ? details.pm : `${details.pm}@${details.pmVersion}`;\n return [\n \"Initial commit (by create-baerly-storage)\",\n \"\",\n \"Details:\",\n ` create-baerly-storage = ${details.cliVersion}`,\n ` project name = ${details.appName}`,\n ` target = ${details.target}`,\n ` starter = ${details.starter}`,\n ` package mgr = ${pmLine}`,\n ` git = ${gitVersion}`,\n \"\",\n ].join(\"\\n\");\n};\n\n/**\n * `git init --initial-branch=main` is rejected by gits older than\n * 2.28 (released 2020). Fall back to plain `git init` followed by\n * `symbolic-ref HEAD refs/heads/main` so the resulting branch is the\n * same regardless of which git the user has on PATH.\n */\nconst initWithMainBranch = (\n outDir: string,\n runner: GitRunner,\n): { code: number; message: string } => {\n const first = runner.run([\"init\", \"--initial-branch=main\"], outDir);\n if (first.code === 0) {\n return { code: 0, message: trim(first.stdout) };\n }\n const fallback = runner.run([\"init\"], outDir);\n if (fallback.code !== 0) {\n return { code: fallback.code, message: trim(fallback.stderr) };\n }\n const setBranch = runner.run([\"symbolic-ref\", \"HEAD\", \"refs/heads/main\"], outDir);\n return { code: setBranch.code, message: trim(setBranch.stderr) };\n};\n\n/**\n * `outDir` must already exist on disk (scaffold has written into it).\n * Probes are all DI'd through the runner, so a test stub controls the\n * whole flow — including the \"is this dir inside a repo?\" question.\n */\nexport const initRepoAndCommit = (\n details: GitInitDetails,\n runner: GitRunner = defaultGitRunner,\n): GitInitOutcome => {\n const gitVersion = probeGitVersion(details.outDir, runner);\n if (gitVersion === undefined) {\n return { initialized: false, reason: \"git-not-available\" };\n }\n if (isInsideGitWorkTree(details.outDir, runner)) {\n return { initialized: false, reason: \"already-in-repo\" };\n }\n if (!hasIdentity(details.outDir, runner)) {\n return { initialized: false, reason: \"no-identity\" };\n }\n const init = initWithMainBranch(details.outDir, runner);\n if (init.code !== 0) {\n return { initialized: false, reason: \"init-failed\", message: init.message };\n }\n const add = runner.run([\"add\", \".\"], details.outDir);\n if (add.code !== 0) {\n return { initialized: false, reason: \"add-failed\", message: trim(add.stderr) };\n }\n const commit = runner.run(\n [\"commit\", \"-m\", commitMessage(details, gitVersion), \"--no-verify\"],\n details.outDir,\n );\n if (commit.code !== 0) {\n return { initialized: false, reason: \"commit-failed\", message: trim(commit.stderr) };\n }\n return { initialized: true, branch: \"main\" };\n};\n","/**\n * Interactive wizard for `create-baerly-storage`. Invoked only when the\n * process is attached to a real TTY and at least one required arg\n * (`projectName` / `target`) is missing. Non-TTY callers (CI, agents,\n * piped stdin) and `--json` callers retain the flag-driven path and\n * unchanged JSON envelope — see `index.ts`.\n *\n * API surface (`@clack/prompts` v1+): `intro`, `text`, `select`,\n * `confirm`, `outro`, `isCancel`, `cancel`. `isCancel(value)` returns\n * `true` when the user hits Ctrl+C; in that case we call `cancel()`\n * and `process.exit(1)` (same exit code as a user error).\n */\nimport { cancel, confirm, intro, isCancel, note, select, text } from \"@clack/prompts\";\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { styleText } from \"node:util\";\nimport { defaultGitRunner, type GitRunner } from \"./git.ts\";\nimport type { Addon } from \"./scaffold.ts\";\n\nconst TARGETS = [\n {\n value: \"cloudflare\",\n label: \"Cloudflare Workers\",\n hint: \"R2 + Workers, deploy via wrangler\",\n },\n {\n value: \"node\",\n label: \"Node\",\n hint: \"Any host that runs `node server.js` (Railway, Render, Fly without Docker, Heroku, a VM)\",\n },\n] as const;\n\nconst STARTERS = [\n {\n value: \"minimal\",\n label: \"Minimal\",\n hint: \"Server only — no UI framework\",\n },\n {\n value: \"react\",\n label: \"React\",\n hint: \"React + Vite SPA over a sample notes collection\",\n },\n] as const;\n\nexport interface WizardInput {\n /** When non-undefined, skip the projectName prompt and use this. */\n readonly projectName?: string;\n /** When non-undefined, skip the target prompt and use this. */\n readonly target?: \"cloudflare\" | \"node\";\n /** When non-undefined, skip the starter prompt and use this. */\n readonly starter?: \"minimal\" | \"react\";\n /**\n * When non-undefined, skip the per-add-on confirms and use this set.\n * Today only `\"docker\"` is a meaningful element (and only when\n * `target === \"node\"`).\n */\n readonly withAddons?: readonly Addon[];\n /** When non-undefined, skip the install confirm and use this. */\n readonly install?: boolean;\n /**\n * When non-undefined, skip the git-init confirm and use this. The\n * wizard also skips the prompt — defaulting to `false` — when the\n * current directory is already inside a git work tree, since\n * `create-baerly-storage` won't nest a new repo inside an existing one\n * either way.\n */\n readonly git?: boolean;\n /** Tenant pin passed through from --tenant; bolt-on mode uses it directly. */\n readonly tenant?: string;\n}\n\nexport type WizardOutput = ScaffoldWizardOutput | BoltOnWizardOutput;\n\nexport interface ScaffoldWizardOutput {\n readonly mode: \"scaffold\";\n /**\n * May be `\".\"` — the sentinel for \"scaffold into the current\n * directory\". Callers must not blindly compose this with a path\n * (e.g. `path.join(cwd, projectName)`); branch on `=== \".\"`\n * first or pass it straight through to `scaffold()`.\n */\n readonly projectName: string;\n readonly target: \"cloudflare\" | \"node\";\n readonly starter: \"minimal\" | \"react\";\n readonly withAddons: readonly Addon[];\n readonly install: boolean;\n readonly git: boolean;\n}\n\ninterface BoltOnWizardOutput {\n readonly mode: \"bolt-on\";\n readonly projectName: string;\n readonly tenant: string;\n readonly install: boolean;\n}\n\nexport const runWizard = async (\n input: WizardInput,\n opts: { readonly gitRunner?: GitRunner } = {},\n): Promise<WizardOutput> => {\n intro(styleText([\"bold\", \"cyan\"], \"create-baerly-storage\"));\n const projectName = input.projectName ?? (await promptProjectName());\n const outDir = projectName === \".\" ? process.cwd() : resolve(process.cwd(), projectName);\n const wranglerPath = resolve(outDir, \"wrangler.jsonc\");\n if (existsSync(wranglerPath)) {\n note(\"Detected existing Cloudflare Worker — bolting baerly on instead of scaffolding.\");\n const install = input.install ?? (await promptInstall());\n return {\n mode: \"bolt-on\",\n projectName,\n tenant: input.tenant ?? \"default\",\n install,\n };\n }\n const target = input.target ?? (await promptTarget());\n const starter = input.starter ?? (await promptStarter());\n // Add-on prompts are gated per-target. Today only `docker` exists\n // and only applies when `target === \"node\"`; on `cloudflare` we\n // skip the prompt and emit an empty addon list.\n let withAddons: readonly Addon[];\n if (input.withAddons !== undefined) {\n withAddons = input.withAddons;\n } else if (target === \"node\") {\n withAddons = (await promptDocker()) ? [\"docker\"] : [];\n } else {\n withAddons = [];\n }\n const install = input.install ?? (await promptInstall());\n // Skip the git prompt entirely when we're already inside a git\n // work tree — `initRepoAndCommit` would skip with `already-in-repo`\n // anyway, and asking the question would only confuse a user who\n // can't usefully answer it. `opts.gitRunner` makes this stubbable\n // for the wizard-flow tests. Pre-filled `input.git` short-circuits\n // BEFORE the spawn so pure-prompt tests don't incur the side effect.\n let git: boolean;\n if (input.git !== undefined) {\n git = input.git;\n } else {\n const gitRunner = opts.gitRunner ?? defaultGitRunner;\n const insideRepo =\n gitRunner.run([\"rev-parse\", \"--is-inside-work-tree\"], process.cwd()).stdout.trim() === \"true\";\n git = insideRepo ? false : await promptGit();\n }\n return { mode: \"scaffold\", projectName, target, starter, withAddons, install, git };\n};\n\nconst promptProjectName = async (): Promise<string> => {\n const v = await text({\n message: \"Project name (use '.' for current directory)\",\n placeholder: \"my-app\",\n // `@clack/prompts` v1 widened the `validate` callback's parameter\n // to `string | undefined`. Treat `undefined` as the empty string\n // so the existing \"non-empty\" guard fires.\n validate: (raw = \"\") => {\n if (raw.length === 0) {\n return \"name must be non-empty\";\n }\n // `\".\"` (exactly one character) is the shorthand for \"scaffold\n // into the current directory\" — `scaffold.ts` derives `appName`\n // from `basename(cwd)` and applies the same regex below to that\n // derived value.\n if (raw === \".\") {\n return undefined;\n }\n // MUST mirror the validation regex in `scaffold.ts`'s `scaffold()`.\n if (!/^[a-z0-9][a-z0-9_-]*$/.test(raw)) {\n return \"lowercase, alphanumeric + - / _, starting with [a-z0-9] (or '.' for current directory)\";\n }\n return undefined;\n },\n });\n if (isCancel(v)) {\n cancel(\"Cancelled.\");\n process.exit(1);\n }\n return v as string;\n};\n\nconst promptTarget = async (): Promise<\"cloudflare\" | \"node\"> => {\n const v = await select({\n message: \"Deploy target\",\n options: [...TARGETS],\n initialValue: \"cloudflare\",\n });\n if (isCancel(v)) {\n cancel(\"Cancelled.\");\n process.exit(1);\n }\n return v as \"cloudflare\" | \"node\";\n};\n\nconst promptStarter = async (): Promise<\"minimal\" | \"react\"> => {\n const v = await select({\n message: \"Starter template\",\n options: [...STARTERS],\n initialValue: \"minimal\",\n });\n if (isCancel(v)) {\n cancel(\"Cancelled.\");\n process.exit(1);\n }\n return v as \"minimal\" | \"react\";\n};\n\nconst promptDocker = async (): Promise<boolean> => {\n const v = await confirm({\n message: \"Add a production Dockerfile?\",\n initialValue: false,\n });\n if (isCancel(v)) {\n cancel(\"Cancelled.\");\n process.exit(1);\n }\n return v as boolean;\n};\n\nconst promptInstall = async (): Promise<boolean> => {\n const v = await confirm({ message: \"Install dependencies?\", initialValue: true });\n if (isCancel(v)) {\n cancel(\"Cancelled.\");\n process.exit(1);\n }\n return v as boolean;\n};\n\nconst promptGit = async (): Promise<boolean> => {\n const v = await confirm({\n message: \"Initialise a git repo and create the initial commit?\",\n initialValue: true,\n });\n if (isCancel(v)) {\n cancel(\"Cancelled.\");\n process.exit(1);\n }\n return v as boolean;\n};\n","/**\n * Which package manager invoked us. Read from\n * `npm_config_user_agent` — set by npm/pnpm/yarn when they run\n * their `create` shorthand. Defaults to `\"npm\"` on any parse\n * failure (most conservative — npm has the widest install base).\n */\nimport { spawnSync } from \"node:child_process\";\n\nexport type Pm = \"npm\" | \"pnpm\" | \"yarn\";\n\nexport const detectPm = (\n userAgent: string | undefined = process.env[\"npm_config_user_agent\"],\n): Pm => {\n if (userAgent === undefined) {\n return \"npm\";\n }\n // user-agent format: \"<pm>/<version> node/<v> <platform> <arch>\"\n const m = /^(npm|pnpm|yarn)\\//.exec(userAgent);\n if (m === null) {\n return \"npm\";\n }\n return m[1] as Pm;\n};\n\n/**\n * The install command for the detected PM. Used in the post-\n * scaffold \"next steps\" output.\n */\nexport const installCommand = (pm: Pm): string => {\n if (pm === \"npm\") {\n return \"npm install\";\n }\n if (pm === \"pnpm\") {\n return \"pnpm install\";\n }\n return \"yarn install\";\n};\n\n/**\n * The run-script invocation prefix. `pnpm dev` / `npm run dev` /\n * `yarn dev`. The scaffolded `package.json` scripts assume this\n * shape.\n */\nexport const runCommand = (pm: Pm, script: string): string => {\n if (pm === \"pnpm\") {\n return `pnpm ${script}`;\n }\n if (pm === \"yarn\") {\n return `yarn ${script}`;\n }\n return `npm run ${script}`;\n};\n\n/**\n * Best-effort `<pm> --version` probe. Returns the trimmed version\n * string on success, or `undefined` if the pm binary can't be\n * spawned or returns non-zero. Used by the `git init` commit-message\n * body — a missing pm version is a stylistic loss, not a hard error,\n * so callers should pass the result through unchecked.\n */\nexport const probePmVersion = (pm: Pm): string | undefined => {\n const res = spawnSync(pm, [\"--version\"], { encoding: \"utf8\" });\n if (res.error !== undefined || res.status !== 0) {\n return undefined;\n }\n const out = (res.stdout ?? \"\").trim();\n return out.length > 0 ? out : undefined;\n};\n","/**\n * Manifest-driven content rewrite for the scaffolder. Two kinds of\n * edits happen at copy time:\n *\n * 1. Sentinel rename. Each entry in `manifest.renames` is a literal\n * substring to replace, mapped to a user-supplied value via\n * `fromKey`. Sentinels are applied longest-first so a longer\n * sentinel (e.g. \"minimal-cloudflare-server\") rewrites before a\n * shorter one it contains as a prefix (\"minimal-cloudflare\").\n *\n * 2. package.json normalisation. For files named `package.json`,\n * any `workspace:*` value under a dep key matching `@gusto/baerly-storage`\n * is pinned to `^<cliVersion>` (the scaffolder + the\n * `@gusto/baerly-storage` umbrella ship at the same version), and\n * any dep in `manifest.dropDevDeps` is removed from\n * `devDependencies`. Indentation is preserved by round-tripping\n * through `JSON.parse` + `JSON.stringify(_, null, 2)`.\n *\n * Literal substring substitution is deliberate: example sentinels are\n * unusual enough (`minimal-cloudflare`, `minimal-demo`, …) not to\n * collide with unrelated content, and substring matching covers the\n * full surface of code/JSON/Markdown/Dockerfile/systemd without per-\n * extension parsing.\n */\n\ninterface ManifestRename {\n readonly from: string;\n readonly fromKey: string;\n}\n\ninterface ManifestCopy {\n readonly from: string;\n readonly to: string;\n}\n\nexport interface ScaffoldManifest {\n readonly renames: readonly ManifestRename[];\n /**\n * Paths relative to the example root that must be skipped during\n * the copy. Matched as exact relative paths (e.g.\n * `\".baerly/scaffold.json\"`).\n */\n readonly excludePaths: readonly string[];\n /**\n * Basename patterns skipped at any depth in the source tree. Each\n * entry is either a literal name (e.g. `\"node_modules\"`) or a\n * `*.<ext>` suffix glob (e.g. `\"*.tsbuildinfo\"`). Use this for\n * build artifacts / OS detritus that may exist inside the\n * example's working tree but must never land in a scaffolded app.\n */\n readonly excludeNames: readonly string[];\n readonly dropDevDeps: readonly string[];\n /**\n * Files written more than once during a single scaffold pass. Each\n * entry mirrors a source file (`from`, relative to the example\n * root) into a second destination (`to`, relative to the output\n * root) with the same `substituteText` pass applied. Lets the\n * example author declare AGENTS.md ↔ CLAUDE.md parity (and any\n * future coding-tool variant) in data, not in walker branches.\n */\n readonly copies: readonly ManifestCopy[];\n}\n\nexport interface SubstituteContext {\n readonly manifest: ScaffoldManifest;\n readonly vars: Record<string, string>;\n readonly cliVersion: string;\n}\n\n/**\n * Rewrite text content (any non-JSON-aware file). Applies sentinel\n * renames longest-first. Unknown `fromKey` values cause the rename to\n * be skipped — that's a scaffolder authoring bug, not a user error,\n * and silent empty-substitution would hide it.\n */\nexport const substituteText = (text: string, ctx: SubstituteContext): string => {\n const sorted = ctx.manifest.renames.toSorted((a, b) => b.from.length - a.from.length);\n let out = text;\n for (const r of sorted) {\n if (!Object.hasOwn(ctx.vars, r.fromKey)) {\n continue;\n }\n out = out.replaceAll(r.from, ctx.vars[r.fromKey]!);\n }\n return out;\n};\n\n/**\n * Rewrite a package.json's text content. Applies sentinel renames\n * first (covers the `\"name\"` field and any other string), then pins\n * `@gusto/baerly-storage` workspace deps to the CLI version, and drops\n * listed devDependencies.\n */\nexport const substitutePackageJson = (text: string, ctx: SubstituteContext): string => {\n const renamed = substituteText(text, ctx);\n const pkg = JSON.parse(renamed) as Record<string, unknown> & {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n };\n const pin = `^${ctx.cliVersion}`;\n for (const block of [\"dependencies\", \"devDependencies\", \"peerDependencies\"] as const) {\n const deps = pkg[block];\n if (deps === undefined) {\n continue;\n }\n for (const [name, value] of Object.entries(deps)) {\n if (value !== \"workspace:*\") {\n continue;\n }\n if (name === \"@gusto/baerly-storage\") {\n deps[name] = pin;\n }\n }\n }\n if (pkg.devDependencies !== undefined) {\n for (const drop of ctx.manifest.dropDevDeps) {\n delete pkg.devDependencies[drop];\n }\n if (Object.keys(pkg.devDependencies).length === 0) {\n delete pkg.devDependencies;\n }\n }\n return `${JSON.stringify(pkg, null, 2)}\\n`;\n};\n","import { fileURLToPath } from \"node:url\";\nimport { basename, dirname, join, resolve, sep } from \"node:path\";\nimport { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from \"node:fs\";\nimport { detectPm, installCommand, runCommand, type Pm } from \"./pm-detect.ts\";\nimport {\n type ScaffoldManifest,\n type SubstituteContext,\n substitutePackageJson,\n substituteText,\n} from \"./substitute.ts\";\n\n/**\n * Optional add-ons and compatibility tokens recognised by the CLI.\n * `docker` is a scaffold template overlay; `agent-rules` is the legacy\n * bolt-on `--with` token for the default-on agent-rules writer. Adding\n * a new entry here is what makes `--with=<name>` recognised by both the\n * flag parser and the wizard.\n *\n * - `docker` (scaffold-only, `--target=node`): copies the Dockerfile\n * add-on under `templates/addons/docker/` on top of the scaffolded\n * project.\n * - `agent-rules` (bolt-on compatibility token): the CLI now writes\n * this by default in bolt-on mode and accepts `--no-agent-rules` to\n * opt out. Scaffolded apps already ship the same guidance via the\n * per-template `AGENTS.md`.\n */\nexport const KNOWN_ADDONS = [\"docker\", \"agent-rules\"] as const;\nexport type Addon = (typeof KNOWN_ADDONS)[number];\n\nexport interface ScaffoldOptions {\n /**\n * Lowercase alphanumeric + `-` / `_`, starting with `[a-z0-9]`.\n * `\".\"` is a sentinel that scaffolds into the current `outRoot`\n * (or `process.cwd()` when `outRoot` is unset); the `appName`\n * substitution sentinel is then derived from that directory's\n * basename and must itself satisfy the same regex.\n */\n readonly projectName: string;\n readonly target: \"cloudflare\" | \"node\";\n readonly starter?: \"minimal\" | \"react\";\n readonly pm?: Pm;\n readonly tenant?: string;\n readonly domain?: string;\n /** Add-ons to layer on top of the base template. */\n readonly withAddons?: readonly Addon[];\n /** Override the templates root. Tests inject a fixture path. */\n readonly templatesRoot?: string;\n /** Override the add-ons root. Tests inject a fixture path. */\n readonly addonsRoot?: string;\n /** Override the output root. Tests inject a tmpdir. */\n readonly outRoot?: string;\n}\n\nexport interface ScaffoldResult {\n readonly outDir: string;\n readonly filesWritten: readonly string[];\n readonly nextSteps: readonly string[];\n /**\n * `create-baerly-storage`'s own `package.json:version`. Stamped into the\n * post-scaffold initial commit (when `--git` runs) so the user\n * can grep `git log` for the scaffolder version that produced\n * their repo.\n */\n readonly cliVersion: string;\n /**\n * The substitution sentinel that was applied to template literals.\n * Equals `projectName` for the named-dir form and `basename(outDir)`\n * for `create-baerly-storage .`. Surfaced on the result so the caller can\n * pass it through to the git-init commit body without re-deriving.\n */\n readonly appName: string;\n}\n\n/**\n * When `projectName === \".\"` (scaffold into the current directory),\n * a pre-existing entry whose basename is in this set is always\n * permitted — even if the scaffold also ships a file by the same\n * name (the scaffold overwrites). Other names are checked against\n * the precomputed \"would-write\" set (see `topLevelOutputs`); only\n * actual collisions fail the guard, so a pre-existing `.npmrc` /\n * `mise.toml` / `.tool-versions` (or any other top-level metadata\n * the user already wrote) coexists with the scaffold.\n */\nconst SCAFFOLD_HERE_ALLOWLIST: ReadonlySet<string> = new Set([\n \".git\",\n \".gitignore\",\n \".gitattributes\",\n \"README.md\",\n \"LICENSE\",\n \"LICENSE.md\",\n \"LICENSE.txt\",\n]);\n\n/**\n * Compute the set of top-level basenames the scaffold will emit\n * into `outDir`. Used by the `inPlace` guard to decide which\n * pre-existing entries actually collide.\n *\n * Mirrors the logic in `walk()`: applies `excludePaths` /\n * `excludeNames`, renames `_gitignore` → `.gitignore`, and folds\n * in the top-level destination of each `manifest.copies` entry.\n * Add-ons layer on top of the base template via the same walker,\n * so their top-level basenames are included here too.\n */\nconst topLevelOutputs = (\n templateDir: string,\n manifest: ScaffoldManifest,\n addonDirs: readonly string[],\n): Set<string> => {\n const excluded = new Set(manifest.excludePaths.map((p) => p.split(\"/\").join(sep)));\n const { literals: excludeLiterals, suffixes: excludeSuffixes } = splitExcludeNames(\n manifest.excludeNames,\n );\n const matchesExcludeName = (name: string): boolean => {\n if (excludeLiterals.has(name)) {\n return true;\n }\n for (const suffix of excludeSuffixes) {\n if (name.endsWith(suffix)) {\n return true;\n }\n }\n return false;\n };\n const out = new Set<string>();\n const addTopLevel = (sourceDir: string): void => {\n for (const ent of readdirSync(sourceDir)) {\n if (excluded.has(ent) || matchesExcludeName(ent)) {\n continue;\n }\n out.add(ent === \"_gitignore\" ? \".gitignore\" : ent);\n }\n };\n addTopLevel(templateDir);\n for (const addonDir of addonDirs) {\n addTopLevel(addonDir);\n }\n for (const copy of manifest.copies) {\n const dest = copy.to.split(\"/\").join(sep);\n const firstSeg = dest.split(sep)[0];\n if (firstSeg !== undefined && firstSeg.length > 0) {\n out.add(firstSeg);\n }\n }\n return out;\n};\n\nconst TEXT_EXTS = new Set([\n \".ts\",\n \".tsx\",\n \".js\",\n \".cjs\",\n \".json\",\n \".jsonc\",\n \".md\",\n \".toml\",\n \".yaml\",\n \".yml\",\n \".html\",\n \".css\",\n \".gitignore\",\n \".dockerignore\",\n \".example\",\n \".service\",\n]);\n\n/**\n * `${target}:${starter}` → example directory name (under `examples/`).\n * Default starter is `\"minimal\"`. The compound key lets us add richer\n * starters per target without renaming or duplicating maps.\n */\nconst STARTER_TO_EXAMPLE: Record<string, string> = {\n \"cloudflare:minimal\": \"minimal-cloudflare\",\n \"cloudflare:react\": \"react-cloudflare\",\n \"node:minimal\": \"minimal-node\",\n \"node:react\": \"react-node\",\n};\n\n/**\n * Resolve the templates root. In a built CLI, examples are copied\n * to `dist/templates/<name>/` so the binary is self-contained\n * (preserving today's `package.json:files` shape). In dev (running\n * straight from `src/` via Node's strip-types) the same directory\n * doesn't exist, so we fall back to `examples/` three levels up\n * (`src/ → create-baerly-storage/ → packages/ → repo-root`).\n */\nconst resolveTemplatesRoot = (): string => {\n const here = dirname(fileURLToPath(import.meta.url));\n const distSidecar = resolve(here, \"templates\");\n if (existsSync(distSidecar)) {\n return distSidecar;\n }\n return resolve(here, \"..\", \"..\", \"..\", \"examples\");\n};\n\n/**\n * Resolve the add-ons root. In a built CLI, add-on trees are copied\n * to `dist/templates/addons/<name>/` next to the example templates.\n * In dev (running from `src/` via Node's strip-types) they live at\n * `packages/create-baerly-storage/templates/addons/<name>/`, one level up\n * from `src/`.\n */\nconst resolveAddonsRoot = (): string => {\n const here = dirname(fileURLToPath(import.meta.url));\n const distSidecar = resolve(here, \"templates\", \"addons\");\n if (existsSync(distSidecar)) {\n return distSidecar;\n }\n return resolve(here, \"..\", \"templates\", \"addons\");\n};\n\n/**\n * Read the CLI's own package.json:version. Used to rewrite\n * `workspace:*` dep specs to `^X.Y.Z` at copy time, since\n * `create-baerly-storage` ships in the same release train as `@baerly/*`.\n */\nconst readCliVersion = (): string => {\n const here = dirname(fileURLToPath(import.meta.url));\n // `src/scaffold.ts` and `dist/index.js` both sit one level under the\n // package root, so `../package.json` works for both.\n const pkgPath = resolve(here, \"..\", \"package.json\");\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf8\")) as { version?: string };\n if (typeof pkg.version !== \"string\" || pkg.version.length === 0) {\n throw new Error(`create-baerly-storage: could not read version from ${pkgPath}`);\n }\n return pkg.version;\n};\n\nconst DEFAULT_MANIFEST: ScaffoldManifest = {\n renames: [],\n excludePaths: [\".baerly/scaffold.json\"],\n excludeNames: [],\n dropDevDeps: [],\n copies: [],\n};\n\nconst loadManifest = (exampleRoot: string): ScaffoldManifest => {\n const p = join(exampleRoot, \".baerly\", \"scaffold.json\");\n if (!existsSync(p)) {\n return DEFAULT_MANIFEST;\n }\n const raw = JSON.parse(readFileSync(p, \"utf8\")) as Partial<ScaffoldManifest>;\n return {\n renames: raw.renames ?? [],\n excludePaths: raw.excludePaths ?? [\".baerly/scaffold.json\"],\n excludeNames: raw.excludeNames ?? [],\n dropDevDeps: raw.dropDevDeps ?? [],\n copies: raw.copies ?? [],\n };\n};\n\n/**\n * `excludeNames` supports both literal basenames (`node_modules`)\n * and `*.<ext>` suffix globs (`*.tsbuildinfo`). Split once per\n * scaffold; the walker calls `matchesExcludeName` per entry.\n */\nconst splitExcludeNames = (\n names: readonly string[],\n): { literals: Set<string>; suffixes: string[] } => {\n const literals = new Set<string>();\n const suffixes: string[] = [];\n for (const n of names) {\n if (n.startsWith(\"*.\")) {\n suffixes.push(n.slice(1));\n } else {\n literals.add(n);\n }\n }\n return { literals, suffixes };\n};\n\n/**\n * Walk the source example tree, apply manifest-driven rewrites, and\n * write to `outRoot/<projectName>/`. Returns the absolute output\n * directory and the relative list of files written.\n *\n * Refuses to overwrite an existing non-empty directory — fails\n * fast with a thrown Error. Callers catch and translate to the\n * CLI's exit-code contract.\n */\nexport const scaffold = async (opts: ScaffoldOptions): Promise<ScaffoldResult> => {\n if (opts.projectName.length === 0) {\n throw new Error(\"create-baerly-storage: projectName must be non-empty\");\n }\n // `\".\"` (exactly one character) is the sole sentinel for \"scaffold\n // into the current directory\" — matches `npm create vite@latest`\n // and `create-next-app`. `\"./\"`, `\"./foo\"`, `\"..\"`, etc. fall\n // through to the regex check below and are rejected like any other\n // invalid name.\n const inPlace = opts.projectName === \".\";\n // MUST mirror the regex in `prompts.ts:promptProjectName`.\n if (!inPlace && !/^[a-z0-9][a-z0-9_-]*$/.test(opts.projectName)) {\n throw new Error(\n `create-baerly-storage: projectName must be lowercase, alphanumeric + \"_\"/\"-\", starting with [a-z0-9] (got ${JSON.stringify(opts.projectName)})`,\n );\n }\n const pm = opts.pm ?? detectPm();\n const tenant = opts.tenant ?? \"default\";\n const domain = opts.domain ?? \"\";\n const templatesRoot = opts.templatesRoot ?? resolveTemplatesRoot();\n const outRoot = opts.outRoot ?? process.cwd();\n const outDir = inPlace ? resolve(outRoot) : resolve(outRoot, opts.projectName);\n // When scaffolding into the current directory, derive the\n // substitution sentinel (`appName`) from the directory's basename\n // and re-run it through the same regex — the value lands in\n // `package.json:name`, `wrangler.jsonc`, etc., which all require\n // an npm-package-shaped slug.\n const appName = inPlace ? basename(outDir) : opts.projectName;\n if (inPlace && !/^[a-z0-9][a-z0-9_-]*$/.test(appName)) {\n throw new Error(\n `create-baerly-storage: appName must be lowercase, alphanumeric + \"_\"/\"-\", starting with [a-z0-9] (got ${JSON.stringify(appName)}) — derived from current directory ${JSON.stringify(outDir)}`,\n );\n }\n const starter = opts.starter ?? \"minimal\";\n const lookupKey = `${opts.target}:${starter}`;\n const exampleName = STARTER_TO_EXAMPLE[lookupKey];\n const templateDir = exampleName === undefined ? \"\" : join(templatesRoot, exampleName);\n if (exampleName === undefined || !existsSync(templateDir)) {\n throw new Error(\n `create-baerly-storage: template not found for target=${opts.target} starter=${starter}`,\n );\n }\n\n const manifest = loadManifest(templateDir);\n\n // Resolve add-on directories up-front so the in-place collision\n // check below can see their top-level outputs too, and so an\n // unknown add-on fails fast before we start writing files.\n const addons = opts.withAddons ?? [];\n const addonsRoot = addons.length > 0 ? (opts.addonsRoot ?? resolveAddonsRoot()) : \"\";\n const addonDirs: string[] = [];\n for (const addon of addons) {\n const addonDir = join(addonsRoot, addon);\n if (!existsSync(addonDir)) {\n throw new Error(\n `create-baerly-storage: add-on directory not found: ${addonDir} (addon=${addon})`,\n );\n }\n addonDirs.push(addonDir);\n }\n\n if (existsSync(outDir)) {\n const entries = readdirSync(outDir);\n if (inPlace) {\n // Allow pre-existing files that don't collide with the scaffold:\n // a user's `.npmrc`, `mise.toml`, `.tool-versions`, etc. should\n // survive untouched. The allowlist (`.git`, `README.md`, …) is a\n // strict superset — those names are permitted even when the\n // scaffold also ships them (the scaffold overwrites).\n const wouldWrite = topLevelOutputs(templateDir, manifest, addonDirs);\n const colliding = entries.filter((e) => !SCAFFOLD_HERE_ALLOWLIST.has(e) && wouldWrite.has(e));\n if (colliding.length > 0) {\n throw new Error(\n `create-baerly-storage: ${outDir} contains files that would be overwritten: ${colliding.join(\", \")}. ` +\n `Move or remove these, then re-run.`,\n );\n }\n } else if (entries.length > 0) {\n throw new Error(`create-baerly-storage: ${outDir} exists and is non-empty`);\n }\n }\n\n const vars: Record<string, string> = {\n appName,\n tenant,\n domain,\n pm,\n installCmd: installCommand(pm),\n runDev: runCommand(pm, \"dev\"),\n runTypecheck: runCommand(pm, \"typecheck\"),\n };\n const ctx: SubstituteContext = { manifest, vars, cliVersion: readCliVersion() };\n\n const excluded = new Set(manifest.excludePaths.map((p) => p.split(\"/\").join(sep)));\n const isExcluded = (rel: string): boolean => excluded.has(rel);\n const { literals: excludeLiterals, suffixes: excludeSuffixes } = splitExcludeNames(\n manifest.excludeNames,\n );\n const matchesExcludeName = (name: string): boolean => {\n if (excludeLiterals.has(name)) {\n return true;\n }\n for (const suffix of excludeSuffixes) {\n if (name.endsWith(suffix)) {\n return true;\n }\n }\n return false;\n };\n\n const copyByFrom = new Map<string, string>(\n manifest.copies.map((c) => [c.from.split(\"/\").join(sep), c.to.split(\"/\").join(sep)]),\n );\n\n const filesWritten: string[] = [];\n const walk = (sourceDir: string, rel: string): void => {\n const from = join(sourceDir, rel);\n for (const ent of readdirSync(from)) {\n const fromEnt = join(from, ent);\n const relEnt = rel === \"\" ? ent : join(rel, ent);\n if (isExcluded(relEnt) || matchesExcludeName(ent)) {\n continue;\n }\n // `npm pack` strips `.gitignore` files from published tarballs\n // (it reads each one as an ignore-source control file and then\n // drops the file itself), so template trees ship `_gitignore`\n // and we rename on emit. Same trick as create-vite. Output\n // file name lives in `outName` / `relOut`; the source name\n // (`ent` / `relEnt`) is unchanged for read + manifest lookup.\n const outName = ent === \"_gitignore\" ? \".gitignore\" : ent;\n const relOut = rel === \"\" ? outName : join(rel, outName);\n const toEnt = join(outDir, relOut);\n if (statSync(fromEnt).isDirectory()) {\n mkdirSync(toEnt, { recursive: true });\n walk(sourceDir, relEnt);\n } else {\n const ext = ent.includes(\".\") ? ent.slice(ent.lastIndexOf(\".\")) : \"\";\n const isText = TEXT_EXTS.has(ext) || ent === \"Dockerfile\" || ent === \"_gitignore\";\n mkdirSync(dirname(toEnt), { recursive: true });\n if (ent === \"package.json\") {\n writeFileSync(toEnt, substitutePackageJson(readFileSync(fromEnt, \"utf8\"), ctx));\n } else if (isText) {\n writeFileSync(toEnt, substituteText(readFileSync(fromEnt, \"utf8\"), ctx));\n } else {\n writeFileSync(toEnt, readFileSync(fromEnt));\n }\n filesWritten.push(relOut);\n const copyTo = copyByFrom.get(relEnt);\n if (copyTo !== undefined) {\n const copyDest = join(outDir, copyTo);\n mkdirSync(dirname(copyDest), { recursive: true });\n writeFileSync(copyDest, substituteText(readFileSync(fromEnt, \"utf8\"), ctx));\n filesWritten.push(copyTo);\n }\n }\n }\n };\n walk(templateDir, \"\");\n\n // Layer requested add-ons on top of the base scaffold. Each add-on\n // directory was already resolved + existence-checked above so the\n // in-place collision guard could see its top-level outputs; here we\n // just walk them through the same substituter pass as the base\n // template (reusing the host's manifest so the appName sentinel\n // rewrite picks up any literal in the add-on files too).\n for (const addonDir of addonDirs) {\n walk(addonDir, \"\");\n }\n\n // When scaffolding into the current directory the user is already\n // sitting in `outDir`, so the `cd <projectName>` step would be a\n // no-op confusion. Drop it.\n const nextSteps = inPlace\n ? [installCommand(pm), runCommand(pm, \"dev\")]\n : [`cd ${opts.projectName}`, installCommand(pm), runCommand(pm, \"dev\")];\n return { outDir, filesWritten, nextSteps, cliVersion: ctx.cliVersion, appName };\n};\n","/**\n * Discriminator for {@link BaerlyError}. Strings (not subclasses) so they\n * survive cross-realm boundaries (e.g. a Web Worker) and so callers can\n * pattern-match with grep-friendly equality.\n */\nexport type BaerlyErrorCode =\n /** Caller-provided config or input is invalid (bad bucket, unsupported credential type, malformed URL, bucket not version-enabled when versioning was requested, a write whose document would encode to more than `MAX_DOCUMENT_BYTES` = 1 MiB). HTTP maps this code to 400. */\n | \"InvalidConfig\"\n /** Generic S3/HTTP transport failure (5xx, unexpected status, retries exhausted). */\n | \"NetworkError\"\n /** S3 returned 403. Either credentials are wrong or the bucket policy denies the operation. */\n | \"AccessDenied\"\n /** Server returned data that didn't parse (malformed XML, non-JSON body where JSON expected). */\n | \"InvalidResponse\"\n /** Internal invariant violation — should not be reachable. File a bug. */\n | \"Internal\"\n /**\n * Document body failed schema validation. Emitted by the table-API\n * write verbs (`Collection.insert`, `Query.update`, `Collection.replace`) when\n * the body is not valid JSON or contains an array where\n * `DocumentValue` is required; also emitted when a collection has a\n * declared `SchemaValidator` (via `Db.create({ collections })`) and\n * the bound schema rejects the doc. In the schema-rejection case the\n * error carries an `issues` array describing each failure. HTTP layer\n * maps this to 400.\n */\n | \"SchemaError\"\n /**\n * Another write won a race this call needed to win, and the losing commit\n * did not land. Re-read, then retry; `retriable` is `true`. Each\n * `Collection` / `Query` verb re-reads on every call, so re-issuing the same\n * call is the retry. The writer makes one commit attempt and resolves a\n * log-create race inside it, so this surfaces from a write only for a\n * rejected precondition the writer does not resolve. Maintenance passes\n * (`compact`, `runGc`, log retirement) raise it when a concurrent pass or\n * writer moved `current.json` first; the next pass retries. HTTP maps this\n * code to 409 with a generic message.\n *\n * `Storage` implementations throw this code for every rejected\n * precondition: a stale `ifMatch`, an `ifMatch` against a missing key, or\n * an `ifNoneMatch: \"*\"` create over an existing key. For a create-only put\n * that followed an attempt of unknown outcome, the occupant may be this\n * call's own earlier write. Callers that care read the key back.\n */\n | \"WriteConflict\"\n /**\n * The thing being created already exists, so the same request can never\n * succeed; `retriable` is `false`. `Collection.insert` raises it when a\n * live row already holds the `_id`, including one a concurrent insert\n * committed first: of concurrent inserts of one `_id`, at most one\n * commits and the others raise this. Insert under a different `_id`,\n * omit `_id` to mint one, or change the stored row with `update` /\n * `replace` — unless this follows a same-`_id` retry after\n * `AmbiguousCommit`, where the stored row may be the first attempt:\n * re-read it instead of inserting under a new `_id`.\n * `baerly admin restore` raises it when the target collection already\n * exists and `--force` was not passed. HTTP maps this code to 409 and\n * keeps the message, which names the id and collection.\n */\n | \"AlreadyExists\"\n /**\n * A write's commit outcome cannot be resolved: one or more committing\n * `log/<seq>` creates may already be durable, but the writer cannot adopt or\n * report a confirmed commit. This includes an unresolved create acknowledgement\n * after the occupant readback, and a create that landed below the\n * certified delete floor (`seq < min(log_delete_floor, log_seq_start)`).\n *\n * `BaerlyError._id` names the affected row, including an auto-ID insert's\n * minted id. Re-read that row and compare it with the intended state before\n * deciding what to do. A matching row helps reconcile the outcome; absence\n * does not prove that a create failed, since a send may still complete or its\n * effect may have been superseded. Retrying is an explicit at-least-once\n * choice and may repeat logical work. Retry an insert with the same `_id`:\n * a second create then targets the same row instead of minting a second\n * document, and commits only if no live row holds that `_id`. An\n * `AlreadyExists` on that retry means a row with that `_id` is committed:\n * re-read it and compare with the intended state rather than inserting\n * under a new `_id`. `retriable` is `false` so generic retry wrappers do\n * not repeat the operation silently. HTTP maps this code to 409.\n */\n | \"AmbiguousCommit\"\n /**\n * The work this request needs is more than the host serving it does in\n * one request, so the request was refused whole; `retriable` is `false`.\n * The refusal is decided per request from the collection's current\n * state and clears by itself once that state changes. Reads and writes\n * both raise it.\n *\n * A refused write commits nothing; a batch refused part-way (a\n * concurrent write filled the room between its check and a row's\n * commit) keeps the rows it already committed. Near the limit only\n * growth is refused (an insert, or an update that makes a row larger):\n * deletes and same-size or shrinking updates still commit, and once\n * maintenance absorbs them, growth is accepted again. When the\n * collection is already more than this host can maintain (for example\n * one grown on a larger host and now served by a smaller one), every\n * write is refused until the collection moves to a larger host or is\n * exported with `baerly admin dump`. Moving hosts is a deployment\n * decision, not an app setting.\n *\n * A refused read returns no rows, never a truncated answer, and writes\n * nothing. Its `resolution` names the remedy for the bound it hit:\n * narrow the predicate or add a limit when the answer is too wide;\n * delete or shrink rows when the collection is too large to read in one\n * request; or retry once maintenance has absorbed pending writes. HTTP\n * maps this code to 409 and keeps the message, which names the\n * collection and the case.\n */\n | \"CapacityExceeded\"\n /**\n * Background maintenance is behind on this collection, so this write was\n * refused and not committed (a batch refused part-way keeps the rows it\n * already committed); `retriable` is `true`. The refusal\n * clears by itself once maintenance catches up. {@link BaerlyError.retryAfter}\n * carries the suggested delay in seconds; wait that long, then repeat the\n * call. HTTP maps this code to 503 with a `Retry-After` header and keeps\n * the message.\n */\n | \"MaintenancePending\"\n /**\n * A `/v1/since` cursor can no longer resume, so the long-poll was\n * refused; `retriable` is `false`, because the same cursor never\n * succeeds again. Either the changes after it are no longer retained\n * (maintenance retired them), or it was minted in a generation that\n * `baerly admin restore --force` has since truncated. Re-read the rows\n * the subscriber shows, then resume with `cursor: \"\"`: the changes\n * between the dead cursor and the restart are not replayed. A\n * malformed cursor is `SchemaError` instead. HTTP maps this code to 410\n * and keeps the message.\n */\n | \"CursorExpired\"\n /**\n * `Verifier` returned no identity. HTTP server maps to 401.\n * Code is reserved here so the union locks.\n */\n | \"Unauthorized\"\n /**\n * The addressed resource does not exist. HTTP server maps to 404.\n * Emitted by the row-by-id read / update / delete handlers in\n * `packages/server/src/http/router.ts` when the predicate\n * `{ _id }` matches zero rows. Not a protocol invariant —\n * callers may retry after creating the resource or treat as a\n * miss depending on intent. The CLI maps this to the generic\n * exit-2 \"storage error\" bucket, not the exit-3 \"protocol\n * invariant\" bucket.\n */\n | \"NotFound\"\n /**\n * Request body exceeded the server's size cap. HTTP server maps\n * to 413. Cap is `MAX_BODY_BYTES` (1 MiB today; exported from\n * `packages/server/src/http/router.ts`). The router counts bytes\n * while it reads a chunked body and stops at the cap on every\n * host; the Node adapter also enforces it during the `node:http`\n * stream pump and drains the rest of the upload.\n */\n | \"PayloadTooLarge\"\n /**\n * A body-bearing HTTP route (`POST`, `PATCH`, `PUT`) got a request\n * whose `Content-Type` is missing or is not `application/json` or a\n * `+json` type. HTTP server maps to 415 and refuses before reading\n * the body. Parameters such as `charset` are allowed. The JSON-only\n * rule is the CSRF defense for ambient auth: a `text/plain` or\n * form-encoded POST is a CORS-simple request another origin can send.\n */\n | \"UnsupportedMediaType\"\n /**\n * A predicate is structurally well-formed but contradicts itself —\n * no document can match. Emitted by `validateWire` and\n * `mergePredicateWires`. Triggers:\n * - `{ clauses: [{op:\"in\", field:\"priority\", value:[]}] }` (empty `in` set)\n * - an `eq` clause with a value outside the residual interval\n * established by range clauses on the same field\n * - merging `{op:\"gt\", value:10}` with `{op:\"lt\", value:5}` on the\n * same field (empty interval)\n * - merging two `in` clauses on the same field with empty intersection\n *\n * Conflicting equality across clauses (`eq:\"open\"` + `eq:\"closed\"` on\n * the same field) surfaces as `InvalidConfig` rather than this code —\n * the merger treats it as a caller-side configuration bug, not an\n * algebraic contradiction.\n *\n * The HTTP layer treats this as a 400 (caller error). The distinct\n * code lets downstream code short-circuit empty-by-construction\n * without re-running the validator or parsing messages.\n */\n | \"UnsatisfiablePredicate\"\n /**\n * A `useQuery` callback awaited a recorder terminal\n * (`.get`/`.first`/`.all`/`.count`). The recorder runs once per\n * render to capture the chain shape; it cannot survive an `await`\n * because the proxy doesn't proxy across microtask boundaries. The\n * recorder's terminal returns a thenable whose `.then` throws this\n * error synchronously, converting what would otherwise be a silent\n * spinner-hang into a render-time error the hook surfaces as\n * `status: \"error\"`. Companion `baerly/no-await-in-use-query` lint\n * flags the pattern at edit time. For compound reads, use\n * `Promise.all` (parallel) or compose two `useQuery` calls with\n * `useQuery.skip` (dependent).\n */\n | \"UseQueryAwaitedRecorder\"\n /**\n * A write method (`.insert`/`.update`/`.replace`/`.delete`) was\n * called on the recorder inside a `useQuery` callback. Writes\n * inside reads are a programming error; the recorder rejects them\n * synchronously from the discovery pass, before any I/O fires. Use\n * `useMutation()` instead.\n */\n | \"UnexpectedWriteInQuery\"\n /**\n * A `useMutation()` callback rejected with a non-`BaerlyError`\n * throwable. The hook wraps the original throw under this code so\n * the `error` slot is always a `BaerlyError`; the original value\n * is preserved on `.cause`.\n */\n | \"MutationFailed\";\n\n/**\n * Runtime enumeration of every {@link BaerlyErrorCode}. The spec\n * generator and the drift gate iterate this to assert the IR lists\n * each code; the type guard in `spec/ir-schema.test.ts` fails tsc if\n * this tuple and the union diverge. Keep order stable for deterministic\n * artifact diffs. This is the canonical code list — do not re-list\n * codes elsewhere (see RETRIABLE_CODES, the sibling retriable subset).\n */\nexport const ERROR_CODES = [\n \"InvalidConfig\",\n \"NetworkError\",\n \"AccessDenied\",\n \"InvalidResponse\",\n \"Internal\",\n \"SchemaError\",\n \"WriteConflict\",\n \"AlreadyExists\",\n \"AmbiguousCommit\",\n \"CapacityExceeded\",\n \"MaintenancePending\",\n \"Unauthorized\",\n \"NotFound\",\n \"PayloadTooLarge\",\n \"UnsupportedMediaType\",\n \"UnsatisfiablePredicate\",\n \"CursorExpired\",\n \"UseQueryAwaitedRecorder\",\n \"UnexpectedWriteInQuery\",\n \"MutationFailed\",\n] as const satisfies readonly BaerlyErrorCode[];\n\n// Exhaustiveness guard: every union member must appear in ERROR_CODES.\n// If a code is added to BaerlyErrorCode without a tuple entry, this\n// errors at tsc time (the union is not assignable to the tuple's union).\ntype _ErrorCodesExhaustive = [BaerlyErrorCode] extends [(typeof ERROR_CODES)[number]]\n ? true\n : [\"missing code in ERROR_CODES\", Exclude<BaerlyErrorCode, (typeof ERROR_CODES)[number]>];\n// eslint-disable-next-line no-underscore-dangle\nconst _errorCodesExhaustive: _ErrorCodesExhaustive = true;\nvoid _errorCodesExhaustive;\n\n/**\n * Codes whose failure can clear on retry. `BaerlyError.retriable` is\n * exactly membership in this set; there are no per-instance overrides.\n */\nexport const RETRIABLE_CODES: ReadonlySet<BaerlyErrorCode> = new Set<BaerlyErrorCode>([\n \"NetworkError\",\n \"WriteConflict\",\n \"MaintenancePending\",\n]);\n\n/**\n * True iff `value` is a code this build knows. Wire decoders use it to\n * catch a code minted by a newer server before it reaches `code`, where\n * an unknown string would defeat both exhaustive switches and\n * {@link isRetriableCode}.\n */\nexport const isBaerlyErrorCode = (value: unknown): value is BaerlyErrorCode =>\n typeof value === \"string\" && (ERROR_CODES as readonly string[]).includes(value);\n\n/**\n * True iff `err` is a `WriteConflict`: a lost conditional write or CAS\n * race. The one predicate every kernel catch site uses, so the code's\n * meaning is tested in one place. Matches on `name` and `code` rather\n * than `instanceof`, so an error from a second loaded copy of this module\n * or another realm still classifies.\n */\nexport const isWriteConflict = (\n err: unknown,\n): err is BaerlyError & { readonly code: \"WriteConflict\" } =>\n typeof err === \"object\" &&\n err !== null &&\n (err as { readonly name?: unknown }).name === \"BaerlyError\" &&\n (err as { readonly code?: unknown }).code === \"WriteConflict\";\n\n/** True iff this error code is retriable (membership in {@link RETRIABLE_CODES}). */\nexport const isRetriableCode = (code: BaerlyErrorCode): boolean => RETRIABLE_CODES.has(code);\n\n/**\n * Codes raised only inside the client-side React runtime\n * (`useQuery` / `useMutation`); they never travel the HTTP wire, so the\n * machine-contract IR reports `httpStatus: null` for them — distinct\n * from a real `500` (a server-side transport/internal failure the HTTP\n * layer maps to a status). Sibling of {@link RETRIABLE_CODES}; add a\n * code here when a new client-only failure mode joins the union.\n */\nexport const CLIENT_RUNTIME_CODES: ReadonlySet<BaerlyErrorCode> = new Set<BaerlyErrorCode>([\n \"UseQueryAwaitedRecorder\",\n \"UnexpectedWriteInQuery\",\n \"MutationFailed\",\n]);\n\n/**\n * Optional fields for {@link BaerlyError}, the third constructor argument.\n * Each field lands on the same-named property of the error; an omitted\n * field leaves that property `undefined`.\n */\nexport interface BaerlyErrorOptions {\n /**\n * The underlying throwable, or a structured detail object. Kept on\n * `error.cause`. A `Storage` adapter reports `cause.notApplied` /\n * `cause.throttled` this way; see the `Storage.put` contract.\n */\n readonly cause?: unknown;\n /** Field-path issues; set only with `code: \"SchemaError\"`. Lands on {@link BaerlyError.issues}. */\n readonly issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>;\n /** Raw HTTP status; set only by the client-side wire decoder. Lands on {@link BaerlyError.status}. */\n readonly status?: number;\n /** Canonical corrective action. Lands on {@link BaerlyError.resolution}. */\n readonly resolution?: string;\n /** The affected row's `_id`; set only with `code: \"AmbiguousCommit\"`. Lands on {@link BaerlyError._id}. */\n readonly _id?: string;\n /** Suggested delay in seconds before retrying; set only with `code: \"MaintenancePending\"`. Lands on {@link BaerlyError.retryAfter}. */\n readonly retryAfter?: number;\n /**\n * Never set. This object is not an `Error`: `Error` requires `message`, so\n * this field makes `new BaerlyError(code, msg, err)` fail to compile. To\n * chain an error, pass `{ cause: err }`.\n */\n readonly message?: never;\n}\n\n/**\n * The single error class thrown by baerly-storage. Discriminate by `code`, not\n * `instanceof`: the code string survives `JSON.stringify` round-trips\n * across Worker / iframe / postMessage realm boundaries, where each\n * realm has its own `BaerlyError` constructor identity. IDB-restored\n * writes can replay across realms, so `instanceof` would spuriously\n * fail on a structurally-identical error from another realm.\n *\n * @example\n * ```ts\n * try {\n * await db.collection(\"tickets\").insert({ _id: \"t-1\", title: \"hi\" });\n * } catch (err) {\n * if (!(err instanceof BaerlyError)) throw err;\n * if (err.code === \"AlreadyExists\") {\n * // t-1 is taken; retrying cannot succeed.\n * } else if (err.code === \"AmbiguousCommit\") {\n * // May have landed: re-read err._id before deciding.\n * } else if (err.retriable) {\n * // WriteConflict or NetworkError: retry with bounded backoff.\n * } else {\n * throw err;\n * }\n * }\n * ```\n */\nexport class BaerlyError extends Error {\n readonly code: BaerlyErrorCode;\n override readonly cause?: unknown;\n /**\n * Structured field-path issues, set only when `code === \"SchemaError\"`.\n * Each entry's `path` is a dotted-key list (e.g. `[\"assignee\", \"team\"]`\n * or `[\"items\", 3, \"qty\"]`) that targets the offending field on the\n * input document. `message` is the validator-emitted human string.\n *\n * The HTTP layer's `mapError` renders these into the 400 body via\n * the existing `HttpErrorEnvelope`; older callers that don't know\n * about `issues` see a plain message-only error and stay correct.\n */\n readonly issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>;\n /**\n * The `_id` of the row whose commit outcome is unknown, set only when\n * `code === \"AmbiguousCommit\"`. For an auto-ID insert it is the minted\n * id, so the caller can re-read the row and retry with the same `_id`\n * rather than mint a second document. A missing row does not prove the\n * write failed. The HTTP layer carries it in `HttpErrorEnvelope`.\n */\n readonly _id?: string;\n /**\n * Raw HTTP status, set only by the client-side wire decoder when\n * inflating an `HttpErrorEnvelope` into this class. Server-side\n * throws never set it (the HTTP layer's `mapError` derives the\n * outbound status from `code`). Useful for diagnostics — e.g. to\n * distinguish 404-as-\"no such row\" from 404-as-\"route not found\".\n * Discriminate by `code` for behavior; reach for `status` only when\n * you genuinely need the wire value.\n */\n readonly status?: number;\n /** Canonical corrective action; crosses the wire via `HttpErrorEnvelope.error.resolution`. */\n readonly resolution?: string;\n /** Suggested delay in seconds before retrying; set only for `MaintenancePending`. Crosses the wire via `HttpErrorEnvelope.error.retryAfter` and the `Retry-After` header. */\n readonly retryAfter?: number;\n\n /**\n * `true` iff re-running the operation from its read step can succeed:\n * `NetworkError` (retry with backoff) and `WriteConflict` (re-read, then\n * write again). A `Collection` / `Query` verb re-reads on every call, so\n * calling it again is the retry; a blind resend of the same conditional\n * `Storage` put loses again. A pure function of `code`\n * ({@link isRetriableCode}): every instance of a code gives the same\n * answer. `AmbiguousCommit` is `false` because the write may have landed;\n * reconcile by `_id` first.\n */\n get retriable(): boolean {\n return isRetriableCode(this.code);\n }\n\n /**\n * `code` and `message` are positional; everything else goes in `options`,\n * as with `new Error(message, { cause })`. Passing an `Error` (or any\n * non-options value) as the third argument does not compile; the\n * options object is where `cause` goes.\n *\n * @example\n * ```ts\n * throw new BaerlyError(\"NetworkError\", \"PUT failed\", { cause: err });\n * throw new BaerlyError(\"AmbiguousCommit\", \"commit outcome unknown\", { _id: \"t-1\" });\n * ```\n */\n constructor(code: BaerlyErrorCode, message: string, options?: BaerlyErrorOptions) {\n super(message);\n this.name = \"BaerlyError\";\n this.code = code;\n this.cause = options?.cause;\n const { issues, status, resolution, _id, retryAfter } = options ?? {};\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (issues !== undefined) {\n this.issues = issues;\n }\n // Stryker disable next-line ConditionalExpression: same rationale as `issues` above\n if (status !== undefined) {\n this.status = status;\n }\n // Stryker disable next-line ConditionalExpression: same rationale as `issues` above\n if (resolution !== undefined) {\n this.resolution = resolution;\n }\n // Stryker disable next-line ConditionalExpression: same rationale as `issues` above\n if (_id !== undefined) {\n this._id = _id;\n }\n // Stryker disable next-line ConditionalExpression: same rationale as `issues` above\n if (retryAfter !== undefined) {\n this.retryAfter = retryAfter;\n }\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport function createScanner(text, ignoreTrivia = false) {\n const len = text.length;\n let pos = 0, value = '', tokenOffset = 0, token = 16 /* SyntaxKind.Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* ScanError.None */;\n function scanHexDigits(count, exact) {\n let digits = 0;\n let value = 0;\n while (digits < count || !exact) {\n let ch = text.charCodeAt(pos);\n if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) {\n value = value * 16 + ch - 48 /* CharacterCodes._0 */;\n }\n else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) {\n value = value * 16 + ch - 65 /* CharacterCodes.A */ + 10;\n }\n else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) {\n value = value * 16 + ch - 97 /* CharacterCodes.a */ + 10;\n }\n else {\n break;\n }\n pos++;\n digits++;\n }\n if (digits < count) {\n value = -1;\n }\n return value;\n }\n function setPosition(newPosition) {\n pos = newPosition;\n value = '';\n tokenOffset = 0;\n token = 16 /* SyntaxKind.Unknown */;\n scanError = 0 /* ScanError.None */;\n }\n function scanNumber() {\n let start = pos;\n if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) {\n pos++;\n }\n else {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) {\n pos++;\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n return text.substring(start, pos);\n }\n }\n let end = pos;\n if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) {\n pos++;\n if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) {\n pos++;\n }\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n end = pos;\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n }\n }\n return text.substring(start, end);\n }\n function scanString() {\n let result = '', start = pos;\n while (true) {\n if (pos >= len) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch = text.charCodeAt(pos);\n if (ch === 34 /* CharacterCodes.doubleQuote */) {\n result += text.substring(start, pos);\n pos++;\n break;\n }\n if (ch === 92 /* CharacterCodes.backslash */) {\n result += text.substring(start, pos);\n pos++;\n if (pos >= len) {\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch2 = text.charCodeAt(pos++);\n switch (ch2) {\n case 34 /* CharacterCodes.doubleQuote */:\n result += '\\\"';\n break;\n case 92 /* CharacterCodes.backslash */:\n result += '\\\\';\n break;\n case 47 /* CharacterCodes.slash */:\n result += '/';\n break;\n case 98 /* CharacterCodes.b */:\n result += '\\b';\n break;\n case 102 /* CharacterCodes.f */:\n result += '\\f';\n break;\n case 110 /* CharacterCodes.n */:\n result += '\\n';\n break;\n case 114 /* CharacterCodes.r */:\n result += '\\r';\n break;\n case 116 /* CharacterCodes.t */:\n result += '\\t';\n break;\n case 117 /* CharacterCodes.u */:\n const ch3 = scanHexDigits(4, true);\n if (ch3 >= 0) {\n result += String.fromCharCode(ch3);\n }\n else {\n scanError = 4 /* ScanError.InvalidUnicode */;\n }\n break;\n default:\n scanError = 5 /* ScanError.InvalidEscapeCharacter */;\n }\n start = pos;\n continue;\n }\n if (ch >= 0 && ch <= 0x1f) {\n if (isLineBreak(ch)) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n else {\n scanError = 6 /* ScanError.InvalidCharacter */;\n // mark as error but continue with string\n }\n }\n pos++;\n }\n return result;\n }\n function scanNext() {\n value = '';\n scanError = 0 /* ScanError.None */;\n tokenOffset = pos;\n lineStartOffset = lineNumber;\n prevTokenLineStartOffset = tokenLineStartOffset;\n if (pos >= len) {\n // at the end\n tokenOffset = len;\n return token = 17 /* SyntaxKind.EOF */;\n }\n let code = text.charCodeAt(pos);\n // trivia: whitespace\n if (isWhiteSpace(code)) {\n do {\n pos++;\n value += String.fromCharCode(code);\n code = text.charCodeAt(pos);\n } while (isWhiteSpace(code));\n return token = 15 /* SyntaxKind.Trivia */;\n }\n // trivia: newlines\n if (isLineBreak(code)) {\n pos++;\n value += String.fromCharCode(code);\n if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n value += '\\n';\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n return token = 14 /* SyntaxKind.LineBreakTrivia */;\n }\n switch (code) {\n // tokens: []{}:,\n case 123 /* CharacterCodes.openBrace */:\n pos++;\n return token = 1 /* SyntaxKind.OpenBraceToken */;\n case 125 /* CharacterCodes.closeBrace */:\n pos++;\n return token = 2 /* SyntaxKind.CloseBraceToken */;\n case 91 /* CharacterCodes.openBracket */:\n pos++;\n return token = 3 /* SyntaxKind.OpenBracketToken */;\n case 93 /* CharacterCodes.closeBracket */:\n pos++;\n return token = 4 /* SyntaxKind.CloseBracketToken */;\n case 58 /* CharacterCodes.colon */:\n pos++;\n return token = 6 /* SyntaxKind.ColonToken */;\n case 44 /* CharacterCodes.comma */:\n pos++;\n return token = 5 /* SyntaxKind.CommaToken */;\n // strings\n case 34 /* CharacterCodes.doubleQuote */:\n pos++;\n value = scanString();\n return token = 10 /* SyntaxKind.StringLiteral */;\n // comments\n case 47 /* CharacterCodes.slash */:\n const start = pos - 1;\n // Single-line comment\n if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n while (pos < len) {\n if (isLineBreak(text.charCodeAt(pos))) {\n break;\n }\n pos++;\n }\n value = text.substring(start, pos);\n return token = 12 /* SyntaxKind.LineCommentTrivia */;\n }\n // Multi-line comment\n if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) {\n pos += 2;\n const safeLength = len - 1; // For lookahead.\n let commentClosed = false;\n while (pos < safeLength) {\n const ch = text.charCodeAt(pos);\n if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n commentClosed = true;\n break;\n }\n pos++;\n if (isLineBreak(ch)) {\n if (ch === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n }\n }\n if (!commentClosed) {\n pos++;\n scanError = 1 /* ScanError.UnexpectedEndOfComment */;\n }\n value = text.substring(start, pos);\n return token = 13 /* SyntaxKind.BlockCommentTrivia */;\n }\n // just a single slash\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n // numbers\n case 45 /* CharacterCodes.minus */:\n value += String.fromCharCode(code);\n pos++;\n if (pos === len || !isDigit(text.charCodeAt(pos))) {\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // found a minus, followed by a number so\n // we fall through to proceed with scanning\n // numbers\n case 48 /* CharacterCodes._0 */:\n case 49 /* CharacterCodes._1 */:\n case 50 /* CharacterCodes._2 */:\n case 51 /* CharacterCodes._3 */:\n case 52 /* CharacterCodes._4 */:\n case 53 /* CharacterCodes._5 */:\n case 54 /* CharacterCodes._6 */:\n case 55 /* CharacterCodes._7 */:\n case 56 /* CharacterCodes._8 */:\n case 57 /* CharacterCodes._9 */:\n value += scanNumber();\n return token = 11 /* SyntaxKind.NumericLiteral */;\n // literals and unknown symbols\n default:\n // is a literal? Read the full word.\n while (pos < len && isUnknownContentCharacter(code)) {\n pos++;\n code = text.charCodeAt(pos);\n }\n if (tokenOffset !== pos) {\n value = text.substring(tokenOffset, pos);\n // keywords: true, false, null\n switch (value) {\n case 'true': return token = 8 /* SyntaxKind.TrueKeyword */;\n case 'false': return token = 9 /* SyntaxKind.FalseKeyword */;\n case 'null': return token = 7 /* SyntaxKind.NullKeyword */;\n }\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // some\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n }\n }\n function isUnknownContentCharacter(code) {\n if (isWhiteSpace(code) || isLineBreak(code)) {\n return false;\n }\n switch (code) {\n case 125 /* CharacterCodes.closeBrace */:\n case 93 /* CharacterCodes.closeBracket */:\n case 123 /* CharacterCodes.openBrace */:\n case 91 /* CharacterCodes.openBracket */:\n case 34 /* CharacterCodes.doubleQuote */:\n case 58 /* CharacterCodes.colon */:\n case 44 /* CharacterCodes.comma */:\n case 47 /* CharacterCodes.slash */:\n return false;\n }\n return true;\n }\n function scanNextNonTrivia() {\n let result;\n do {\n result = scanNext();\n } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */);\n return result;\n }\n return {\n setPosition: setPosition,\n getPosition: () => pos,\n scan: ignoreTrivia ? scanNextNonTrivia : scanNext,\n getToken: () => token,\n getTokenValue: () => value,\n getTokenOffset: () => tokenOffset,\n getTokenLength: () => pos - tokenOffset,\n getTokenStartLine: () => lineStartOffset,\n getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,\n getTokenError: () => scanError,\n };\n}\nfunction isWhiteSpace(ch) {\n return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */;\n}\nfunction isLineBreak(ch) {\n return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */;\n}\nfunction isDigit(ch) {\n return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */;\n}\nvar CharacterCodes;\n(function (CharacterCodes) {\n CharacterCodes[CharacterCodes[\"lineFeed\"] = 10] = \"lineFeed\";\n CharacterCodes[CharacterCodes[\"carriageReturn\"] = 13] = \"carriageReturn\";\n CharacterCodes[CharacterCodes[\"space\"] = 32] = \"space\";\n CharacterCodes[CharacterCodes[\"_0\"] = 48] = \"_0\";\n CharacterCodes[CharacterCodes[\"_1\"] = 49] = \"_1\";\n CharacterCodes[CharacterCodes[\"_2\"] = 50] = \"_2\";\n CharacterCodes[CharacterCodes[\"_3\"] = 51] = \"_3\";\n CharacterCodes[CharacterCodes[\"_4\"] = 52] = \"_4\";\n CharacterCodes[CharacterCodes[\"_5\"] = 53] = \"_5\";\n CharacterCodes[CharacterCodes[\"_6\"] = 54] = \"_6\";\n CharacterCodes[CharacterCodes[\"_7\"] = 55] = \"_7\";\n CharacterCodes[CharacterCodes[\"_8\"] = 56] = \"_8\";\n CharacterCodes[CharacterCodes[\"_9\"] = 57] = \"_9\";\n CharacterCodes[CharacterCodes[\"a\"] = 97] = \"a\";\n CharacterCodes[CharacterCodes[\"b\"] = 98] = \"b\";\n CharacterCodes[CharacterCodes[\"c\"] = 99] = \"c\";\n CharacterCodes[CharacterCodes[\"d\"] = 100] = \"d\";\n CharacterCodes[CharacterCodes[\"e\"] = 101] = \"e\";\n CharacterCodes[CharacterCodes[\"f\"] = 102] = \"f\";\n CharacterCodes[CharacterCodes[\"g\"] = 103] = \"g\";\n CharacterCodes[CharacterCodes[\"h\"] = 104] = \"h\";\n CharacterCodes[CharacterCodes[\"i\"] = 105] = \"i\";\n CharacterCodes[CharacterCodes[\"j\"] = 106] = \"j\";\n CharacterCodes[CharacterCodes[\"k\"] = 107] = \"k\";\n CharacterCodes[CharacterCodes[\"l\"] = 108] = \"l\";\n CharacterCodes[CharacterCodes[\"m\"] = 109] = \"m\";\n CharacterCodes[CharacterCodes[\"n\"] = 110] = \"n\";\n CharacterCodes[CharacterCodes[\"o\"] = 111] = \"o\";\n CharacterCodes[CharacterCodes[\"p\"] = 112] = \"p\";\n CharacterCodes[CharacterCodes[\"q\"] = 113] = \"q\";\n CharacterCodes[CharacterCodes[\"r\"] = 114] = \"r\";\n CharacterCodes[CharacterCodes[\"s\"] = 115] = \"s\";\n CharacterCodes[CharacterCodes[\"t\"] = 116] = \"t\";\n CharacterCodes[CharacterCodes[\"u\"] = 117] = \"u\";\n CharacterCodes[CharacterCodes[\"v\"] = 118] = \"v\";\n CharacterCodes[CharacterCodes[\"w\"] = 119] = \"w\";\n CharacterCodes[CharacterCodes[\"x\"] = 120] = \"x\";\n CharacterCodes[CharacterCodes[\"y\"] = 121] = \"y\";\n CharacterCodes[CharacterCodes[\"z\"] = 122] = \"z\";\n CharacterCodes[CharacterCodes[\"A\"] = 65] = \"A\";\n CharacterCodes[CharacterCodes[\"B\"] = 66] = \"B\";\n CharacterCodes[CharacterCodes[\"C\"] = 67] = \"C\";\n CharacterCodes[CharacterCodes[\"D\"] = 68] = \"D\";\n CharacterCodes[CharacterCodes[\"E\"] = 69] = \"E\";\n CharacterCodes[CharacterCodes[\"F\"] = 70] = \"F\";\n CharacterCodes[CharacterCodes[\"G\"] = 71] = \"G\";\n CharacterCodes[CharacterCodes[\"H\"] = 72] = \"H\";\n CharacterCodes[CharacterCodes[\"I\"] = 73] = \"I\";\n CharacterCodes[CharacterCodes[\"J\"] = 74] = \"J\";\n CharacterCodes[CharacterCodes[\"K\"] = 75] = \"K\";\n CharacterCodes[CharacterCodes[\"L\"] = 76] = \"L\";\n CharacterCodes[CharacterCodes[\"M\"] = 77] = \"M\";\n CharacterCodes[CharacterCodes[\"N\"] = 78] = \"N\";\n CharacterCodes[CharacterCodes[\"O\"] = 79] = \"O\";\n CharacterCodes[CharacterCodes[\"P\"] = 80] = \"P\";\n CharacterCodes[CharacterCodes[\"Q\"] = 81] = \"Q\";\n CharacterCodes[CharacterCodes[\"R\"] = 82] = \"R\";\n CharacterCodes[CharacterCodes[\"S\"] = 83] = \"S\";\n CharacterCodes[CharacterCodes[\"T\"] = 84] = \"T\";\n CharacterCodes[CharacterCodes[\"U\"] = 85] = \"U\";\n CharacterCodes[CharacterCodes[\"V\"] = 86] = \"V\";\n CharacterCodes[CharacterCodes[\"W\"] = 87] = \"W\";\n CharacterCodes[CharacterCodes[\"X\"] = 88] = \"X\";\n CharacterCodes[CharacterCodes[\"Y\"] = 89] = \"Y\";\n CharacterCodes[CharacterCodes[\"Z\"] = 90] = \"Z\";\n CharacterCodes[CharacterCodes[\"asterisk\"] = 42] = \"asterisk\";\n CharacterCodes[CharacterCodes[\"backslash\"] = 92] = \"backslash\";\n CharacterCodes[CharacterCodes[\"closeBrace\"] = 125] = \"closeBrace\";\n CharacterCodes[CharacterCodes[\"closeBracket\"] = 93] = \"closeBracket\";\n CharacterCodes[CharacterCodes[\"colon\"] = 58] = \"colon\";\n CharacterCodes[CharacterCodes[\"comma\"] = 44] = \"comma\";\n CharacterCodes[CharacterCodes[\"dot\"] = 46] = \"dot\";\n CharacterCodes[CharacterCodes[\"doubleQuote\"] = 34] = \"doubleQuote\";\n CharacterCodes[CharacterCodes[\"minus\"] = 45] = \"minus\";\n CharacterCodes[CharacterCodes[\"openBrace\"] = 123] = \"openBrace\";\n CharacterCodes[CharacterCodes[\"openBracket\"] = 91] = \"openBracket\";\n CharacterCodes[CharacterCodes[\"plus\"] = 43] = \"plus\";\n CharacterCodes[CharacterCodes[\"slash\"] = 47] = \"slash\";\n CharacterCodes[CharacterCodes[\"formFeed\"] = 12] = \"formFeed\";\n CharacterCodes[CharacterCodes[\"tab\"] = 9] = \"tab\";\n})(CharacterCodes || (CharacterCodes = {}));\n","export const cachedSpaces = new Array(20).fill(0).map((_, index) => {\n return ' '.repeat(index);\n});\nconst maxCachedValues = 200;\nexport const cachedBreakLinesWithSpaces = {\n ' ': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + ' '.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + ' '.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + ' '.repeat(index);\n }),\n },\n '\\t': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + '\\t'.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + '\\t'.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + '\\t'.repeat(index);\n }),\n }\n};\nexport const supportedEols = ['\\n', '\\r', '\\r\\n'];\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport { createScanner } from './scanner';\nimport { cachedSpaces, cachedBreakLinesWithSpaces, supportedEols } from './string-intern';\nexport function format(documentText, range, options) {\n let initialIndentLevel;\n let formatText;\n let formatTextStart;\n let rangeStart;\n let rangeEnd;\n if (range) {\n rangeStart = range.offset;\n rangeEnd = rangeStart + range.length;\n formatTextStart = rangeStart;\n while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {\n formatTextStart--;\n }\n let endOffset = rangeEnd;\n while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {\n endOffset++;\n }\n formatText = documentText.substring(formatTextStart, endOffset);\n initialIndentLevel = computeIndentLevel(formatText, options);\n }\n else {\n formatText = documentText;\n initialIndentLevel = 0;\n formatTextStart = 0;\n rangeStart = 0;\n rangeEnd = documentText.length;\n }\n const eol = getEOL(options, documentText);\n const eolFastPathSupported = supportedEols.includes(eol);\n let numberLineBreaks = 0;\n let indentLevel = 0;\n let indentValue;\n if (options.insertSpaces) {\n indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4);\n }\n else {\n indentValue = '\\t';\n }\n const indentType = indentValue === '\\t' ? '\\t' : ' ';\n let scanner = createScanner(formatText, false);\n let hasError = false;\n function newLinesAndIndent() {\n if (numberLineBreaks > 1) {\n return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);\n }\n const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);\n if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) {\n return eol + repeat(indentValue, initialIndentLevel + indentLevel);\n }\n if (amountOfSpaces <= 0) {\n return eol;\n }\n return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];\n }\n function scanNext() {\n let token = scanner.scan();\n numberLineBreaks = 0;\n while (token === 15 /* SyntaxKind.Trivia */ || token === 14 /* SyntaxKind.LineBreakTrivia */) {\n if (token === 14 /* SyntaxKind.LineBreakTrivia */ && options.keepLines) {\n numberLineBreaks += 1;\n }\n else if (token === 14 /* SyntaxKind.LineBreakTrivia */) {\n numberLineBreaks = 1;\n }\n token = scanner.scan();\n }\n hasError = token === 16 /* SyntaxKind.Unknown */ || scanner.getTokenError() !== 0 /* ScanError.None */;\n return token;\n }\n const editOperations = [];\n function addEdit(text, startOffset, endOffset) {\n if (!hasError && (!range || (startOffset < rangeEnd && endOffset > rangeStart)) && documentText.substring(startOffset, endOffset) !== text) {\n editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });\n }\n }\n let firstToken = scanNext();\n if (options.keepLines && numberLineBreaks > 0) {\n addEdit(repeat(eol, numberLineBreaks), 0, 0);\n }\n if (firstToken !== 17 /* SyntaxKind.EOF */) {\n let firstTokenStart = scanner.getTokenOffset() + formatTextStart;\n let initialIndent = (indentValue.length * initialIndentLevel < 20) && options.insertSpaces\n ? cachedSpaces[indentValue.length * initialIndentLevel]\n : repeat(indentValue, initialIndentLevel);\n addEdit(initialIndent, formatTextStart, firstTokenStart);\n }\n while (firstToken !== 17 /* SyntaxKind.EOF */) {\n let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;\n let secondToken = scanNext();\n let replaceContent = '';\n let needsLineBreak = false;\n while (numberLineBreaks === 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) {\n let commentTokenStart = scanner.getTokenOffset() + formatTextStart;\n addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);\n firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;\n needsLineBreak = secondToken === 12 /* SyntaxKind.LineCommentTrivia */;\n replaceContent = needsLineBreak ? newLinesAndIndent() : '';\n secondToken = scanNext();\n }\n if (secondToken === 2 /* SyntaxKind.CloseBraceToken */) {\n if (firstToken !== 1 /* SyntaxKind.OpenBraceToken */) {\n indentLevel--;\n }\n ;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1 /* SyntaxKind.OpenBraceToken */) {\n replaceContent = newLinesAndIndent();\n }\n else if (options.keepLines) {\n replaceContent = cachedSpaces[1];\n }\n }\n else if (secondToken === 4 /* SyntaxKind.CloseBracketToken */) {\n if (firstToken !== 3 /* SyntaxKind.OpenBracketToken */) {\n indentLevel--;\n }\n ;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3 /* SyntaxKind.OpenBracketToken */) {\n replaceContent = newLinesAndIndent();\n }\n else if (options.keepLines) {\n replaceContent = cachedSpaces[1];\n }\n }\n else {\n switch (firstToken) {\n case 3 /* SyntaxKind.OpenBracketToken */:\n case 1 /* SyntaxKind.OpenBraceToken */:\n indentLevel++;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 5 /* SyntaxKind.CommaToken */:\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 12 /* SyntaxKind.LineCommentTrivia */:\n replaceContent = newLinesAndIndent();\n break;\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n if (numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (!needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 6 /* SyntaxKind.ColonToken */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (!needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 10 /* SyntaxKind.StringLiteral */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (secondToken === 6 /* SyntaxKind.ColonToken */ && !needsLineBreak) {\n replaceContent = '';\n }\n break;\n case 7 /* SyntaxKind.NullKeyword */:\n case 8 /* SyntaxKind.TrueKeyword */:\n case 9 /* SyntaxKind.FalseKeyword */:\n case 11 /* SyntaxKind.NumericLiteral */:\n case 2 /* SyntaxKind.CloseBraceToken */:\n case 4 /* SyntaxKind.CloseBracketToken */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else {\n if ((secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */) && !needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n else if (secondToken !== 5 /* SyntaxKind.CommaToken */ && secondToken !== 17 /* SyntaxKind.EOF */) {\n hasError = true;\n }\n }\n break;\n case 16 /* SyntaxKind.Unknown */:\n hasError = true;\n break;\n }\n if (numberLineBreaks > 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) {\n replaceContent = newLinesAndIndent();\n }\n }\n if (secondToken === 17 /* SyntaxKind.EOF */) {\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = options.insertFinalNewline ? eol : '';\n }\n }\n const secondTokenStart = scanner.getTokenOffset() + formatTextStart;\n addEdit(replaceContent, firstTokenEnd, secondTokenStart);\n firstToken = secondToken;\n }\n return editOperations;\n}\nfunction repeat(s, count) {\n let result = '';\n for (let i = 0; i < count; i++) {\n result += s;\n }\n return result;\n}\nfunction computeIndentLevel(content, options) {\n let i = 0;\n let nChars = 0;\n const tabSize = options.tabSize || 4;\n while (i < content.length) {\n let ch = content.charAt(i);\n if (ch === cachedSpaces[1]) {\n nChars++;\n }\n else if (ch === '\\t') {\n nChars += tabSize;\n }\n else {\n break;\n }\n i++;\n }\n return Math.floor(nChars / tabSize);\n}\nfunction getEOL(options, text) {\n for (let i = 0; i < text.length; i++) {\n const ch = text.charAt(i);\n if (ch === '\\r') {\n if (i + 1 < text.length && text.charAt(i + 1) === '\\n') {\n return '\\r\\n';\n }\n return '\\r';\n }\n else if (ch === '\\n') {\n return '\\n';\n }\n }\n return (options && options.eol) || '\\n';\n}\nexport function isEOL(text, offset) {\n return '\\r\\n'.indexOf(text.charAt(offset)) !== -1;\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport { createScanner } from './scanner';\nvar ParseOptions;\n(function (ParseOptions) {\n ParseOptions.DEFAULT = {\n allowTrailingComma: false\n };\n})(ParseOptions || (ParseOptions = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport function getLocation(text, position) {\n const segments = []; // strings or numbers\n const earlyReturnException = new Object();\n let previousNode = undefined;\n const previousNodeInst = {\n value: {},\n offset: 0,\n length: 0,\n type: 'object',\n parent: undefined\n };\n let isAtPropertyKey = false;\n function setPreviousNode(value, offset, length, type) {\n previousNodeInst.value = value;\n previousNodeInst.offset = offset;\n previousNodeInst.length = length;\n previousNodeInst.type = type;\n previousNodeInst.colonOffset = undefined;\n previousNode = previousNodeInst;\n }\n try {\n visit(text, {\n onObjectBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n isAtPropertyKey = position > offset;\n segments.push(''); // push a placeholder (will be replaced)\n },\n onObjectProperty: (name, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(name, offset, length, 'property');\n segments[segments.length - 1] = name;\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onObjectEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onArrayBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.push(0);\n },\n onArrayEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onLiteralValue: (value, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(value, offset, length, getNodeType(value));\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onSeparator: (sep, offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n if (sep === ':' && previousNode && previousNode.type === 'property') {\n previousNode.colonOffset = offset;\n isAtPropertyKey = false;\n previousNode = undefined;\n }\n else if (sep === ',') {\n const last = segments[segments.length - 1];\n if (typeof last === 'number') {\n segments[segments.length - 1] = last + 1;\n }\n else {\n isAtPropertyKey = true;\n segments[segments.length - 1] = '';\n }\n previousNode = undefined;\n }\n }\n });\n }\n catch (e) {\n if (e !== earlyReturnException) {\n throw e;\n }\n }\n return {\n path: segments,\n previousNode,\n isAtPropertyKey,\n matches: (pattern) => {\n let k = 0;\n for (let i = 0; k < pattern.length && i < segments.length; i++) {\n if (pattern[k] === segments[i] || pattern[k] === '*') {\n k++;\n }\n else if (pattern[k] !== '**') {\n return false;\n }\n }\n return k === pattern.length;\n }\n };\n}\n/**\n * 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.\n * Therefore always check the errors list to find out if the input was valid.\n */\nexport function parse(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentProperty = null;\n let currentParent = [];\n const previousParents = [];\n function onValue(value) {\n if (Array.isArray(currentParent)) {\n currentParent.push(value);\n }\n else if (currentProperty !== null) {\n currentParent[currentProperty] = value;\n }\n }\n const visitor = {\n onObjectBegin: () => {\n const object = {};\n onValue(object);\n previousParents.push(currentParent);\n currentParent = object;\n currentProperty = null;\n },\n onObjectProperty: (name) => {\n currentProperty = name;\n },\n onObjectEnd: () => {\n currentParent = previousParents.pop();\n },\n onArrayBegin: () => {\n const array = [];\n onValue(array);\n previousParents.push(currentParent);\n currentParent = array;\n currentProperty = null;\n },\n onArrayEnd: () => {\n currentParent = previousParents.pop();\n },\n onLiteralValue: onValue,\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n return currentParent[0];\n}\n/**\n * 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.\n */\nexport function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n const visitor = {\n onObjectBegin: (offset) => {\n currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: (name, offset, length) => {\n currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent });\n },\n onObjectEnd: (offset, length) => {\n ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: (offset, length) => {\n currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: (offset, length) => {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: (value, offset, length) => {\n onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: (sep, offset, length) => {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.colonOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n const result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n}\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport function findNodeAtLocation(root, path) {\n if (!root) {\n return undefined;\n }\n let node = root;\n for (let segment of path) {\n if (typeof segment === 'string') {\n if (node.type !== 'object' || !Array.isArray(node.children)) {\n return undefined;\n }\n let found = false;\n for (const propertyNode of node.children) {\n if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {\n node = propertyNode.children[1];\n found = true;\n break;\n }\n }\n if (!found) {\n return undefined;\n }\n }\n else {\n const index = segment;\n if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {\n return undefined;\n }\n node = node.children[index];\n }\n }\n return node;\n}\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport function getNodePath(node) {\n if (!node.parent || !node.parent.children) {\n return [];\n }\n const path = getNodePath(node.parent);\n if (node.parent.type === 'property') {\n const key = node.parent.children[0].value;\n path.push(key);\n }\n else if (node.parent.type === 'array') {\n const index = node.parent.children.indexOf(node);\n if (index !== -1) {\n path.push(index);\n }\n }\n return path;\n}\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport function getNodeValue(node) {\n switch (node.type) {\n case 'array':\n return node.children.map(getNodeValue);\n case 'object':\n const obj = Object.create(null);\n for (let prop of node.children) {\n const valueNode = prop.children[1];\n if (valueNode) {\n obj[prop.children[0].value] = getNodeValue(valueNode);\n }\n }\n return obj;\n case 'null':\n case 'string':\n case 'number':\n case 'boolean':\n return node.value;\n default:\n return undefined;\n }\n}\nexport function contains(node, offset, includeRightBound = false) {\n return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));\n}\n/**\n * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport function findNodeAtOffset(node, offset, includeRightBound = false) {\n if (contains(node, offset, includeRightBound)) {\n const children = node.children;\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length && children[i].offset <= offset; i++) {\n const item = findNodeAtOffset(children[i], offset, includeRightBound);\n if (item) {\n return item;\n }\n }\n }\n return node;\n }\n return undefined;\n}\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport function visit(text, visitor, options = ParseOptions.DEFAULT) {\n const _scanner = createScanner(text, false);\n // Important: Only pass copies of this to visitor functions to prevent accidental modification, and\n // to not affect visitor functions which stored a reference to a previous JSONPath\n const _jsonPath = [];\n // Depth of onXXXBegin() callbacks suppressed. onXXXEnd() decrements this if it isn't 0 already.\n // Callbacks are only called when this value is 0.\n let suppressedCallbacks = 0;\n function toNoArgVisit(visitFunction) {\n return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisit(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisitWithPath(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;\n }\n function toBeginVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks++;\n }\n else {\n let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());\n if (cbReturn === false) {\n suppressedCallbacks = 1;\n }\n }\n }\n : () => true;\n }\n function toEndVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks--;\n }\n if (suppressedCallbacks === 0) {\n visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());\n }\n }\n : () => true;\n }\n 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);\n const disallowComments = options && options.disallowComments;\n const allowTrailingComma = options && options.allowTrailingComma;\n function scanNext() {\n while (true) {\n const token = _scanner.scan();\n switch (_scanner.getTokenError()) {\n case 4 /* ScanError.InvalidUnicode */:\n handleError(14 /* ParseErrorCode.InvalidUnicode */);\n break;\n case 5 /* ScanError.InvalidEscapeCharacter */:\n handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */);\n break;\n case 3 /* ScanError.UnexpectedEndOfNumber */:\n handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */);\n break;\n case 1 /* ScanError.UnexpectedEndOfComment */:\n if (!disallowComments) {\n handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */);\n }\n break;\n case 2 /* ScanError.UnexpectedEndOfString */:\n handleError(12 /* ParseErrorCode.UnexpectedEndOfString */);\n break;\n case 6 /* ScanError.InvalidCharacter */:\n handleError(16 /* ParseErrorCode.InvalidCharacter */);\n break;\n }\n switch (token) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n if (disallowComments) {\n handleError(10 /* ParseErrorCode.InvalidCommentToken */);\n }\n else {\n onComment();\n }\n break;\n case 16 /* SyntaxKind.Unknown */:\n handleError(1 /* ParseErrorCode.InvalidSymbol */);\n break;\n case 15 /* SyntaxKind.Trivia */:\n case 14 /* SyntaxKind.LineBreakTrivia */:\n break;\n default:\n return token;\n }\n }\n }\n function handleError(error, skipUntilAfter = [], skipUntil = []) {\n onError(error);\n if (skipUntilAfter.length + skipUntil.length > 0) {\n let token = _scanner.getToken();\n while (token !== 17 /* SyntaxKind.EOF */) {\n if (skipUntilAfter.indexOf(token) !== -1) {\n scanNext();\n break;\n }\n else if (skipUntil.indexOf(token) !== -1) {\n break;\n }\n token = scanNext();\n }\n }\n }\n function parseString(isValue) {\n const value = _scanner.getTokenValue();\n if (isValue) {\n onLiteralValue(value);\n }\n else {\n onObjectProperty(value);\n // add property name afterwards\n _jsonPath.push(value);\n }\n scanNext();\n return true;\n }\n function parseLiteral() {\n switch (_scanner.getToken()) {\n case 11 /* SyntaxKind.NumericLiteral */:\n const tokenValue = _scanner.getTokenValue();\n let value = Number(tokenValue);\n if (isNaN(value)) {\n handleError(2 /* ParseErrorCode.InvalidNumberFormat */);\n value = 0;\n }\n onLiteralValue(value);\n break;\n case 7 /* SyntaxKind.NullKeyword */:\n onLiteralValue(null);\n break;\n case 8 /* SyntaxKind.TrueKeyword */:\n onLiteralValue(true);\n break;\n case 9 /* SyntaxKind.FalseKeyword */:\n onLiteralValue(false);\n break;\n default:\n return false;\n }\n scanNext();\n return true;\n }\n function parseProperty() {\n if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) {\n handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n return false;\n }\n parseString(false);\n if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) {\n onSeparator(':');\n scanNext(); // consume colon\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n }\n else {\n handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n _jsonPath.pop(); // remove processed property name\n return true;\n }\n function parseObject() {\n onObjectBegin();\n scanNext(); // consume open brace\n let needsComma = false;\n while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (!parseProperty()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onObjectEnd();\n if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) {\n handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []);\n }\n else {\n scanNext(); // consume close brace\n }\n return true;\n }\n function parseArray() {\n onArrayBegin();\n scanNext(); // consume open bracket\n let isFirstElement = true;\n let needsComma = false;\n while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (isFirstElement) {\n _jsonPath.push(0);\n isFirstElement = false;\n }\n else {\n _jsonPath[_jsonPath.length - 1]++;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onArrayEnd();\n if (!isFirstElement) {\n _jsonPath.pop(); // remove array index\n }\n if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) {\n handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []);\n }\n else {\n scanNext(); // consume close bracket\n }\n return true;\n }\n function parseValue() {\n switch (_scanner.getToken()) {\n case 3 /* SyntaxKind.OpenBracketToken */:\n return parseArray();\n case 1 /* SyntaxKind.OpenBraceToken */:\n return parseObject();\n case 10 /* SyntaxKind.StringLiteral */:\n return parseString(true);\n default:\n return parseLiteral();\n }\n }\n scanNext();\n if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) {\n if (options.allowEmptyContent) {\n return true;\n }\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []);\n }\n return true;\n}\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport function stripComments(text, replaceCh) {\n let _scanner = createScanner(text), parts = [], kind, offset = 0, pos;\n do {\n pos = _scanner.getPosition();\n kind = _scanner.scan();\n switch (kind) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n case 17 /* SyntaxKind.EOF */:\n if (offset !== pos) {\n parts.push(text.substring(offset, pos));\n }\n if (replaceCh !== undefined) {\n parts.push(_scanner.getTokenValue().replace(/[^\\r\\n]/g, replaceCh));\n }\n offset = _scanner.getPosition();\n break;\n }\n } while (kind !== 17 /* SyntaxKind.EOF */);\n return parts.join('');\n}\nexport function getNodeType(value) {\n switch (typeof value) {\n case 'boolean': return 'boolean';\n case 'number': return 'number';\n case 'string': return 'string';\n case 'object': {\n if (!value) {\n return 'null';\n }\n else if (Array.isArray(value)) {\n return 'array';\n }\n return 'object';\n }\n default: return 'null';\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport { format, isEOL } from './format';\nimport { parseTree, findNodeAtLocation } from './parser';\nexport function removeProperty(text, path, options) {\n return setProperty(text, path, void 0, options);\n}\nexport function setProperty(text, originalPath, value, options) {\n const path = originalPath.slice();\n const errors = [];\n const root = parseTree(text, errors);\n let parent = void 0;\n let lastSegment = void 0;\n while (path.length > 0) {\n lastSegment = path.pop();\n parent = findNodeAtLocation(root, path);\n if (parent === void 0 && value !== void 0) {\n if (typeof lastSegment === 'string') {\n value = { [lastSegment]: value };\n }\n else {\n value = [value];\n }\n }\n else {\n break;\n }\n }\n if (!parent) {\n // empty document\n if (value === void 0) { // delete\n throw new Error('Can not delete in empty document');\n }\n return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);\n }\n else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {\n const existing = findNodeAtLocation(parent, [lastSegment]);\n if (existing !== void 0) {\n if (value === void 0) { // delete\n if (!existing.parent) {\n throw new Error('Malformed AST');\n }\n const propertyIndex = parent.children.indexOf(existing.parent);\n let removeBegin;\n let removeEnd = existing.parent.offset + existing.parent.length;\n if (propertyIndex > 0) {\n // remove the comma of the previous node\n let previous = parent.children[propertyIndex - 1];\n removeBegin = previous.offset + previous.length;\n }\n else {\n removeBegin = parent.offset + 1;\n if (parent.children.length > 1) {\n // remove the comma of the next node\n let next = parent.children[1];\n removeEnd = next.offset;\n }\n }\n return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options);\n }\n else {\n // set value of existing property\n return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);\n }\n }\n else {\n if (value === void 0) { // delete\n return []; // property does not exist, nothing to do\n }\n const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;\n const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(p => p.children[0].value)) : parent.children.length;\n let edit;\n if (index > 0) {\n let previous = parent.children[index - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n else if (parent.children.length === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty };\n }\n else {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };\n }\n return withFormatting(text, edit, options);\n }\n }\n else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {\n const insertIndex = lastSegment;\n if (insertIndex === -1) {\n // Insert\n const newProperty = `${JSON.stringify(value)}`;\n let edit;\n if (parent.children.length === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty };\n }\n else {\n const previous = parent.children[parent.children.length - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n return withFormatting(text, edit, options);\n }\n else if (value === void 0 && parent.children.length >= 0) {\n // Removal\n const removalIndex = lastSegment;\n const toRemove = parent.children[removalIndex];\n let edit;\n if (parent.children.length === 1) {\n // only item\n edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };\n }\n else if (parent.children.length - 1 === removalIndex) {\n // last item\n let previous = parent.children[removalIndex - 1];\n let offset = previous.offset + previous.length;\n let parentEndOffset = parent.offset + parent.length;\n edit = { offset, length: parentEndOffset - 2 - offset, content: '' };\n }\n else {\n edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };\n }\n return withFormatting(text, edit, options);\n }\n else if (value !== void 0) {\n let edit;\n const newProperty = `${JSON.stringify(value)}`;\n if (!options.isArrayInsertion && parent.children.length > lastSegment) {\n const toModify = parent.children[lastSegment];\n edit = { offset: toModify.offset, length: toModify.length, content: newProperty };\n }\n else if (parent.children.length === 0 || lastSegment === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' };\n }\n else {\n const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;\n const previous = parent.children[index - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n return withFormatting(text, edit, options);\n }\n else {\n throw new Error(`Can not ${value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')} Array index ${insertIndex} as length is not sufficient`);\n }\n }\n else {\n throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`);\n }\n}\nfunction withFormatting(text, edit, options) {\n if (!options.formattingOptions) {\n return [edit];\n }\n // apply the edit\n let newText = applyEdit(text, edit);\n // format the new text\n let begin = edit.offset;\n let end = edit.offset + edit.content.length;\n if (edit.length === 0 || edit.content.length === 0) { // insert or remove\n while (begin > 0 && !isEOL(newText, begin - 1)) {\n begin--;\n }\n while (end < newText.length && !isEOL(newText, end)) {\n end++;\n }\n }\n const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false });\n // apply the formatting edits and track the begin and end offsets of the changes\n for (let i = edits.length - 1; i >= 0; i--) {\n const edit = edits[i];\n newText = applyEdit(newText, edit);\n begin = Math.min(begin, edit.offset);\n end = Math.max(end, edit.offset + edit.length);\n end += edit.content.length - edit.length;\n }\n // create a single edit with all changes\n const editLength = text.length - (newText.length - end) - begin;\n return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];\n}\nexport function applyEdit(text, edit) {\n return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);\n}\nexport function isWS(text, offset) {\n return '\\r\\n \\t'.indexOf(text.charAt(offset)) !== -1;\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport * as formatter from './impl/format';\nimport * as edit from './impl/edit';\nimport * as scanner from './impl/scanner';\nimport * as parser from './impl/parser';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport const createScanner = scanner.createScanner;\nexport var ScanError;\n(function (ScanError) {\n ScanError[ScanError[\"None\"] = 0] = \"None\";\n ScanError[ScanError[\"UnexpectedEndOfComment\"] = 1] = \"UnexpectedEndOfComment\";\n ScanError[ScanError[\"UnexpectedEndOfString\"] = 2] = \"UnexpectedEndOfString\";\n ScanError[ScanError[\"UnexpectedEndOfNumber\"] = 3] = \"UnexpectedEndOfNumber\";\n ScanError[ScanError[\"InvalidUnicode\"] = 4] = \"InvalidUnicode\";\n ScanError[ScanError[\"InvalidEscapeCharacter\"] = 5] = \"InvalidEscapeCharacter\";\n ScanError[ScanError[\"InvalidCharacter\"] = 6] = \"InvalidCharacter\";\n})(ScanError || (ScanError = {}));\nexport var SyntaxKind;\n(function (SyntaxKind) {\n SyntaxKind[SyntaxKind[\"OpenBraceToken\"] = 1] = \"OpenBraceToken\";\n SyntaxKind[SyntaxKind[\"CloseBraceToken\"] = 2] = \"CloseBraceToken\";\n SyntaxKind[SyntaxKind[\"OpenBracketToken\"] = 3] = \"OpenBracketToken\";\n SyntaxKind[SyntaxKind[\"CloseBracketToken\"] = 4] = \"CloseBracketToken\";\n SyntaxKind[SyntaxKind[\"CommaToken\"] = 5] = \"CommaToken\";\n SyntaxKind[SyntaxKind[\"ColonToken\"] = 6] = \"ColonToken\";\n SyntaxKind[SyntaxKind[\"NullKeyword\"] = 7] = \"NullKeyword\";\n SyntaxKind[SyntaxKind[\"TrueKeyword\"] = 8] = \"TrueKeyword\";\n SyntaxKind[SyntaxKind[\"FalseKeyword\"] = 9] = \"FalseKeyword\";\n SyntaxKind[SyntaxKind[\"StringLiteral\"] = 10] = \"StringLiteral\";\n SyntaxKind[SyntaxKind[\"NumericLiteral\"] = 11] = \"NumericLiteral\";\n SyntaxKind[SyntaxKind[\"LineCommentTrivia\"] = 12] = \"LineCommentTrivia\";\n SyntaxKind[SyntaxKind[\"BlockCommentTrivia\"] = 13] = \"BlockCommentTrivia\";\n SyntaxKind[SyntaxKind[\"LineBreakTrivia\"] = 14] = \"LineBreakTrivia\";\n SyntaxKind[SyntaxKind[\"Trivia\"] = 15] = \"Trivia\";\n SyntaxKind[SyntaxKind[\"Unknown\"] = 16] = \"Unknown\";\n SyntaxKind[SyntaxKind[\"EOF\"] = 17] = \"EOF\";\n})(SyntaxKind || (SyntaxKind = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport const getLocation = parser.getLocation;\n/**\n * 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.\n * Therefore, always check the errors list to find out if the input was valid.\n */\nexport const parse = parser.parse;\n/**\n * 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.\n */\nexport const parseTree = parser.parseTree;\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport const findNodeAtLocation = parser.findNodeAtLocation;\n/**\n * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport const findNodeAtOffset = parser.findNodeAtOffset;\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport const getNodePath = parser.getNodePath;\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport const getNodeValue = parser.getNodeValue;\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport const visit = parser.visit;\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport const stripComments = parser.stripComments;\nexport var ParseErrorCode;\n(function (ParseErrorCode) {\n ParseErrorCode[ParseErrorCode[\"InvalidSymbol\"] = 1] = \"InvalidSymbol\";\n ParseErrorCode[ParseErrorCode[\"InvalidNumberFormat\"] = 2] = \"InvalidNumberFormat\";\n ParseErrorCode[ParseErrorCode[\"PropertyNameExpected\"] = 3] = \"PropertyNameExpected\";\n ParseErrorCode[ParseErrorCode[\"ValueExpected\"] = 4] = \"ValueExpected\";\n ParseErrorCode[ParseErrorCode[\"ColonExpected\"] = 5] = \"ColonExpected\";\n ParseErrorCode[ParseErrorCode[\"CommaExpected\"] = 6] = \"CommaExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBraceExpected\"] = 7] = \"CloseBraceExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBracketExpected\"] = 8] = \"CloseBracketExpected\";\n ParseErrorCode[ParseErrorCode[\"EndOfFileExpected\"] = 9] = \"EndOfFileExpected\";\n ParseErrorCode[ParseErrorCode[\"InvalidCommentToken\"] = 10] = \"InvalidCommentToken\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfComment\"] = 11] = \"UnexpectedEndOfComment\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfString\"] = 12] = \"UnexpectedEndOfString\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfNumber\"] = 13] = \"UnexpectedEndOfNumber\";\n ParseErrorCode[ParseErrorCode[\"InvalidUnicode\"] = 14] = \"InvalidUnicode\";\n ParseErrorCode[ParseErrorCode[\"InvalidEscapeCharacter\"] = 15] = \"InvalidEscapeCharacter\";\n ParseErrorCode[ParseErrorCode[\"InvalidCharacter\"] = 16] = \"InvalidCharacter\";\n})(ParseErrorCode || (ParseErrorCode = {}));\nexport function printParseErrorCode(code) {\n switch (code) {\n case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol';\n case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat';\n case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected';\n case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected';\n case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected';\n case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected';\n case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected';\n case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected';\n case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected';\n case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken';\n case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';\n case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString';\n case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';\n case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode';\n case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';\n case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter';\n }\n return '<unknown ParseErrorCode>';\n}\n/**\n * Computes the edit operations needed to format a JSON document.\n *\n * @param documentText The input text\n * @param range The range to format or `undefined` to format the full content\n * @param options The formatting options\n * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function format(documentText, range, options) {\n return formatter.format(documentText, range, options);\n}\n/**\n * Computes the edit operations needed to modify a value in the JSON document.\n *\n * @param documentText The input text\n * @param path The path of the value to change. The path represents either to the document root, a property or an array item.\n * If the path points to an non-existing property or item, it will be created.\n * @param value The new value for the specified property or item. If the value is undefined,\n * the property or item will be removed.\n * @param options Options\n * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function modify(text, path, value, options) {\n return edit.setProperty(text, path, value, options);\n}\n/**\n * Applies edits to an input string.\n * @param text The input text\n * @param edits Edit operations following the format described in {@linkcode EditResult}.\n * @returns The text with the applied edits.\n * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.\n */\nexport function applyEdits(text, edits) {\n let sortedEdits = edits.slice(0).sort((a, b) => {\n const diff = a.offset - b.offset;\n if (diff === 0) {\n return a.length - b.length;\n }\n return diff;\n });\n let lastModifiedOffset = text.length;\n for (let i = sortedEdits.length - 1; i >= 0; i--) {\n let e = sortedEdits[i];\n if (e.offset + e.length <= lastModifiedOffset) {\n text = edit.applyEdit(text, e);\n }\n else {\n throw new Error('Overlapping edit');\n }\n lastModifiedOffset = e.offset;\n }\n return text;\n}\n","/**\n * Surgical wrangler.jsonc helpers used by `baerly deploy` and the\n * `@gusto/create-baerly-storage` bolt-on flow. All functions are pure (no I/O) —\n * callers do the file read/write. Built on `jsonc-parser` so\n * comments and trailing commas survive round-trips.\n */\n\nimport { parse, modify, applyEdits, type ParseError, type FormattingOptions } from \"jsonc-parser\";\nimport { BaerlyError } from \"@baerly/protocol\";\n\n/**\n * Declared R2 binding extracted from a `wrangler.jsonc` source.\n * Subset of the wrangler schema — we only consume `binding` and\n * `bucket_name`, not the optional preview/jurisdiction fields.\n */\nexport interface R2BindingDeclaration {\n readonly binding: string;\n readonly bucket_name: string;\n}\n\n/**\n * Parse declared `r2_buckets[]` from a `wrangler.jsonc` source\n * string. Tolerates comments + trailing commas via `jsonc-parser`.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — malformed JSONC or\n * invalid `r2_buckets` shape.\n */\nexport const parseR2Bindings = (source: string): readonly R2BindingDeclaration[] => {\n const errors: ParseError[] = [];\n const obj = parse(source, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { r2_buckets?: unknown }\n | undefined;\n if (errors.length > 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `wrangler.jsonc parse error at offset ${errors[0]!.offset}: ${errors[0]!.error}`,\n );\n }\n if (obj === undefined || typeof obj !== \"object\") {\n throw new BaerlyError(\"InvalidConfig\", `wrangler.jsonc did not parse to an object`);\n }\n const buckets = obj.r2_buckets;\n if (buckets === undefined) {\n return [];\n }\n if (!Array.isArray(buckets)) {\n throw new BaerlyError(\"InvalidConfig\", `wrangler.jsonc: r2_buckets must be an array`);\n }\n const out: R2BindingDeclaration[] = [];\n for (const b of buckets) {\n if (b === null || typeof b !== \"object\") {\n throw new BaerlyError(\"InvalidConfig\", `wrangler.jsonc: r2_buckets entry must be an object`);\n }\n const entry = b as { binding?: unknown; bucket_name?: unknown };\n if (typeof entry.binding !== \"string\" || entry.binding.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `wrangler.jsonc: r2_buckets[].binding must be a non-empty string`,\n );\n }\n if (typeof entry.bucket_name !== \"string\" || entry.bucket_name.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `wrangler.jsonc: r2_buckets[].bucket_name must be a non-empty string`,\n );\n }\n out.push({ binding: entry.binding, bucket_name: entry.bucket_name });\n }\n return out;\n};\n\n/**\n * Input spec for a single R2 binding to add or verify in\n * `wrangler.jsonc`. Mirrors `R2BindingDeclaration` in shape but\n * represents caller intent rather than a parsed declaration.\n */\nexport interface R2BindingSpec {\n readonly binding: string;\n readonly bucket_name: string;\n}\n\n/**\n * Flat string→string map of `vars` entries to merge into\n * `wrangler.jsonc`. Existing keys are never overwritten (user wins).\n */\nexport interface VarsSpec {\n readonly [key: string]: string;\n}\n\n/**\n * Result returned by `patchWranglerJsonc`. `text` is the updated\n * JSONC source; `changes` is a human-readable summary of what was\n * added (empty when the file was already up to date).\n */\nexport interface PatchResult {\n readonly text: string;\n readonly changes: readonly string[];\n}\n\n/**\n * Read the `name` field from a `wrangler.jsonc` source string.\n * Returns `undefined` on malformed JSONC or when the field is absent.\n * Never throws — designed for caller-friendly inspection.\n */\nexport const readWranglerName = (source: string): string | undefined => {\n const errors: ParseError[] = [];\n const parsed = parse(source, errors, { allowTrailingComma: true }) as\n | { name?: unknown }\n | undefined;\n if (errors.length > 0 || typeof parsed?.name !== \"string\") {\n return undefined;\n }\n return parsed.name;\n};\n\n/**\n * Read the `main` field from a `wrangler.jsonc` source string.\n * Returns `undefined` on malformed JSONC or when the field is absent.\n * Never throws — designed for caller-friendly inspection.\n */\nexport const readWranglerMain = (source: string): string | undefined => {\n const errors: ParseError[] = [];\n const parsed = parse(source, errors, { allowTrailingComma: true }) as\n | { main?: unknown }\n | undefined;\n if (errors.length > 0 || typeof parsed?.main !== \"string\") {\n return undefined;\n }\n return parsed.main;\n};\n\n// Sniff the indent style of a JSONC source by scanning for the first\n// indented line and inspecting its leading whitespace. The stock\n// `pnpm create cloudflare` template uses tabs; older / hand-rolled\n// `wrangler.jsonc` files commonly use 2- or 4-space indents. Falls\n// back to 2-space when the file has no indented content (e.g. `{}`).\nconst detectIndent = (source: string): FormattingOptions => {\n for (const line of source.split(\"\\n\")) {\n if (line.length === 0 || line.startsWith(\"{\") || line.startsWith(\"}\")) {\n continue;\n }\n const first = line.charAt(0);\n if (first === \"\\t\") {\n return { insertSpaces: false, tabSize: 2, eol: \"\\n\" };\n }\n if (first === \" \") {\n let count = 0;\n while (count < line.length && line.charAt(count) === \" \") {\n count += 1;\n }\n return { insertSpaces: true, tabSize: count, eol: \"\\n\" };\n }\n }\n return { insertSpaces: true, tabSize: 2, eol: \"\\n\" };\n};\n\n/**\n * Idempotently patch a `wrangler.jsonc` source string:\n *\n * - Appends an R2 binding to `r2_buckets[]` unless an entry with\n * the same `binding` name already exists (user wins).\n * - Merges `vars` keys, skipping any key already present (user wins).\n *\n * Comments and trailing commas are preserved by `jsonc-parser`.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — malformed JSONC or\n * invalid `r2_buckets` / `vars` shape.\n */\nexport const patchWranglerJsonc = (\n source: string,\n binding: R2BindingSpec,\n vars: VarsSpec,\n): PatchResult => {\n const existingBindings = parseR2Bindings(source);\n\n const errors: ParseError[] = [];\n const entry = parse(source, errors, { allowTrailingComma: true }) as\n | { vars?: unknown }\n | undefined;\n\n const rawVars = entry?.vars;\n if (rawVars !== undefined) {\n if (typeof rawVars !== \"object\" || rawVars === null || Array.isArray(rawVars)) {\n throw new BaerlyError(\"InvalidConfig\", \"wrangler.jsonc: vars must be an object\");\n }\n }\n const existingVars = (rawVars ?? {}) as Record<string, unknown>;\n\n const formattingOptions = detectIndent(source);\n const changes: string[] = [];\n let text = source;\n\n const bindingAlreadyDeclared = existingBindings.some((b) => b.binding === binding.binding);\n if (!bindingAlreadyDeclared) {\n const edits = modify(text, [\"r2_buckets\", -1], binding, { formattingOptions });\n text = applyEdits(text, edits);\n changes.push(`added r2 binding ${binding.binding} → ${binding.bucket_name}`);\n }\n\n const addedVarKeys: string[] = [];\n for (const [key, value] of Object.entries(vars)) {\n if (!(key in existingVars)) {\n const edits = modify(text, [\"vars\", key], value, { formattingOptions });\n text = applyEdits(text, edits);\n addedVarKeys.push(key);\n }\n }\n if (addedVarKeys.length > 0) {\n changes.push(`merged vars: ${addedVarKeys.join(\", \")}`);\n }\n\n return { text, changes };\n};\n","/**\n * Render the worker-entry paste-string that the create-baerly-storage\n * bolt-on flow prints after patching `wrangler.jsonc`. The user\n * copies this verbatim into the path declared in\n * `wrangler.jsonc:main`, replacing the stock `wrangler create`\n * hello world. baerly never writes user code (Convex-style:\n * structured config is fair game; the worker entry is sacred).\n */\n\nimport { relative, dirname, normalize } from \"node:path/posix\";\n\nexport interface SnippetContext {\n /**\n * Tenant identifier the bolt-on flow seeds into `wrangler.jsonc:vars.TENANT`.\n * The snippet itself does NOT interpolate this — it references the runtime\n * `env.TENANT`. The field lives on this context type so callers pass a\n * single object to both the snippet renderer and the wrangler patcher.\n */\n readonly tenant: string;\n /** Verbatim `wrangler.jsonc:main` — drives the import-to-config relpath. */\n readonly wranglerMain: string;\n}\n\n/**\n * Compute the JS import path from `wranglerMain` to `./baerly.config.ts`.\n * Both inputs are repo-root-relative; the output is the import string\n * the snippet emits. Always carries the explicit `.ts` extension\n * (project convention; see CLAUDE.md \"Imports are relative, with\n * explicit `.ts`/`.tsx` extensions\").\n */\n// Callers must pass forward-slash paths. POSIX normalize treats `\\\\` as a\n// literal character, not a separator, so backslash-style Windows paths\n// would be misinterpreted. `wrangler.jsonc:main` always uses forward slashes\n// on every host, so this is safe in practice.\nexport const computeConfigImportPath = (wranglerMain: string): string => {\n const normalised = normalize(wranglerMain);\n const fromDir = dirname(normalised);\n if (fromDir === \".\" || fromDir === \"\") {\n return \"./baerly.config.ts\";\n }\n const rel = relative(fromDir, \"baerly.config.ts\");\n return rel.startsWith(\"..\") ? rel : `./${rel}`;\n};\n\nexport const renderWorkerEntrySnippet = (ctx: SnippetContext): string => {\n const configPath = computeConfigImportPath(ctx.wranglerMain);\n return `import { baerlyWorker, type BaerlyEnv } from \"@gusto/baerly-storage/cloudflare\";\nimport { sharedSecret } from \"@gusto/baerly-storage/auth\";\nimport config from \"${configPath}\";\n\ninterface AppEnv extends BaerlyEnv {\n readonly TENANT: string;\n readonly SHARED_SECRET: string;\n}\n\nexport default baerlyWorker<AppEnv>((env) => ({\n verifier: sharedSecret({ secret: env.SHARED_SECRET, tenantPrefix: env.TENANT }),\n config,\n}));\n`;\n};\n","/**\n * `Installer` DI seam for the post-scaffold install step. The default\n * implementation shells out to the detected package manager via\n * `node:child_process.spawn` with `stdio: \"inherit\"` so the user sees\n * the pm's own progress (pnpm's spinner, npm's bars). Tests inject a\n * mock to avoid spawning real installs.\n *\n * Mirrors the shape of `packages/cli/src/runner.ts:ProcessRunner` —\n * intentionally not imported cross-package because `create-baerly-storage`\n * has its own dependency surface (no `@baerly/cli` dep).\n */\nimport { spawn } from \"node:child_process\";\nimport type { Pm } from \"./pm-detect.ts\";\n\nexport interface Installer {\n /**\n * Run `<pm> install` in `cwd`. Resolves with the child's exit code.\n * Never throws on a non-zero exit — the caller decides whether that\n * should be fatal. Throws only if `spawn` itself fails (binary not\n * on PATH, permission denied).\n */\n run(pm: Pm, cwd: string): Promise<{ readonly code: number }>;\n}\n\nexport const defaultInstaller: Installer = {\n run: (pm, cwd) =>\n new Promise((resolve, reject) => {\n const child = spawn(pm, [\"install\"], { cwd, stdio: \"inherit\" });\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolve({ code: code ?? 1 }));\n }),\n};\n","/**\n * Bolt-on agent-rules writer. The CLI enables this by default for\n * existing wrangler projects and lets users opt out with\n * `--no-agent-rules`. It drops a delimited block that tells the user's\n * AI agent (Claude / Cursor / Copilot) that\n * `node_modules/@gusto/baerly-storage/dist/API.md` is the canonical API\n * surface and that the patterns those agents' training data is densest\n * with (Postgres/Prisma/Drizzle, Mongo, Firebase) don't apply.\n *\n * Scaffolded apps already get this via the per-template `AGENTS.md`\n * shipped by `scaffold()`. This module is for the bolt-on path —\n * `pnpm create @gusto/baerly-storage@latest .` in an existing wrangler\n * project — where no template file is copied.\n *\n * Target detection (first match wins):\n * 1. `.claude/rules/` exists → write `.claude/rules/baerly.md`.\n * 2. `AGENTS.md` exists at repo root → append a delimited block.\n * 3. `.cursor/rules/` exists → write `.cursor/rules/baerly.md`.\n * 4. None of the above → create `AGENTS.md` at repo root.\n *\n * Idempotent: a second run with the same target replaces the\n * delimited block in place rather than duplicating it.\n */\n\nimport { constants } from \"node:fs\";\nimport { mkdir, readFile, writeFile, access, stat } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\n\nconst BLOCK_START = \"<!-- baerly:start -->\";\nconst BLOCK_END = \"<!-- baerly:end -->\";\n\n/**\n * The literal block content emitted into the chosen target file.\n * Wording mirrors the per-template `AGENTS.md` preamble shipped by\n * `scaffold()` so an agent dropped into a bolt-on repo gets the\n * same orientation a scaffolded-app agent gets.\n *\n * Wrapped in `BLOCK_START` / `BLOCK_END` so a second run replaces\n * in place.\n */\nconst AGENT_RULES_BLOCK = `${BLOCK_START}\n## @gusto/baerly-storage\n\nThis repo uses @gusto/baerly-storage. Before writing or modifying storage code:\n\n- Read **\\`node_modules/@gusto/baerly-storage/dist/API.md\\`** — public-API\n quickref. Every method, every error code, every example. If a\n pattern you want to use is not here, it does not exist in baerly.\n- Common mistakes keyed by the exact error string live in\n \\`node_modules/@gusto/baerly-storage/dist/RECIPES.md\\`.\n- Type contracts live in \\`node_modules/@gusto/baerly-storage/dist/*.d.ts\\`.\n The whole API is \\`Db\\`, \\`Collection<T>\\`, \\`Query<T>\\`, and \\`Predicate<T>\\`.\n\nAnti-patterns that compile but are wrong:\n\n- \\`db.collection(...).insertOne(...)\\` — no such method. Use\n \\`db.collection(...).insert(...)\\`.\n- \\`.useIndex(\"name\")\\` — does not exist. Declared \\`indexes\\` do not\n change how a read runs; every read scans the collection.\n- \\`z.string().nullable()\\` — \\`DocumentValue\\` excludes \\`null\\`. Use\n \\`.optional()\\`; \\`null\\` in update patches is the RFC 7386 deletion\n sentinel.\n- SQL strings, raw \\`WHERE\\` clauses — the API is a method-chain\n only: \\`.where({ field: value }).all()\\` (object literal, equality)\n or \\`.where(q => q.gte(\"field\", n)).all()\\` (callback DSL,\n operators: \\`eq\\` / \\`gt\\` / \\`gte\\` / \\`lt\\` / \\`lte\\` / \\`in\\`).\n- Paging or cursor-iterating \\`.all()\\` — there is no offset, page or\n cursor API. Bound every read instead: scope it with\n \\`.where(...)\\` and cap it with \\`.limit(n)\\` (plus \\`.order(...)\\` for a\n stable top N). Each read still folds the whole collection, so a limit\n caps the rows returned, not the work done.\n${BLOCK_END}\n`;\n\ntype AgentRulesAction = \"created\" | \"appended\" | \"replaced\";\n\nexport interface AgentRulesResult {\n /** Absolute path of the file written. */\n readonly path: string;\n readonly action: AgentRulesAction;\n}\n\n/**\n * Target-file resolution. Exported for tests; callers should use\n * `writeAgentRulesBlock` directly.\n */\ninterface AgentRulesTarget {\n /** Absolute path. */\n readonly path: string;\n /**\n * `dedicated` → write a fresh file owned entirely by us (we are\n * inside `.claude/rules/` or `.cursor/rules/`). `shared` → append\n * to / replace inside a file the user may also edit (root\n * `AGENTS.md`).\n */\n readonly mode: \"dedicated\" | \"shared\";\n}\n\nconst fileExists = async (path: string): Promise<boolean> => {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n};\n\nconst dirExists = async (path: string): Promise<boolean> => {\n try {\n const s = await stat(path);\n return s.isDirectory();\n } catch {\n return false;\n }\n};\n\nconst detectAgentRulesTarget = async (outDir: string): Promise<AgentRulesTarget> => {\n if (await dirExists(resolve(outDir, \".claude\", \"rules\"))) {\n return { path: resolve(outDir, \".claude\", \"rules\", \"baerly.md\"), mode: \"dedicated\" };\n }\n if (await fileExists(resolve(outDir, \"AGENTS.md\"))) {\n return { path: resolve(outDir, \"AGENTS.md\"), mode: \"shared\" };\n }\n if (await dirExists(resolve(outDir, \".cursor\", \"rules\"))) {\n return { path: resolve(outDir, \".cursor\", \"rules\", \"baerly.md\"), mode: \"dedicated\" };\n }\n return { path: resolve(outDir, \"AGENTS.md\"), mode: \"shared\" };\n};\n\n/**\n * `Indices` plural intentionally: returns the indices of the first\n * START and the matching END so callers can slice surrounding\n * content cleanly. Returns null when the file has no managed block.\n */\nconst findBlockRange = (text: string): { start: number; end: number } | null => {\n const start = text.indexOf(BLOCK_START);\n if (start === -1) {\n return null;\n }\n const endTag = text.indexOf(BLOCK_END, start + BLOCK_START.length);\n if (endTag === -1) {\n return null;\n }\n return { start, end: endTag + BLOCK_END.length };\n};\n\nexport const writeAgentRulesBlock = async (outDir: string): Promise<AgentRulesResult> => {\n const target = await detectAgentRulesTarget(outDir);\n\n if (target.mode === \"dedicated\") {\n // .claude/rules/ or .cursor/rules/ — we own the whole file.\n // First run: `created`. Second run: `replaced` (idempotent\n // overwrite is byte-identical since the block constant is the\n // whole file).\n await mkdir(dirname(target.path), { recursive: true });\n const existed = await fileExists(target.path);\n await writeFile(target.path, AGENT_RULES_BLOCK, \"utf8\");\n return { path: target.path, action: existed ? \"replaced\" : \"created\" };\n }\n\n // Shared mode: AGENTS.md at repo root. Three sub-cases.\n if (!(await fileExists(target.path))) {\n await writeFile(target.path, AGENT_RULES_BLOCK, \"utf8\");\n return { path: target.path, action: \"created\" };\n }\n\n const existing = await readFile(target.path, \"utf8\");\n const range = findBlockRange(existing);\n if (range !== null) {\n const before = existing.slice(0, range.start);\n const after = existing.slice(range.end);\n // Drop the leading newline of our block when the preceding text\n // already ends with one — keeps replace byte-identical to the\n // append case.\n const trimmedBlock = before.endsWith(\"\\n\")\n ? AGENT_RULES_BLOCK.replace(/\\n$/, \"\")\n : `\\n${AGENT_RULES_BLOCK.replace(/\\n$/, \"\")}`;\n await writeFile(target.path, `${before}${trimmedBlock}${after}`, \"utf8\");\n return { path: target.path, action: \"replaced\" };\n }\n\n // Append. Ensure the user's existing content is byte-identical\n // before the appended block: introduce a single blank-line gap\n // when the existing file doesn't already end with `\\n\\n`.\n let gap: string;\n if (existing.endsWith(\"\\n\\n\")) {\n gap = \"\";\n } else if (existing.endsWith(\"\\n\")) {\n gap = \"\\n\";\n } else {\n gap = \"\\n\\n\";\n }\n await writeFile(target.path, `${existing}${gap}${AGENT_RULES_BLOCK}`, \"utf8\");\n return { path: target.path, action: \"appended\" };\n};\n","/**\n * The wrangler bolt-on flow for `create-baerly-storage`. Runs when `runner.ts`\n * detects an existing `wrangler.jsonc` in the resolved `outDir` — the\n * user has a Cloudflare Worker project already and wants to add\n * baerly. No template copy. Patches the mergeable files\n * (`wrangler.jsonc`, `.dev.vars`, `.gitignore`, `package.json`),\n * writes `baerly.config.ts` (skip-if-exists), and returns the\n * worker-entry snippet for the caller to print.\n *\n * Mirrors Convex's `npx convex dev` philosophy: structured config is\n * fair game; user code (`src/index.ts`) is sacred — printed, never\n * written.\n */\n\nimport { constants } from \"node:fs\";\nimport { readFile, writeFile, appendFile, access } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport type { BaerlyAppConfig } from \"@baerly/server\";\nimport { patchWranglerJsonc, readWranglerName, readWranglerMain } from \"@baerly/cli/wrangler-patch\";\nimport { renderWorkerEntrySnippet } from \"./init-snippet.ts\";\nimport { detectPm, type Pm } from \"./pm-detect.ts\";\nimport { defaultInstaller, type Installer } from \"./install.ts\";\nimport { writeAgentRulesBlock, type AgentRulesResult } from \"./agent-rules.ts\";\n\nconst DEV_SHARED_SECRET = \"dev-shared-secret\";\n\n// Lines that, if present literally in .gitignore, are treated as \"the user\n// already has a story for env-var files.\" We don't add a separate .dev.vars\n// entry in that case — we trust their convention. (NOT gitignore glob semantics.)\nconst GITIGNORE_DEV_VARS_ALIASES = new Set([\n \".dev.vars\",\n \".dev.vars*\",\n \".env*.local\",\n \"*.local\",\n \".env\",\n]);\n\nexport interface BoltOnOptions {\n readonly outDir: string;\n readonly tenant: string;\n readonly app?: string;\n readonly force?: boolean;\n readonly runInstall?: boolean;\n readonly pm?: Pm;\n readonly installer?: Installer;\n /**\n * When `true`, drop a delimited \"this repo uses @gusto/baerly-storage\"\n * block telling the user's AI agent where the canonical API\n * surface lives. The programmatic helper is opt-in; the CLI bolt-on\n * path passes `true` by default unless `--no-agent-rules` is set.\n * See `agent-rules.ts` for the target-detection chain and the\n * literal block content.\n */\n readonly agentRules?: boolean;\n}\n\nexport interface BoltOnResult {\n readonly app: string;\n readonly tenant: string;\n readonly changes: readonly string[];\n readonly snippet: string;\n readonly snippetTarget: string;\n readonly nextSteps: readonly string[];\n /** Present iff `opts.agentRules === true`. */\n readonly agentRules?: AgentRulesResult;\n}\n\nconst configTemplate = (app: string, tenant: string): string => {\n const cfg = {\n app,\n tenant,\n target: \"cloudflare\",\n auth: \"none\",\n collections: {},\n } as const satisfies BaerlyAppConfig;\n return `import { defineConfig } from \"@gusto/baerly-storage/config\";\n\nexport default defineConfig(${JSON.stringify(cfg, null, 2)});\n`;\n};\n\nconst gitignoreCovers = (text: string, line: string): boolean => {\n const lines = text.split(\"\\n\").map((l) => l.trim());\n return lines.some((l) => GITIGNORE_DEV_VARS_ALIASES.has(l) || l === line);\n};\n\nconst fileExists = async (path: string): Promise<boolean> => {\n try {\n await access(path, constants.F_OK);\n return true;\n } catch {\n return false;\n }\n};\n\nconst appendBaerlyStorageDep = async (pkgJsonPath: string, changes: string[]): Promise<void> => {\n const raw = await readFile(pkgJsonPath, \"utf8\");\n let pkg: { dependencies?: Record<string, string> };\n try {\n pkg = JSON.parse(raw) as { dependencies?: Record<string, string> };\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `create-baerly-storage bolt-on: ${pkgJsonPath} is not valid JSON — ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n pkg.dependencies = pkg.dependencies ?? {};\n if (pkg.dependencies[\"@gusto/baerly-storage\"] !== undefined) {\n return;\n }\n pkg.dependencies[\"@gusto/baerly-storage\"] = \"*\";\n await writeFile(pkgJsonPath, `${JSON.stringify(pkg, null, 2)}\\n`, \"utf8\");\n changes.push(\"package.json: added @gusto/baerly-storage dependency\");\n};\n\nexport const boltOnExistingWrangler = async (opts: BoltOnOptions): Promise<BoltOnResult> => {\n const wranglerPath = resolve(opts.outDir, \"wrangler.jsonc\");\n if (!(await fileExists(wranglerPath))) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `create-baerly-storage bolt-on: ${wranglerPath} missing — bolt-on mode requires wrangler.jsonc`,\n );\n }\n const wranglerSource = await readFile(wranglerPath, \"utf8\");\n const detectedName = readWranglerName(wranglerSource);\n const detectedMain = readWranglerMain(wranglerSource) ?? \"src/index.ts\";\n\n const app = opts.app ?? detectedName;\n if (typeof app !== \"string\" || app.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"create-baerly-storage bolt-on: --app=<name> is required (no wrangler.jsonc:name to infer from)\",\n );\n }\n\n const changes: string[] = [];\n\n const patch = patchWranglerJsonc(\n wranglerSource,\n { binding: \"BUCKET\", bucket_name: app },\n { APP: app, TENANT: opts.tenant },\n );\n if (patch.changes.length > 0) {\n await writeFile(wranglerPath, patch.text, \"utf8\");\n for (const c of patch.changes) {\n changes.push(`wrangler.jsonc: ${c}`);\n }\n }\n\n const devVarsPath = resolve(opts.outDir, \".dev.vars\");\n if (!(await fileExists(devVarsPath))) {\n await writeFile(devVarsPath, `SHARED_SECRET=${DEV_SHARED_SECRET}\\n`, \"utf8\");\n changes.push(\".dev.vars: seeded SHARED_SECRET (dev-only placeholder; replace before deploy)\");\n }\n\n const gitignorePath = resolve(opts.outDir, \".gitignore\");\n let gitignoreText = \"\";\n if (await fileExists(gitignorePath)) {\n gitignoreText = await readFile(gitignorePath, \"utf8\");\n }\n if (!gitignoreCovers(gitignoreText, \".dev.vars\")) {\n const suffix = gitignoreText.length === 0 || gitignoreText.endsWith(\"\\n\") ? \"\" : \"\\n\";\n await appendFile(gitignorePath, `${suffix}.dev.vars\\n`, \"utf8\");\n changes.push(\".gitignore: added .dev.vars\");\n }\n\n const configPath = resolve(opts.outDir, \"baerly.config.ts\");\n const configExists = await fileExists(configPath);\n if (!configExists || opts.force === true) {\n await writeFile(configPath, configTemplate(app, opts.tenant), \"utf8\");\n changes.push(`baerly.config.ts: ${configExists ? \"rewrote\" : \"wrote\"}`);\n }\n\n const pkgJsonPath = resolve(opts.outDir, \"package.json\");\n if (await fileExists(pkgJsonPath)) {\n await appendBaerlyStorageDep(pkgJsonPath, changes);\n }\n\n let agentRules: AgentRulesResult | undefined;\n if (opts.agentRules === true) {\n agentRules = await writeAgentRulesBlock(opts.outDir);\n const relPath = agentRules.path.startsWith(opts.outDir)\n ? agentRules.path.slice(opts.outDir.length + 1)\n : agentRules.path;\n changes.push(`${relPath}: ${agentRules.action} agent-rules block`);\n }\n\n if (opts.runInstall === true) {\n const pm = opts.pm ?? detectPm();\n const installer = opts.installer ?? defaultInstaller;\n await installer.run(pm, opts.outDir);\n changes.push(`${pm} install`);\n }\n\n const snippet = renderWorkerEntrySnippet({\n tenant: opts.tenant,\n wranglerMain: detectedMain,\n });\n\n return {\n app,\n tenant: opts.tenant,\n changes,\n snippet,\n snippetTarget: detectedMain,\n nextSteps: [\n `Paste the snippet above into ${detectedMain}, replacing the stock handler.`,\n `Before deploy: \\`wrangler secret put SHARED_SECRET\\` (the .dev.vars value is dev-only).`,\n ],\n ...(agentRules !== undefined && { agentRules }),\n };\n};\n","/**\n * `create-baerly-storage` command logic — citty `defineCommand` plus the\n * programmatic `runCreateBaerly` entry consumed by tests. The bin\n * shim at `./index.ts` imports `main` from here and invokes citty's\n * `runMain`. Tests import `runCreateBaerly` so they can drive the\n * CLI in-process without `runMain` calling `process.exit` inside\n * vitest.\n *\n * That `npm create` invocation is the **post-publish** form; until\n * the package ships to npm, stage locally from a clone via\n * `pnpm pack` + `pnpm dlx file:.../create-baerly-0.1.0.tgz` — see\n * the repo `README.md` Quick Start.\n *\n * Citty arg shape matches `@baerly/cli`'s `defineCommand` pattern\n * (see `packages/cli/src/init.ts`).\n *\n * Two flows live here:\n * - **Interactive wizard** — enters `runWizard` from `./prompts.ts`\n * when stdin is a TTY *and* `--json` is not set *and* either\n * `projectName` or `target` was omitted.\n * - **Flag-driven** — unchanged: CI, agents, piped stdin, and any\n * TTY invocation with `--json` keep the existing behavior and\n * the existing JSON envelope shape (part of the agent contract).\n */\nimport { defineCommand, parseArgs, type ArgsDef, type ParsedArgs } from \"citty\";\nimport { outro } from \"@clack/prompts\";\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { styleText } from \"node:util\";\nimport { version } from \"../package.json\" with { type: \"json\" };\nimport { runWizard } from \"./prompts.ts\";\nimport { type Addon, KNOWN_ADDONS, scaffold } from \"./scaffold.ts\";\nimport { boltOnExistingWrangler } from \"./bolt-on.ts\";\nimport { defaultInstaller, type Installer } from \"./install.ts\";\nimport { detectPm, probePmVersion } from \"./pm-detect.ts\";\nimport { defaultGitRunner, type GitRunner, initRepoAndCommit } from \"./git.ts\";\n\nexport const CREATE_BAERLY_ARGS = {\n projectName: {\n type: \"positional\",\n description: \"Output directory name (or '.' to scaffold into the current directory)\",\n // Optional at the citty layer so a bare `create-baerly-storage` on a\n // TTY can fall into the wizard. The flag-driven branch below\n // re-validates when wizard mode is suppressed (non-TTY / --json).\n required: false,\n valueHint: \"name\",\n },\n target: {\n type: \"enum\",\n options: [\"cloudflare\", \"node\"],\n description: 'Deploy target — \"cloudflare\" or \"node\".',\n // Optional at the citty layer so a bare `create-baerly-storage` on a\n // TTY can fall into the wizard. The flag-driven branch below\n // re-validates when wizard mode is suppressed (non-TTY / --json).\n required: false,\n },\n starter: {\n type: \"enum\",\n options: [\"minimal\", \"react\"],\n description: 'Starter template — \"minimal\" (default) or \"react\".',\n },\n tenant: {\n type: \"string\",\n description: 'Default tenant pin (default \"default\").',\n valueHint: \"string\",\n },\n domain: {\n type: \"string\",\n description: \"Custom domain for the deployed service.\",\n valueHint: \"host\",\n },\n install: {\n type: \"boolean\",\n description: \"Run <pm> install after writing files (default false).\",\n },\n force: {\n type: \"boolean\",\n description:\n \"In bolt-on mode, overwrite an existing baerly.config.ts (no-op in scaffold mode).\",\n },\n git: {\n type: \"boolean\",\n description:\n \"Initialise a git repo + create the initial commit after scaffold (default true in wizard, false in flag-driven mode). Negate with --no-git.\",\n },\n with: {\n type: \"string\",\n description:\n 'Comma-separated add-ons. Scaffold mode: \"docker\" (requires --target=node). ' +\n \"The bolt-on AGENTS.md block is its own default-on flag — see --agent-rules.\",\n valueHint: \"docker\",\n },\n \"agent-rules\": {\n type: \"boolean\",\n description:\n \"Bolt-on mode: write/refresh the AGENTS.md router pointing at the baerly API (default true; negate with --no-agent-rules). Ignored in scaffold mode.\",\n },\n pm: {\n type: \"string\",\n description: 'Override package manager — \"npm\", \"pnpm\", or \"yarn\".',\n valueHint: \"pm\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit JSON envelope to stdout (success) or stderr (error).\",\n },\n} as const satisfies ArgsDef;\n\nconst resolveOutDir = (projectName: string): string =>\n projectName === \".\" ? process.cwd() : resolve(process.cwd(), projectName);\n\ninterface DispatchBoltOnOpts {\n readonly outDir: string;\n readonly tenant: string;\n readonly force: boolean;\n readonly install: boolean;\n readonly pm: \"npm\" | \"pnpm\" | \"yarn\" | undefined;\n readonly json: boolean;\n readonly isInteractive: boolean;\n readonly installer: Installer | undefined;\n readonly agentRules: boolean;\n}\n\nconst dispatchBoltOn = async (opts: DispatchBoltOnOpts): Promise<number> => {\n try {\n const result = await boltOnExistingWrangler({\n outDir: opts.outDir,\n tenant: opts.tenant,\n ...(opts.force && { force: true }),\n runInstall: opts.install,\n ...(opts.pm !== undefined && { pm: opts.pm }),\n ...(opts.installer !== undefined && { installer: opts.installer }),\n ...(opts.agentRules && { agentRules: true }),\n });\n if (opts.json) {\n process.stdout.write(\n `${JSON.stringify({\n result: {\n command: \"create-baerly-storage\",\n status: \"ok\",\n mode: \"bolt-on\",\n outDir: opts.outDir,\n app: result.app,\n tenant: result.tenant,\n changes: result.changes,\n snippet: result.snippet,\n snippetTarget: result.snippetTarget,\n nextSteps: result.nextSteps,\n ...(result.agentRules !== undefined && { agentRules: result.agentRules }),\n },\n })}\\n`,\n );\n } else if (opts.isInteractive) {\n const changesBlock =\n result.changes.length === 0\n ? \" (no changes — already bolted on)\"\n : result.changes.map((c) => ` ${c}`).join(\"\\n\");\n outro(\n `${styleText(\"green\", \"✓\")} bolted baerly onto ${opts.outDir}\\n\\n` +\n `Changes:\\n${changesBlock}\\n\\n` +\n `Paste this into ${result.snippetTarget}, replacing the stock handler:\\n\\n` +\n result.snippet +\n `\\nNext steps:\\n` +\n result.nextSteps.map((s) => ` ${s}`).join(\"\\n\"),\n );\n } else {\n process.stdout.write(`${styleText(\"green\", \"✓\")} bolted baerly onto ${opts.outDir}\\n`);\n if (result.changes.length > 0) {\n process.stdout.write(`\\n Changes:\\n`);\n for (const c of result.changes) {\n process.stdout.write(` ${c}\\n`);\n }\n }\n process.stdout.write(\n `\\n Paste this into ${result.snippetTarget}, replacing the stock handler:\\n\\n`,\n );\n process.stdout.write(result.snippet);\n process.stdout.write(`\\n Next steps:\\n`);\n for (const s of result.nextSteps) {\n process.stdout.write(` ${s}\\n`);\n }\n process.stdout.write(\"\\n\");\n }\n return 0;\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (opts.json) {\n process.stderr.write(\n `${JSON.stringify({ error: { code: \"InvalidConfig\", message: msg, command: \"create-baerly-storage\" } })}\\n`,\n );\n } else {\n process.stderr.write(\n `${styleText(\"red\", \"create-baerly-storage:\", { stream: process.stderr })} ${msg}\\n`,\n );\n }\n return 1;\n }\n};\n\nconst handleCreateBaerly = async (\n args: ParsedArgs<typeof CREATE_BAERLY_ARGS>,\n opts: { readonly installer?: Installer; readonly gitRunner?: GitRunner } = {},\n): Promise<number> => {\n const jsonMode = args.json === true;\n try {\n const isInteractive = process.stdin.isTTY === true && !jsonMode;\n const wantWizard =\n isInteractive && (args.projectName === undefined || args.target === undefined);\n // Parse `--with=docker,…` early so both the flag-driven and\n // wizard-driven paths can use the same parsed value. Unknown\n // add-on names reject here with a list of valid choices.\n let withAddonsFromFlag: readonly Addon[] | undefined;\n if (args.with !== undefined) {\n const parts = args.with\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n const seen = new Set<Addon>();\n for (const p of parts) {\n if (!(KNOWN_ADDONS as readonly string[]).includes(p)) {\n throw new Error(\n `Unknown add-on ${JSON.stringify(p)}. Available add-ons: ${KNOWN_ADDONS.join(\", \")}.`,\n );\n }\n seen.add(p as Addon);\n }\n withAddonsFromFlag = [...seen];\n }\n let projectName: string;\n let target: \"cloudflare\" | \"node\";\n let starter: \"minimal\" | \"react\";\n let withAddons: readonly Addon[];\n let install: boolean;\n let git: boolean;\n if (wantWizard) {\n const w = await runWizard({\n projectName: args.projectName,\n target: args.target,\n starter: args.starter,\n withAddons: withAddonsFromFlag,\n install: args.install,\n git: args.git,\n ...(args.tenant !== undefined && { tenant: args.tenant }),\n });\n if (w.mode === \"bolt-on\") {\n return await dispatchBoltOn({\n outDir: resolveOutDir(w.projectName),\n tenant: w.tenant,\n force: args.force === true,\n install: w.install,\n pm: args.pm as \"npm\" | \"pnpm\" | \"yarn\" | undefined,\n json: jsonMode,\n isInteractive,\n installer: opts.installer,\n agentRules: args[\"agent-rules\"] !== false,\n });\n }\n projectName = w.projectName;\n target = w.target;\n starter = w.starter;\n withAddons = w.withAddons;\n install = w.install;\n git = w.git;\n } else {\n if (args.projectName === undefined) {\n throw new Error(\"projectName is required (positional)\");\n }\n projectName = args.projectName;\n const outDir = resolveOutDir(projectName);\n if (args.target === \"node\" && existsSync(resolve(outDir, \"wrangler.jsonc\"))) {\n throw new Error(\n \"create-baerly-storage: detected wrangler.jsonc but --target=node was passed. \" +\n \"Bolt-on only supports Cloudflare. Remove --target=node, or move out of this directory to scaffold a Node app.\",\n );\n }\n if (existsSync(resolve(outDir, \"wrangler.jsonc\"))) {\n return await dispatchBoltOn({\n outDir,\n tenant: args.tenant ?? \"default\",\n force: args.force === true,\n install: args.install === true,\n pm: args.pm as \"npm\" | \"pnpm\" | \"yarn\" | undefined,\n json: jsonMode,\n isInteractive,\n installer: opts.installer,\n agentRules: args[\"agent-rules\"] !== false,\n });\n }\n if (args.target === undefined) {\n throw new Error(`--target is required when not running in wizard mode (got undefined)`);\n }\n target = args.target;\n // Flag-driven path: scaffold() defaults to \"minimal\" internally,\n // so the explicit fallback here keeps the local `starter` type\n // tight without changing observed behavior.\n starter = args.starter ?? \"minimal\";\n withAddons = withAddonsFromFlag ?? [];\n // Flag-driven path: no wizard, so default to false unless the user\n // explicitly passed --install. Today's CI/agent callers see no\n // behavior change because they never pass --install.\n install = args.install === true;\n // Same shape as `install`: in flag-driven mode the default is off\n // so CI / agents see no behavior change unless they opt in with\n // `--git`. The wizard branch defaults to `true` because a fresh\n // scaffold without a baseline commit is a strict downgrade for\n // anyone iterating against `git diff`.\n git = args.git === true;\n }\n // Cross-field validation: each add-on's mode/target constraint\n // is checked here. Control only reaches this block in scaffold\n // mode — bolt-on dispatch already returned above.\n if (withAddons.includes(\"docker\") && target !== \"node\") {\n throw new Error(\n `--with=docker only applies to --target=node. The Docker add-on adds a ` +\n `Dockerfile to the Node template. Use --target=node --with=docker, or ` +\n `drop --with=docker to scaffold for --target=${target}.`,\n );\n }\n if (withAddons.includes(\"agent-rules\")) {\n throw new Error(\n `--with=agent-rules is unnecessary in scaffold mode. Bolt-on mode writes ` +\n `agent rules by default and supports --no-agent-rules to opt out. ` +\n `Scaffolded apps already include an AGENTS.md preamble — drop --with=agent-rules.`,\n );\n }\n const result = await scaffold({\n projectName,\n target,\n starter,\n ...(args.tenant !== undefined && { tenant: args.tenant }),\n ...(args.domain !== undefined && { domain: args.domain }),\n ...(args.pm !== undefined && { pm: args.pm as \"npm\" | \"pnpm\" | \"yarn\" }),\n ...(withAddons.length > 0 && { withAddons }),\n });\n // Resolve the package manager once; both the git commit body and\n // the optional install step read it.\n const pm = (args.pm as \"npm\" | \"pnpm\" | \"yarn\" | undefined) ?? detectPm();\n // Git init runs BEFORE install so the initial commit captures the\n // scaffold contents only — `node_modules/` is gitignored by the\n // template, but committing pre-install also keeps `git diff` from\n // the start matching exactly what `scaffold()` wrote.\n if (git) {\n const gitRunner = opts.gitRunner ?? defaultGitRunner;\n const pmVersion = probePmVersion(pm);\n const outcome = initRepoAndCommit(\n {\n outDir: result.outDir,\n cliVersion: result.cliVersion,\n appName: result.appName,\n target,\n starter,\n pm,\n ...(pmVersion !== undefined && { pmVersion }),\n },\n gitRunner,\n );\n if (!outcome.initialized && outcome.reason !== \"already-in-repo\") {\n // `already-in-repo` is a *silent* skip — the user opted into\n // scaffold-in-place inside an existing repo, so init would be\n // an error. Every other skip is worth surfacing so the user\n // knows the scaffold succeeded but the git step did not.\n const detail =\n outcome.message === undefined || outcome.message.length === 0\n ? \"\"\n : `: ${outcome.message}`;\n let hint = `${outcome.reason}${detail}`;\n if (outcome.reason === \"git-not-available\") {\n hint = `git is not installed; install it then run \\`git init && git add . && git commit -m '…'\\` in ${result.outDir}.`;\n } else if (outcome.reason === \"no-identity\") {\n 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.`;\n }\n process.stderr.write(\n `${styleText(\"yellow\", \"create-baerly-storage:\", { stream: process.stderr })} git init skipped — ${hint}\\n`,\n );\n }\n }\n if (install) {\n const installer = opts.installer ?? defaultInstaller;\n const { code } = await installer.run(pm, result.outDir);\n if (code !== 0) {\n process.stderr.write(\n `${styleText(\"yellow\", \"create-baerly-storage:\", { stream: process.stderr })} install exited with code ${code}. ` +\n `Run \\`${pm} install\\` in ${result.outDir} manually.\\n`,\n );\n }\n }\n if (jsonMode) {\n process.stdout.write(\n `${JSON.stringify({\n result: {\n command: \"create-baerly-storage\",\n status: \"ok\",\n outDir: result.outDir,\n filesWritten: result.filesWritten.length,\n nextSteps: result.nextSteps,\n },\n })}\\n`,\n );\n } else if (isInteractive) {\n outro(\n `${styleText(\"green\", \"✓\")} ${result.outDir}\\n` +\n `\\n Next steps:\\n` +\n result.nextSteps.map((s) => ` ${s}`).join(\"\\n\"),\n );\n } else {\n // Non-TTY, non-JSON: keep the existing plaintext output\n // bit-for-bit so any scripts parsing it don't break.\n process.stdout.write(`${styleText(\"green\", \"✓\")} scaffolded ${result.outDir}\\n`);\n process.stdout.write(`\\n Next steps:\\n`);\n for (const s of result.nextSteps) {\n process.stdout.write(` ${s}\\n`);\n }\n process.stdout.write(\"\\n\");\n }\n return 0;\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (jsonMode) {\n process.stderr.write(\n `${JSON.stringify({ error: { code: \"InvalidConfig\", message: msg, command: \"create-baerly-storage\" } })}\\n`,\n );\n } else {\n process.stderr.write(\n `${styleText(\"red\", \"create-baerly-storage:\", { stream: process.stderr })} ${msg}\\n`,\n );\n }\n return 1;\n }\n};\n\nexport const main = defineCommand({\n meta: {\n name: \"create-baerly-storage\",\n version,\n description: \"Scaffold a new baerly app (Cloudflare Worker or self-hosted Node).\",\n },\n args: CREATE_BAERLY_ARGS,\n run: async ({ args }) => {\n const code = await handleCreateBaerly(args);\n if (code !== 0) {\n process.exit(code);\n }\n },\n});\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runCreateBaerly = async (\n argv: readonly string[],\n opts: { readonly installer?: Installer; readonly gitRunner?: GitRunner } = {},\n): Promise<number> => {\n let parsed: ParsedArgs<typeof CREATE_BAERLY_ARGS>;\n try {\n parsed = parseArgs<typeof CREATE_BAERLY_ARGS>(argv as string[], CREATE_BAERLY_ARGS);\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n if (argv.includes(\"--json\")) {\n process.stderr.write(\n `${JSON.stringify({ error: { code: \"InvalidConfig\", message: msg, command: \"create-baerly-storage\" } })}\\n`,\n );\n } else {\n process.stderr.write(\n `${styleText(\"red\", \"create-baerly-storage:\", { stream: process.stderr })} ${msg}\\n`,\n );\n }\n return 1;\n }\n return handleCreateBaerly(parsed, opts);\n};\n","/**\n * `create-baerly-storage` bin entry. Imports the citty command from `./runner.ts`\n * and dispatches via an inline `runBin` shim. Kept as a thin shim so\n * the runner module has no import-time side effects — tests can\n * import `runCreateBaerly` from `./runner.ts` directly without citty\n * running and calling `process.exit` inside vitest.\n *\n * The shim mirrors the shape of `@baerly/cli`'s `bin-runner.ts`\n * (same `--help` / `--version` interception, same `CLIError →\n * InvalidConfig` translation). Inlined here rather than imported\n * cross-package because `create-baerly-storage` is a separate publishable\n * with its own dependency surface — the cross-package import\n * overhead beats the dedup at this scale.\n */\nimport { runCommand, showUsage, type CommandMeta, type Resolvable } from \"citty\";\nimport { styleText } from \"node:util\";\nimport { main } from \"./runner.ts\";\n\nconst resolve = async <T>(v: Resolvable<T>): Promise<T> => {\n if (typeof v === \"function\") {\n return (v as () => T | Promise<T>)();\n }\n return v;\n};\n\nconst writeError = (json: boolean, code: string, message: string): void => {\n if (json) {\n process.stderr.write(\n `${JSON.stringify({ error: { code, message, command: \"create-baerly-storage\" } })}\\n`,\n );\n } else {\n process.stderr.write(\n `${styleText(\"red\", \"create-baerly-storage:\", { stream: process.stderr })} ${code}: ${message}\\n`,\n );\n }\n};\n\nconst argv = process.argv.slice(2);\nconst wantJson = argv.includes(\"--json\");\n\nconst run = async (): Promise<void> => {\n if (argv.includes(\"--help\") || argv.includes(\"-h\")) {\n // create-baerly-storage has no subCommands, so the top-level command is\n // always the showUsage target.\n await showUsage(main);\n process.exit(0);\n }\n if (argv.includes(\"--version\") || argv.includes(\"-v\")) {\n const meta = (await resolve(main.meta as Resolvable<CommandMeta>)) ?? {};\n const version = meta.version;\n if (typeof version !== \"string\" || version.length === 0) {\n writeError(wantJson, \"InvalidConfig\", \"no version declared on this command\");\n process.exit(1);\n }\n process.stdout.write(`${version}\\n`);\n process.exit(0);\n }\n try {\n await runCommand(main, { rawArgs: [...argv] });\n process.exit(0);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n writeError(wantJson, \"InvalidConfig\", message);\n process.exit(1);\n }\n};\n\nvoid run();\n"],"ignoreList":[0,1,2,3,4,5,6,7,8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