@smoothbricks/cli 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAMA,wBAAsB,MAAM,CAAC,IAAI,WAAwB,GAAG,OAAO,CAAC,IAAI,CAAC,CAexE"}
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAOA,wBAAsB,MAAM,CAAC,IAAI,WAAwB,GAAG,OAAO,CAAC,IAAI,CAAC,CAexE"}
package/dist/cli.js CHANGED
@@ -3,6 +3,7 @@ import { variants } from './generate/index.js';
3
3
  import { cliPackageVersion } from './lib/cli-package.js';
4
4
  import { findRepoRoot } from './lib/run.js';
5
5
  import { resolvePrConflicts } from './pr/index.js';
6
+ import { scaffold } from './wrangler/scaffold.js';
6
7
  export async function runCli(argv = process.argv.slice(2)) {
7
8
  const program = buildProgram();
8
9
  try {
@@ -290,6 +291,14 @@ function buildProgram() {
290
291
  process.exitCode = exitCode;
291
292
  }
292
293
  });
294
+ const wrangler = program.command('wrangler').description('Cloudflare wrangler project helpers');
295
+ wrangler
296
+ .command('scaffold <project>')
297
+ .description('Write a starter scripts/prepare-env.ts (manifest-driven) and wire its nx target')
298
+ .option('--force', 'overwrite an existing scripts/prepare-env.ts')
299
+ .action(async (project, options) => {
300
+ scaffold(await findRepoRoot(), project, { force: options.force });
301
+ });
293
302
  return program;
294
303
  }
295
304
  function booleanOption(value) {
@@ -0,0 +1,89 @@
1
+ export declare function isRecord(v: unknown): v is Record<string, unknown>;
2
+ /** First `[env.<name>]` (source order; also derived from a nested `[env.<name>.*]`), or null when no env declared. */
3
+ export declare function firstWranglerEnv(toml: string): string | null;
4
+ /** True if the toml declares `[env.<env>]` (or any `[env.<env>.*]` sub-table). */
5
+ export declare function hasEnvBlock(toml: string, env: string): boolean;
6
+ /** A `[env.<env>.vars]` value, or null if unset/empty. Reads committed public config. */
7
+ export declare function getVar(toml: string, env: string, name: string): string | null;
8
+ /** Set a `[env.<env>.vars]` value (JSON-encoded), preserving any trailing comment. Throws if the key is absent (scaffold first). */
9
+ export declare function setVar(toml: string, env: string, name: string, value: string): string;
10
+ /** The id written for `[[env.<env>.kv_namespaces]]` binding, or null if absent/empty. */
11
+ export declare function getKvId(toml: string, env: string, binding: string): string | null;
12
+ /** Rewrite the `id = ...` line (value + trailing comment) of the kv_namespaces table whose binding matches. Throws if absent. */
13
+ export declare function setKvId(toml: string, env: string, binding: string, id: string, title: string): string;
14
+ /**
15
+ * Append a copy of every `[env.<from>...]` table rewritten for `<to>` (headers
16
+ * only — values copied verbatim). Throws if `<from>` is absent or `<to>` exists.
17
+ */
18
+ export declare function cloneEnvBlock(toml: string, from: string, to: string): string;
19
+ /** Blank the named `[env.<env>.vars]` values to `""` (preserving comments), skipping absent keys. */
20
+ export declare function blankEnvVars(toml: string, env: string, keys: string[]): string;
21
+ /** Blank every kv_namespaces `id` under the env to `""` (drops trailing comment; binding/name survive). */
22
+ export declare function blankKvIds(toml: string, env: string): string;
23
+ /** The database_id written for `[[env.<env>.d1_databases]]` binding, or null if absent/empty. */
24
+ export declare function getD1Id(toml: string, env: string, binding: string): string | null;
25
+ /** The `database_name` for `[[env.<env>.d1_databases]]` binding, or null. Source of truth for which DB to create/reuse. */
26
+ export declare function getD1Name(toml: string, env: string, binding: string): string | null;
27
+ /** Rewrite the `database_id = ...` line (value + trailing comment) of the d1 table whose binding matches; the name line is untouched. Throws if absent. */
28
+ export declare function setD1Id(toml: string, env: string, binding: string, id: string, name: string): string;
29
+ /** Blank every d1 `database_id` under the env to `""` (drops trailing comment; binding/name survive). */
30
+ export declare function blankD1Ids(toml: string, env: string): string;
31
+ /** Parse-guard: throws if `toml` no longer parses, so a bad edit can't be written to disk. */
32
+ export declare function assertToml(toml: string): void;
33
+ /** Persist a toml string after confirming it still parses. */
34
+ export declare function saveToml(path: string, toml: string): void;
35
+ export interface Manifest {
36
+ /** KV binding names declared under `[[env.<env>.kv_namespaces]]` (resources to provision). */
37
+ kvBindings: string[];
38
+ /** D1 binding names declared under `[[env.<env>.d1_databases]]` (resources to provision). */
39
+ d1Bindings: string[];
40
+ /** Public var names declared in `[env.<env>.vars]` (committed config). */
41
+ vars: string[];
42
+ /** Secret names declared in `.dev.vars.example` (values live on the worker, never in the repo). */
43
+ secrets: string[];
44
+ }
45
+ /** Secret NAMES from a `.dev.vars.example` file (KEY=... / KEY="..."), ignoring comments/blanks. */
46
+ export declare function parseDevVarsExample(text: string): string[];
47
+ /**
48
+ * Read the vars/secrets split for `env` from `<root>/wrangler.toml` (public var
49
+ * keys) + `<root>/.dev.vars.example` (secret names). This is the "what to prompt
50
+ * for" manifest a prepare-env script derives its work from.
51
+ */
52
+ export declare function readManifest(root: string, env: string): Manifest;
53
+ /** True if `value` looks like a PEM block (any `-----BEGIN ...-----`). */
54
+ export declare function isPem(value: string): boolean;
55
+ /** Read a `.pem` file (expanding a leading `~`) and assert it's a PEM block. Throws otherwise. */
56
+ export declare function readPemFile(path: string): string;
57
+ /** Heuristic: does this secret name suggest file input (PEM/key)? Used to preselect a file prompt — never to change semantics. */
58
+ export declare function looksLikeFileSecret(name: string): boolean;
59
+ export interface KvNamespace {
60
+ id: string;
61
+ title: string;
62
+ }
63
+ /** Best-effort ERROR line from a Bun ShellError (thrown on non-zero exit). */
64
+ export declare function errText(err: unknown): string;
65
+ /** Live KV namespaces on the account (`kv namespace list` emits a pure JSON array); `[]` when offline/unauthenticated. */
66
+ export declare function listNamespaces(cwd: string): Promise<KvNamespace[]>;
67
+ /**
68
+ * Reuse the namespace whose title exactly matches `logical`, else create it. The
69
+ * id always comes from the structured `list` JSON (create prints freeform text),
70
+ * so we re-list rather than scrape. Returns the id, or null on failure.
71
+ */
72
+ export declare function ensureNamespace(logical: string, existing: KvNamespace[], cwd: string): Promise<string | null>;
73
+ export interface D1Database {
74
+ uuid: string;
75
+ name: string;
76
+ }
77
+ /** Live D1 databases on the account (`d1 list --json`); `[]` when offline/unauthenticated. */
78
+ export declare function listD1Databases(cwd: string): Promise<D1Database[]>;
79
+ /**
80
+ * Reuse the D1 database whose name matches, else create it. The uuid comes from
81
+ * the structured `list` JSON (create prints freeform text), so we re-list rather
82
+ * than scrape. Returns the uuid, or null on failure.
83
+ */
84
+ export declare function ensureD1Database(name: string, existing: D1Database[], cwd: string): Promise<string | null>;
85
+ /** Current secret names on the worker for `env`; `[]` when none/unreachable (Cloudflare allows setting pre-deploy). */
86
+ export declare function listSecretNames(env: string, cwd: string): Promise<string[]>;
87
+ /** `wrangler secret put <name> --env <env>` piping `value` on stdin (never a CLI arg). Returns success. */
88
+ export declare function putSecret(name: string, value: string, env: string, cwd: string): Promise<boolean>;
89
+ //# sourceMappingURL=prepare-env.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prepare-env.d.ts","sourceRoot":"","sources":["../../src/wrangler/prepare-env.ts"],"names":[],"mappings":"AAyBA,wBAAgB,QAAQ,CAAC,CAAC,EAAE,OAAO,GAAG,CAAC,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAEjE;AAsDD,sHAAsH;AACtH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAK5D;AAED,kFAAkF;AAClF,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAG9D;AAED,yFAAyF;AACzF,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAK7E;AAED,oIAAoI;AACpI,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,M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AM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CASnH;AAMD,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd;AAaD,8FAA8F;AAC9F,wBAAsB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC,CAMxE;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAShH;AAMD,uHAAuH;AACvH,wBAAsB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAMjF;AAED,2GAA2G;AAC3G,wBAAsB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAOvG"}
@@ -0,0 +1,363 @@
1
+ /**
2
+ * Composable primitives for writing a project's own `prepare-env` script — the
3
+ * provisioning half of the wrangler setup flow (the `wrangler` monorepo pack owns
4
+ * the build-time half: the `wrangler-types` target + `.dev.vars.example`).
5
+ *
6
+ * `wrangler types --env-file .dev.vars.example` emits a machine-readable manifest
7
+ * that distinguishes committed public **vars** (literal-typed in `[env.<env>.vars]`)
8
+ * from **secrets** (string-typed, names in `.dev.vars.example`, values never in the
9
+ * repo). `readManifest` reads that split back so a script knows what to prompt for;
10
+ * the toml editors clone/blank/fill env blocks; the wrangler shell-outs provision.
11
+ *
12
+ * Import from a target's `scripts/prepare-env.ts`:
13
+ * import * as pe from '@smoothbricks/cli/wrangler/prepare-env';
14
+ * Scaffold a starter with: smoo wrangler scaffold <project>
15
+ *
16
+ * Prompt-agnostic by design: the module does the toml + wrangler work; the script
17
+ * brings its own prompts (e.g. @clack/prompts). Bun-only (uses `bun`'s `$`).
18
+ */
19
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
20
+ import { join } from 'node:path';
21
+ import { $ } from 'bun';
22
+ import { getStaticTOMLValue, parseTOML } from 'toml-eslint-parser';
23
+ // ── runtime narrowing (wrangler JSON is external data — no casts) ─────────────
24
+ export function isRecord(v) {
25
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
26
+ }
27
+ // ── wrangler.toml editors (CST: read via getStaticTOMLValue, write via
28
+ // node-range splice — comment/format-preserving by construction, no regex) ─────
29
+ /** All top-level tables (`[env.x]`, `[env.x.vars]`, `[[env.x.d1_databases]]`, …) — each carries `resolvedKey` (incl. array index). */
30
+ function tables(toml) {
31
+ return parseTOML(toml).body[0].body.filter((n) => n.type === 'TOMLTable');
32
+ }
33
+ /** Whole doc as a JS object (comments/format dropped — reads only). */
34
+ function tomlValue(toml) {
35
+ const value = getStaticTOMLValue(parseTOML(toml));
36
+ return isRecord(value) ? value : {};
37
+ }
38
+ function envRecord(toml, env) {
39
+ const envs = tomlValue(toml).env;
40
+ const block = isRecord(envs) ? envs[env] : undefined;
41
+ return isRecord(block) ? block : null;
42
+ }
43
+ function sameKey(a, b) {
44
+ return a.length === b.length && a.every((x, i) => x === b[i]);
45
+ }
46
+ /** The `key = value` node named `key` in a table (single-segment keys; matched by source text). */
47
+ function kvIn(toml, table, key) {
48
+ for (const kv of table.body) {
49
+ if (toml.slice(kv.key.range[0], kv.key.range[1]).trim() === key)
50
+ return kv;
51
+ }
52
+ return null;
53
+ }
54
+ /** The `<field>` KV of the `[[env.<env>.<arrayKey>]]` table whose `binding` matches, or null. */
55
+ function arrayTableKv(toml, env, arrayKey, binding, field) {
56
+ const block = envRecord(toml, env);
57
+ const rows = isRecord(block) && Array.isArray(block[arrayKey]) ? block[arrayKey] : [];
58
+ const index = rows.findIndex((r) => isRecord(r) && r.binding === binding);
59
+ if (index < 0)
60
+ return null;
61
+ const table = tables(toml).find((t) => t.kind === 'array' && sameKey(t.resolvedKey, ['env', env, arrayKey, index]));
62
+ return table ? kvIn(toml, table, field) : null;
63
+ }
64
+ function splice(toml, start, end, text) {
65
+ return toml.slice(0, start) + text + toml.slice(end);
66
+ }
67
+ /** End of the physical line containing `offset` (exclusive of the newline). */
68
+ function endOfLine(toml, offset) {
69
+ const nl = toml.indexOf('\n', offset);
70
+ return nl === -1 ? toml.length : nl;
71
+ }
72
+ /** First `[env.<name>]` (source order; also derived from a nested `[env.<name>.*]`), or null when no env declared. */
73
+ export function firstWranglerEnv(toml) {
74
+ const envs = tomlValue(toml).env;
75
+ if (!isRecord(envs))
76
+ return null;
77
+ const [first] = Object.keys(envs);
78
+ return first ?? null;
79
+ }
80
+ /** True if the toml declares `[env.<env>]` (or any `[env.<env>.*]` sub-table). */
81
+ export function hasEnvBlock(toml, env) {
82
+ const envs = tomlValue(toml).env;
83
+ return isRecord(envs) && env in envs;
84
+ }
85
+ /** A `[env.<env>.vars]` value, or null if unset/empty. Reads committed public config. */
86
+ export function getVar(toml, env, name) {
87
+ const block = envRecord(toml, env);
88
+ const vars = isRecord(block?.vars) ? block.vars : {};
89
+ const value = vars[name];
90
+ return typeof value === 'string' && value ? value : null;
91
+ }
92
+ /** Set a `[env.<env>.vars]` value (JSON-encoded), preserving any trailing comment. Throws if the key is absent (scaffold first). */
93
+ export function setVar(toml, env, name, value) {
94
+ const table = tables(toml).find((t) => sameKey(t.resolvedKey, ['env', env, 'vars']));
95
+ const kv = table ? kvIn(toml, table, name) : null;
96
+ if (!kv)
97
+ throw new Error(`vars key "${name}" not found under [env.${env}.vars]`);
98
+ return splice(toml, kv.value.range[0], kv.value.range[1], JSON.stringify(value));
99
+ }
100
+ /** The id written for `[[env.<env>.kv_namespaces]]` binding, or null if absent/empty. */
101
+ export function getKvId(toml, env, binding) {
102
+ const block = envRecord(toml, env);
103
+ const rows = isRecord(block) && Array.isArray(block.kv_namespaces) ? block.kv_namespaces : [];
104
+ for (const row of rows) {
105
+ if (isRecord(row) && row.binding === binding && typeof row.id === 'string')
106
+ return row.id || null;
107
+ }
108
+ return null;
109
+ }
110
+ /** Rewrite the `id = ...` line (value + trailing comment) of the kv_namespaces table whose binding matches. Throws if absent. */
111
+ export function setKvId(toml, env, binding, id, title) {
112
+ const kv = arrayTableKv(toml, env, 'kv_namespaces', binding, 'id');
113
+ if (!kv)
114
+ throw new Error(`kv_namespaces binding "${binding}" not found under [env.${env}]`);
115
+ return splice(toml, kv.value.range[0], endOfLine(toml, kv.value.range[1]), `${JSON.stringify(id)} # ${title}`);
116
+ }
117
+ /**
118
+ * Append a copy of every `[env.<from>...]` table rewritten for `<to>` (headers
119
+ * only — values copied verbatim). Throws if `<from>` is absent or `<to>` exists.
120
+ */
121
+ export function cloneEnvBlock(toml, from, to) {
122
+ if (!hasEnvBlock(toml, from))
123
+ throw new Error(`source [env.${from}] not found`);
124
+ if (hasEnvBlock(toml, to))
125
+ throw new Error(`target [env.${to}] already exists — blank/fill it instead`);
126
+ const cloned = tables(toml)
127
+ .filter((t) => t.resolvedKey[0] === 'env' && t.resolvedKey[1] === from)
128
+ .map((t) => {
129
+ const seg = t.key.keys[1].range; // the `<from>` segment of this table's header
130
+ const text = toml.slice(t.range[0], t.range[1]);
131
+ return text.slice(0, seg[0] - t.range[0]) + to + text.slice(seg[1] - t.range[0]);
132
+ });
133
+ return `${toml.replace(/\s*$/, '')}\n\n${cloned.join('\n\n')}\n`;
134
+ }
135
+ /** Blank the named `[env.<env>.vars]` values to `""` (preserving comments), skipping absent keys. */
136
+ export function blankEnvVars(toml, env, keys) {
137
+ const table = tables(toml).find((t) => sameKey(t.resolvedKey, ['env', env, 'vars']));
138
+ if (!table)
139
+ return toml;
140
+ const edits = keys
141
+ .map((key) => kvIn(toml, table, key))
142
+ .flatMap((kv) => (kv ? [{ start: kv.value.range[0], end: kv.value.range[1] }] : []));
143
+ return applyBlanks(toml, edits);
144
+ }
145
+ /** Blank every kv_namespaces `id` under the env to `""` (drops trailing comment; binding/name survive). */
146
+ export function blankKvIds(toml, env) {
147
+ return blankArrayField(toml, env, 'kv_namespaces', 'id');
148
+ }
149
+ /** The database_id written for `[[env.<env>.d1_databases]]` binding, or null if absent/empty. */
150
+ export function getD1Id(toml, env, binding) {
151
+ const block = envRecord(toml, env);
152
+ const rows = isRecord(block) && Array.isArray(block.d1_databases) ? block.d1_databases : [];
153
+ for (const row of rows) {
154
+ if (isRecord(row) && row.binding === binding && typeof row.database_id === 'string')
155
+ return row.database_id || null;
156
+ }
157
+ return null;
158
+ }
159
+ /** The `database_name` for `[[env.<env>.d1_databases]]` binding, or null. Source of truth for which DB to create/reuse. */
160
+ export function getD1Name(toml, env, binding) {
161
+ const block = envRecord(toml, env);
162
+ const rows = isRecord(block) && Array.isArray(block.d1_databases) ? block.d1_databases : [];
163
+ for (const row of rows) {
164
+ if (isRecord(row) && row.binding === binding && typeof row.database_name === 'string')
165
+ return row.database_name || null;
166
+ }
167
+ return null;
168
+ }
169
+ /** Rewrite the `database_id = ...` line (value + trailing comment) of the d1 table whose binding matches; the name line is untouched. Throws if absent. */
170
+ export function setD1Id(toml, env, binding, id, name) {
171
+ const kv = arrayTableKv(toml, env, 'd1_databases', binding, 'database_id');
172
+ if (!kv)
173
+ throw new Error(`d1_databases binding "${binding}" not found under [env.${env}]`);
174
+ return splice(toml, kv.value.range[0], endOfLine(toml, kv.value.range[1]), `${JSON.stringify(id)} # ${name}`);
175
+ }
176
+ /** Blank every d1 `database_id` under the env to `""` (drops trailing comment; binding/name survive). */
177
+ export function blankD1Ids(toml, env) {
178
+ return blankArrayField(toml, env, 'd1_databases', 'database_id');
179
+ }
180
+ /** Blank one field across every `[[env.<env>.<arrayKey>]]` table (value..EOL -> `""`). */
181
+ function blankArrayField(toml, env, arrayKey, field) {
182
+ const edits = tables(toml)
183
+ .filter((t) => t.kind === 'array' && t.resolvedKey[0] === 'env' && t.resolvedKey[1] === env && t.resolvedKey[2] === arrayKey)
184
+ .map((t) => kvIn(toml, t, field))
185
+ .flatMap((kv) => (kv ? [{ start: kv.value.range[0], end: endOfLine(toml, kv.value.range[1]) }] : []));
186
+ return applyBlanks(toml, edits);
187
+ }
188
+ /** Apply `""` at each range, descending so earlier offsets stay valid. */
189
+ function applyBlanks(toml, edits) {
190
+ let out = toml;
191
+ for (const e of [...edits].sort((a, b) => b.start - a.start))
192
+ out = splice(out, e.start, e.end, '""');
193
+ return out;
194
+ }
195
+ /** Parse-guard: throws if `toml` no longer parses, so a bad edit can't be written to disk. */
196
+ export function assertToml(toml) {
197
+ parseTOML(toml);
198
+ }
199
+ /** Persist a toml string after confirming it still parses. */
200
+ export function saveToml(path, toml) {
201
+ assertToml(toml);
202
+ writeFileSync(path, toml);
203
+ }
204
+ /** Secret NAMES from a `.dev.vars.example` file (KEY=... / KEY="..."), ignoring comments/blanks. */
205
+ export function parseDevVarsExample(text) {
206
+ const names = [];
207
+ for (const raw of text.split('\n')) {
208
+ const line = raw.trim();
209
+ if (!line || line.startsWith('#'))
210
+ continue;
211
+ const m = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/);
212
+ if (m)
213
+ names.push(m[1]);
214
+ }
215
+ return names;
216
+ }
217
+ /**
218
+ * Read the vars/secrets split for `env` from `<root>/wrangler.toml` (public var
219
+ * keys) + `<root>/.dev.vars.example` (secret names). This is the "what to prompt
220
+ * for" manifest a prepare-env script derives its work from.
221
+ */
222
+ export function readManifest(root, env) {
223
+ const toml = readFileSync(join(root, 'wrangler.toml'), 'utf8');
224
+ const block = envRecord(toml, env);
225
+ const varsRec = isRecord(block?.vars) ? block.vars : {};
226
+ const vars = Object.keys(varsRec);
227
+ const kvRows = isRecord(block) && Array.isArray(block.kv_namespaces) ? block.kv_namespaces : [];
228
+ const kvBindings = kvRows.flatMap((row) => (isRecord(row) && typeof row.binding === 'string' ? [row.binding] : []));
229
+ const d1Rows = isRecord(block) && Array.isArray(block.d1_databases) ? block.d1_databases : [];
230
+ const d1Bindings = d1Rows.flatMap((row) => (isRecord(row) && typeof row.binding === 'string' ? [row.binding] : []));
231
+ const examplePath = join(root, '.dev.vars.example');
232
+ const secrets = existsSync(examplePath) ? parseDevVarsExample(readFileSync(examplePath, 'utf8')) : [];
233
+ return { kvBindings, d1Bindings, vars, secrets };
234
+ }
235
+ // ── PEM (a standard, reusable) ───────────────────────────────────────────────
236
+ /** True if `value` looks like a PEM block (any `-----BEGIN ...-----`). */
237
+ export function isPem(value) {
238
+ return /-----BEGIN [A-Z ]+-----/.test(value);
239
+ }
240
+ /** Read a `.pem` file (expanding a leading `~`) and assert it's a PEM block. Throws otherwise. */
241
+ export function readPemFile(path) {
242
+ const resolved = path.replace(/^~/, process.env.HOME ?? '~');
243
+ const content = readFileSync(resolved, 'utf8');
244
+ if (!isPem(content))
245
+ throw new Error(`${path} is not a PEM (no -----BEGIN block)`);
246
+ return content;
247
+ }
248
+ /** Heuristic: does this secret name suggest file input (PEM/key)? Used to preselect a file prompt — never to change semantics. */
249
+ export function looksLikeFileSecret(name) {
250
+ return /_PEM$|_KEY$|_CERT$/.test(name);
251
+ }
252
+ function asKvNamespaces(json) {
253
+ if (!Array.isArray(json))
254
+ return [];
255
+ const out = [];
256
+ for (const row of json) {
257
+ if (isRecord(row) && typeof row.id === 'string' && typeof row.title === 'string') {
258
+ out.push({ id: row.id, title: row.title });
259
+ }
260
+ }
261
+ return out;
262
+ }
263
+ function asSecretNames(json) {
264
+ if (!Array.isArray(json))
265
+ return [];
266
+ return json.flatMap((row) => (isRecord(row) && typeof row.name === 'string' ? [row.name] : []));
267
+ }
268
+ /** Best-effort ERROR line from a Bun ShellError (thrown on non-zero exit). */
269
+ export function errText(err) {
270
+ if (!isRecord(err))
271
+ return 'unknown error';
272
+ const stderr = 'stderr' in err && err.stderr != null ? String(err.stderr) : '';
273
+ const exit = 'exitCode' in err ? String(err.exitCode) : '?';
274
+ return stderr.split('\n').find((l) => l.includes('ERROR')) ?? `exit ${exit}`;
275
+ }
276
+ /** Live KV namespaces on the account (`kv namespace list` emits a pure JSON array); `[]` when offline/unauthenticated. */
277
+ export async function listNamespaces(cwd) {
278
+ try {
279
+ return asKvNamespaces(await $ `bunx wrangler kv namespace list`.cwd(cwd).quiet().json());
280
+ }
281
+ catch {
282
+ return [];
283
+ }
284
+ }
285
+ /**
286
+ * Reuse the namespace whose title exactly matches `logical`, else create it. The
287
+ * id always comes from the structured `list` JSON (create prints freeform text),
288
+ * so we re-list rather than scrape. Returns the id, or null on failure.
289
+ */
290
+ export async function ensureNamespace(logical, existing, cwd) {
291
+ const match = existing.find((n) => n.title === logical);
292
+ if (match)
293
+ return match.id;
294
+ try {
295
+ await $ `bunx wrangler kv namespace create ${logical}`.cwd(cwd).quiet();
296
+ }
297
+ catch (err) {
298
+ return errText(err).includes('already') ? (await reList(logical, cwd)) : null;
299
+ }
300
+ return reList(logical, cwd);
301
+ }
302
+ async function reList(logical, cwd) {
303
+ return (await listNamespaces(cwd)).find((n) => n.title === logical)?.id ?? null;
304
+ }
305
+ function asD1Databases(json) {
306
+ if (!Array.isArray(json))
307
+ return [];
308
+ const out = [];
309
+ for (const row of json) {
310
+ if (isRecord(row) && typeof row.uuid === 'string' && typeof row.name === 'string') {
311
+ out.push({ uuid: row.uuid, name: row.name });
312
+ }
313
+ }
314
+ return out;
315
+ }
316
+ /** Live D1 databases on the account (`d1 list --json`); `[]` when offline/unauthenticated. */
317
+ export async function listD1Databases(cwd) {
318
+ try {
319
+ return asD1Databases(await $ `bunx wrangler d1 list --json`.cwd(cwd).quiet().json());
320
+ }
321
+ catch {
322
+ return [];
323
+ }
324
+ }
325
+ /**
326
+ * Reuse the D1 database whose name matches, else create it. The uuid comes from
327
+ * the structured `list` JSON (create prints freeform text), so we re-list rather
328
+ * than scrape. Returns the uuid, or null on failure.
329
+ */
330
+ export async function ensureD1Database(name, existing, cwd) {
331
+ const match = existing.find((d) => d.name === name);
332
+ if (match)
333
+ return match.uuid;
334
+ try {
335
+ await $ `bunx wrangler d1 create ${name}`.cwd(cwd).quiet();
336
+ }
337
+ catch (err) {
338
+ return errText(err).includes('already') ? reListD1(name, cwd) : null;
339
+ }
340
+ return reListD1(name, cwd);
341
+ }
342
+ async function reListD1(name, cwd) {
343
+ return (await listD1Databases(cwd)).find((d) => d.name === name)?.uuid ?? null;
344
+ }
345
+ /** Current secret names on the worker for `env`; `[]` when none/unreachable (Cloudflare allows setting pre-deploy). */
346
+ export async function listSecretNames(env, cwd) {
347
+ try {
348
+ return asSecretNames(await $ `bunx wrangler secret list --format json --env ${env}`.cwd(cwd).quiet().json());
349
+ }
350
+ catch {
351
+ return [];
352
+ }
353
+ }
354
+ /** `wrangler secret put <name> --env <env>` piping `value` on stdin (never a CLI arg). Returns success. */
355
+ export async function putSecret(name, value, env, cwd) {
356
+ try {
357
+ await $ `bunx wrangler secret put ${name} --env ${env} < ${Buffer.from(value)}`.cwd(cwd).quiet();
358
+ return true;
359
+ }
360
+ catch {
361
+ return false;
362
+ }
363
+ }
@@ -0,0 +1,7 @@
1
+ export interface ScaffoldOptions {
2
+ /** Overwrite an existing scripts/prepare-env.ts. */
3
+ force?: boolean;
4
+ }
5
+ /** Write the starter script + wire the `prepare-env` nx target. Returns the script path. */
6
+ export declare function scaffold(root: string, project: string, options?: ScaffoldOptions): string;
7
+ //# sourceMappingURL=scaffold.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scaffold.d.ts","sourceRoot":"","sources":["../../src/wrangler/scaffold.ts"],"names":[],"mappings":"AAYA,MAAM,WAAW,eAAe;IAC9B,oDAAoD;IACpD,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAmMD,4FAA4F;AAC5F,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,eAAoB,GAAG,MAAM,CA2B7F"}