@zitadel/cli 0.0.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.
@@ -0,0 +1,694 @@
1
+ import { l as DEFAULT_SERVER, n as hasZitadelSecret, p as ZitadelError, s as BaseCommand, t as hasZitadelConfig } from "../project-C3pSfbao.mjs";
2
+ import { n as RENDERER_IDS, r as issuerFromPort, t as createOrca } from "../orca-COsUnVoz.mjs";
3
+ import { Flags } from "@oclif/core";
4
+ import { cancel, confirm, intro, isCancel, outro, select, spinner, text } from "@clack/prompts";
5
+ import { consola as consola$1 } from "consola";
6
+ import { readFile, stat } from "node:fs/promises";
7
+ import { basename, join } from "node:path";
8
+ import { execFile } from "node:child_process";
9
+ import { createZitadelClient } from "@zitadel/api/client";
10
+ import pc from "picocolors";
11
+ //#region src/commands/setup/prompts/cancel.ts
12
+ /**
13
+ * Converts a clack cancellation (Ctrl-C) into a thrown `E_VALIDATION` rather
14
+ * than a partial answer. Every prompt funnels its clack return value through
15
+ * this so the wizard never proceeds with a sentinel or missing value.
16
+ */
17
+ function bail(value) {
18
+ if (isCancel(value)) {
19
+ cancel("Setup cancelled.");
20
+ throw new ZitadelError("E_VALIDATION", "Setup cancelled by user");
21
+ }
22
+ }
23
+ //#endregion
24
+ //#region src/commands/setup/prompts/dev-port.ts
25
+ /**
26
+ * "Dev server port" — defaults to the detected port. The validated answer
27
+ * becomes the issuer URL (`http://localhost:<port>`) via `issuerFromPort`.
28
+ */
29
+ var DevPortPrompt = class {
30
+ async ask(answers, _ctx) {
31
+ const value = await text({
32
+ message: "Dev server port",
33
+ placeholder: String(answers.devPort),
34
+ initialValue: String(answers.devPort),
35
+ validate: (input) => {
36
+ const num = Number.parseInt(input ?? "", 10);
37
+ return Number.isFinite(num) && num > 0 && num < 65536 ? void 0 : "Must be a port number";
38
+ }
39
+ });
40
+ bail(value);
41
+ return {
42
+ ...answers,
43
+ devPort: Number.parseInt(String(value), 10)
44
+ };
45
+ }
46
+ };
47
+ //#endregion
48
+ //#region src/commands/setup/prompts/framework-confirm.ts
49
+ /**
50
+ * "Detected `<framework>`. Proceed?" — the wizard's first question. Accepting
51
+ * leaves answers unchanged; declining throws `E_UNSUPPORTED_PROJECT_SHAPE`
52
+ * (the user should re-run with an explicit `--framework`).
53
+ */
54
+ var FrameworkConfirmPrompt = class {
55
+ async ask(answers, ctx) {
56
+ const ack = await confirm({
57
+ message: `Detected ${ctx.framework.id}. Proceed?`,
58
+ initialValue: true
59
+ });
60
+ bail(ack);
61
+ if (ack === false) throw new ZitadelError("E_UNSUPPORTED_PROJECT_SHAPE", "Setup cancelled — framework declined", { hint: `Re-run with --framework ${ctx.framework.id} when ready.` });
62
+ return answers;
63
+ }
64
+ };
65
+ //#endregion
66
+ //#region src/lib/prober/ports.ts
67
+ /**
68
+ * Enumerate TCP ports currently in LISTEN state on the loopback interface
69
+ * (`127.0.0.1`, `::1`, or the wildcard `*`). Spawns `lsof -iTCP -sTCP:LISTEN
70
+ * -P -n -F n` and parses its machine-readable output. Returns the unique,
71
+ * numerically-sorted list of ports.
72
+ *
73
+ * Never throws. Returns `[]` whenever lsof is unavailable (e.g. Windows,
74
+ * unusual PATH), the spawn errors, exits non-zero, or the call exceeds
75
+ * `timeoutMs` (default 1000ms). The caller treats an empty list the same as
76
+ * "no listeners worth probing."
77
+ */
78
+ async function listListeningPorts(opts) {
79
+ const timeoutMs = opts?.timeoutMs ?? 1e3;
80
+ try {
81
+ return parseLsofPorts(await runLsof(timeoutMs));
82
+ } catch {
83
+ return [];
84
+ }
85
+ }
86
+ /**
87
+ * Spawn `lsof` with the canned argv and resolve to its stdout. Hand-rolled
88
+ * rather than `util.promisify(execFile)` because the latter resolves with a
89
+ * `{stdout, stderr}` object via its custom-promisify symbol — a heavier shape
90
+ * to mock and worse to read at the call site, where we only ever want stdout.
91
+ */
92
+ function runLsof(timeoutMs) {
93
+ return new Promise((resolve, reject) => {
94
+ execFile("lsof", [
95
+ "-iTCP",
96
+ "-sTCP:LISTEN",
97
+ "-P",
98
+ "-n",
99
+ "-F",
100
+ "n"
101
+ ], {
102
+ timeout: timeoutMs,
103
+ encoding: "utf8"
104
+ }, (err, stdout) => {
105
+ if (err) {
106
+ reject(err);
107
+ return;
108
+ }
109
+ resolve(stdout);
110
+ });
111
+ });
112
+ }
113
+ /**
114
+ * Parse the `n` records emitted by `lsof -F n`. Each record is a single line
115
+ * `n<address>` where `<address>` ends in `:<port>` (e.g. `n*:8080`,
116
+ * `n127.0.0.1:3000`, `n[::1]:5050`). Only loopback/wildcard hosts are kept;
117
+ * external interface bindings are ignored.
118
+ */
119
+ function parseLsofPorts(stdout) {
120
+ const ports = /* @__PURE__ */ new Set();
121
+ for (const line of stdout.split(/\r?\n/)) {
122
+ if (!line.startsWith("n")) continue;
123
+ const address = line.slice(1);
124
+ const colon = address.lastIndexOf(":");
125
+ if (colon < 0) continue;
126
+ const host = address.slice(0, colon);
127
+ const portStr = address.slice(colon + 1);
128
+ if (!isLoopback(host)) continue;
129
+ const port = Number.parseInt(portStr, 10);
130
+ if (Number.isFinite(port) && port > 0 && port < 65536) ports.add(port);
131
+ }
132
+ return [...ports].sort((a, b) => a - b);
133
+ }
134
+ /** Recognised loopback host strings as emitted by `lsof -F n`. */
135
+ function isLoopback(host) {
136
+ return host === "*" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
137
+ }
138
+ //#endregion
139
+ //#region src/lib/prober/http.ts
140
+ /**
141
+ * Fetch `url` with a per-call timeout and pass the resulting `Response` to
142
+ * `predicate`. Returns the predicate's value, or `null` on any failure: a
143
+ * network error, an `AbortError` from the timeout, a thrown predicate, or the
144
+ * predicate returning `null`.
145
+ *
146
+ * Never throws. The predicate decides what counts as a match — it gets the
147
+ * raw `Response` and may read `.json()` / `.headers` / `.status` as needed.
148
+ *
149
+ * `timeoutMs` defaults to 500ms. The implementation uses
150
+ * `AbortSignal.timeout`, so the underlying fetch is cancelled when the
151
+ * timeout fires (no orphaned sockets).
152
+ */
153
+ async function probeUrl(url, predicate, opts) {
154
+ const timeoutMs = opts?.timeoutMs ?? 500;
155
+ try {
156
+ return await predicate(await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }));
157
+ } catch {
158
+ return null;
159
+ }
160
+ }
161
+ /**
162
+ * Probe many URLs in parallel and return the non-null matches, preserving
163
+ * the input order. Each URL is bounded by `timeoutMs` independently — one
164
+ * slow target can't hold up the others.
165
+ */
166
+ async function probeUrls(urls, predicate, opts) {
167
+ const list = [...urls];
168
+ return (await Promise.all(list.map(async (url) => {
169
+ const value = await probeUrl(url, predicate, opts);
170
+ return value === null ? null : {
171
+ url,
172
+ value
173
+ };
174
+ }))).filter((match) => match !== null);
175
+ }
176
+ //#endregion
177
+ //#region src/commands/setup/prompts/server.ts
178
+ /** Sentinel returned by the choice select when the user picks "Custom URL". */
179
+ const CUSTOM = "__custom__";
180
+ /** Per-probe timeout for the localhost OIDC scan — generous enough for a TLS handshake on a busy laptop. */
181
+ const OIDC_PROBE_TIMEOUT_MS = 300;
182
+ /**
183
+ * "Which server should `zitadel.json` point to?" — Zitadel Cloud, a localhost
184
+ * OIDC server we discovered, or a custom URL.
185
+ *
186
+ * Before asking, it scans the loopback for listening ports (via the generic
187
+ * `lib/prober`) and `GET`s `/.well-known/openid-configuration` on each. Every
188
+ * 2xx response with a string `issuer` becomes an extra option in the choice
189
+ * list. Picking a discovered URL writes it directly to `answers.server` and
190
+ * skips the follow-up text prompt. Picking "Custom URL" still asks for a
191
+ * validated URL exactly as before.
192
+ */
193
+ var ServerPrompt = class {
194
+ async ask(answers, ctx) {
195
+ if (ctx.serverFlag) return answers;
196
+ const discovered = await discoverLocalOidc();
197
+ const choice = await select({
198
+ message: "Which server should zitadel.json point to?",
199
+ options: [
200
+ {
201
+ value: DEFAULT_SERVER,
202
+ label: "Zitadel Cloud (api.zitadel.cloud)",
203
+ hint: "recommended for real projects"
204
+ },
205
+ ...discovered.map((server) => ({
206
+ value: server,
207
+ label: server,
208
+ hint: "detected — OIDC"
209
+ })),
210
+ {
211
+ value: CUSTOM,
212
+ label: "Custom URL (self-hosted)"
213
+ }
214
+ ],
215
+ initialValue: answers.server ?? "https://api.zitadel.cloud"
216
+ });
217
+ bail(choice);
218
+ if (choice !== CUSTOM) return {
219
+ ...answers,
220
+ server: choice
221
+ };
222
+ const custom = await text({
223
+ message: "Server URL",
224
+ placeholder: "https://zitadel.internal",
225
+ validate: (value) => {
226
+ try {
227
+ new URL(value ?? "");
228
+ return;
229
+ } catch {
230
+ return "Must be a valid URL";
231
+ }
232
+ }
233
+ });
234
+ bail(custom);
235
+ return {
236
+ ...answers,
237
+ server: custom
238
+ };
239
+ }
240
+ };
241
+ /**
242
+ * Returns the loopback origins (`http://localhost:<port>`) whose
243
+ * `/.well-known/openid-configuration` endpoint responds with a valid OIDC
244
+ * discovery document. Sniffs purely via the generic prober — the only
245
+ * Zitadel-shaped detail here is the OIDC predicate, which is the standard
246
+ * "any OIDC server" contract (no `zitadel`-keyword check), so Keycloak/dex/
247
+ * etc. also surface and the user picks the right one.
248
+ */
249
+ async function discoverLocalOidc() {
250
+ const s = spinner();
251
+ s.start("Scanning localhost for OIDC servers");
252
+ try {
253
+ const ports = await listListeningPorts();
254
+ if (ports.length === 0) {
255
+ s.stop("No local servers detected.");
256
+ return [];
257
+ }
258
+ const origins = (await probeUrls(ports.map((port) => `http://localhost:${port}/.well-known/openid-configuration`), async (response) => {
259
+ if (!response.ok) return null;
260
+ try {
261
+ const body = await response.json();
262
+ return typeof body.issuer === "string" ? body.issuer : null;
263
+ } catch {
264
+ return null;
265
+ }
266
+ }, { timeoutMs: OIDC_PROBE_TIMEOUT_MS })).map((match) => new URL(match.url).origin);
267
+ s.stop(origins.length === 0 ? "No local OIDC servers found." : `Found ${origins.length} local OIDC server${origins.length === 1 ? "" : "s"}.`);
268
+ return origins;
269
+ } catch (error) {
270
+ s.stop("Discovery skipped.");
271
+ throw error;
272
+ }
273
+ }
274
+ //#endregion
275
+ //#region src/commands/setup/prompts/pick-framework.ts
276
+ /**
277
+ * "Choose a framework to scaffold" — the only prompt outside the main wizard.
278
+ * Runs at the empty-directory branch (before any other detection), so it owns
279
+ * its own `intro` heading. Returns the chosen framework id; choices come from
280
+ * `Orca.availableFrameworks`.
281
+ */
282
+ var PickFrameworkPrompt = class {
283
+ async ask(choices) {
284
+ intro("Zitadel setup — new project");
285
+ const picked = await select({
286
+ message: "Choose a framework to scaffold",
287
+ options: choices.map((choice) => ({
288
+ value: choice.id,
289
+ label: choice.displayName
290
+ }))
291
+ });
292
+ bail(picked);
293
+ return picked;
294
+ }
295
+ };
296
+ //#endregion
297
+ //#region src/commands/setup/prompts/index.ts
298
+ /**
299
+ * Public surface for the setup wizard prompts. The `setup` command imports
300
+ * {@link SETUP_PROMPTS} and iterates every entry, threading the answers
301
+ * through each prompt's `ask` so they decide whether to actually ask the
302
+ * user. Add a new question by writing a class and appending an instance to
303
+ * the registry below.
304
+ *
305
+ * {@link PickFrameworkPrompt} is intentionally **not** in {@link SETUP_PROMPTS}
306
+ * — it runs at the empty-directory scaffold branch, before the main wizard
307
+ * starts.
308
+ */
309
+ /** Every question the main setup wizard asks, in ask order. */
310
+ const SETUP_PROMPTS = [
311
+ new FrameworkConfirmPrompt(),
312
+ new ServerPrompt(),
313
+ new DevPortPrompt()
314
+ ];
315
+ //#endregion
316
+ //#region src/commands/setup/summary.ts
317
+ /**
318
+ * Renders the section list as a single multi-line string. Labels are
319
+ * padded to a common width per section so the `✓ label value` columns
320
+ * line up, the title prints in dim gray, and `✓` is green. Values come
321
+ * in pre-styled — use the helpers below ({@link path}, {@link url},
322
+ * {@link id}, {@link dim}) to keep the colour palette consistent with
323
+ * the mock.
324
+ */
325
+ function renderSummary(sections) {
326
+ const lines = [];
327
+ for (const section of sections) {
328
+ if (section.rows.length === 0) continue;
329
+ if (lines.length > 0) lines.push("");
330
+ lines.push(pc.dim(section.title.toUpperCase()));
331
+ const labelWidth = Math.max(...section.rows.map((r) => r.label.length)) + 3;
332
+ for (const row of section.rows) {
333
+ const labelCol = row.label.padEnd(labelWidth);
334
+ const secondary = row.secondary ? ` ${pc.dim("→")} ${row.secondary}` : "";
335
+ lines.push(`${pc.green("✓")} ${labelCol}${row.value}${secondary}`);
336
+ }
337
+ }
338
+ return lines.join("\n");
339
+ }
340
+ /** Cyan, for filesystem paths the user can open. */
341
+ const path = (s) => pc.cyan(s);
342
+ /** Cyan, for URLs (browser-clickable in most terminals). */
343
+ const url = (s) => pc.cyan(s);
344
+ /** Yellow, for opaque ids the user shouldn't try to read. */
345
+ const id = (s) => pc.yellow(s);
346
+ /**
347
+ * Reads the project root to identify the framework version, TS presence,
348
+ * and which package manager the user runs. Returns the worst-case
349
+ * (`"unknown"` PM, no version) on any error so summary rendering can
350
+ * always proceed.
351
+ */
352
+ async function detectProjectFacts(cwd, frameworkId) {
353
+ const facts = {
354
+ framework: frameworkId,
355
+ typescript: await fileExists(join(cwd, "tsconfig.json")),
356
+ packageManager: await detectPackageManager(cwd)
357
+ };
358
+ try {
359
+ const raw = await readFile(join(cwd, "package.json"), "utf8");
360
+ const pj = JSON.parse(raw);
361
+ const depPkg = depFromFramework(frameworkId);
362
+ const range = pj.dependencies?.[depPkg] ?? pj.devDependencies?.[depPkg];
363
+ if (range) facts.frameworkVersion = stripRange(range);
364
+ } catch {}
365
+ return facts;
366
+ }
367
+ /** Formats the project facts as the "Next.js 15 · TypeScript · npm" string the mock shows. */
368
+ function formatFrameworkLine(facts) {
369
+ const segments = [];
370
+ const pretty = prettyFramework(facts.framework);
371
+ segments.push(facts.frameworkVersion ? `${pretty} ${facts.frameworkVersion}` : pretty);
372
+ if (facts.typescript) segments.push("TypeScript");
373
+ if (facts.packageManager !== "unknown") segments.push(facts.packageManager);
374
+ return segments.join(` ${pc.dim("·")} `);
375
+ }
376
+ async function detectPackageManager(cwd) {
377
+ if (await fileExists(join(cwd, "pnpm-lock.yaml"))) return "pnpm";
378
+ if (await fileExists(join(cwd, "yarn.lock"))) return "yarn";
379
+ if (await fileExists(join(cwd, "bun.lockb"))) return "bun";
380
+ if (await fileExists(join(cwd, "package-lock.json"))) return "npm";
381
+ return "unknown";
382
+ }
383
+ async function fileExists(p) {
384
+ try {
385
+ await stat(p);
386
+ return true;
387
+ } catch {
388
+ return false;
389
+ }
390
+ }
391
+ function depFromFramework(framework) {
392
+ switch (framework) {
393
+ case "next": return "next";
394
+ case "nuxt": return "nuxt";
395
+ default: return framework;
396
+ }
397
+ }
398
+ function prettyFramework(framework) {
399
+ switch (framework) {
400
+ case "next": return "Next.js";
401
+ case "nuxt": return "Nuxt";
402
+ default: return framework;
403
+ }
404
+ }
405
+ /** Strips `^`/`~`/`>=`/`v` prefixes from an npm range so the version reads cleanly in the summary. */
406
+ function stripRange(range) {
407
+ const trimmed = range.replace(/^([\^~]|>=?|v)/, "").trim();
408
+ return trimmed.split(/\s+/)[0] ?? trimmed;
409
+ }
410
+ /** Returns just the file name from a relative path, for the `→ filename` secondary detail in PACKAGE rows. */
411
+ function fileNameOf(p) {
412
+ return basename(p);
413
+ }
414
+ //#endregion
415
+ //#region src/commands/setup/index.ts
416
+ /**
417
+ * The frameworks `--framework` accepts, derived from Orca's registry so the
418
+ * flag can't drift from what the CLI can actually scaffold. `createOrca` is
419
+ * pure (it only builds the in-memory registries), so this is safe at module
420
+ * load.
421
+ */
422
+ const FRAMEWORK_OPTIONS = createOrca().availableFrameworks().map((framework) => framework.id);
423
+ /** `zitadel setup` — create a project and scaffold local auth.
424
+ *
425
+ * Detects (or, for an empty directory, scaffolds then re-detects) the
426
+ * framework, runs the wizard prompts to fill in any answers not pre-supplied
427
+ * by flags, creates the remote project (whose default user schema and login
428
+ * flow are provisioned server-side), and patches the local files via
429
+ * `Orca`'s framework patcher.
430
+ *
431
+ * Every interactive question lives in {@link SETUP_PROMPTS} (the main wizard
432
+ * — each entry is a small class) and {@link PickFrameworkPrompt} (the
433
+ * empty-directory framework choice, before the main wizard).
434
+ */
435
+ var Setup = class Setup extends BaseCommand {
436
+ static description = "Create a Zitadel project and scaffold local auth.";
437
+ static examples = ["<%= config.bin %> setup --framework next"];
438
+ static flags = {
439
+ framework: Flags.string({
440
+ description: "Framework to target.",
441
+ options: FRAMEWORK_OPTIONS
442
+ }),
443
+ renderer: Flags.string({
444
+ description: "Renderer (default: react).",
445
+ options: [...RENDERER_IDS]
446
+ })
447
+ };
448
+ async run() {
449
+ const { flags } = await this.parse(Setup);
450
+ await this.toMeta(flags);
451
+ const { cwd, nonInteractive, dryRun, force } = this.meta;
452
+ if (await hasZitadelConfig(cwd)) return this.emit({
453
+ status: "skipped",
454
+ reason: "already-initialized"
455
+ });
456
+ if (await hasZitadelSecret(cwd)) throw new ZitadelError("E_CONFLICT", ".zitadel/secret exists without zitadel.json", { hint: "Move the secret aside or restore zitadel.json before running setup." });
457
+ const orca = createOrca();
458
+ consola$1.start(`Detecting framework in ${shortPath(cwd)}`);
459
+ let framework;
460
+ let scaffoldedFramework = false;
461
+ try {
462
+ framework = await orca.detect(cwd, flags.framework);
463
+ consola$1.success(`Detected ${framework.id}${framework.devPort ? ` (dev port ${framework.devPort})` : ""}`);
464
+ } catch (error) {
465
+ if (error instanceof ZitadelError && error.code === "E_FRAMEWORK_NOT_DETECTED" && await orca.isEmpty(cwd)) {
466
+ consola$1.info("Empty directory — scaffolding a fresh project");
467
+ framework = await orca.scaffold(cwd, await resolveScaffoldFramework(flags.framework, nonInteractive, orca));
468
+ scaffoldedFramework = true;
469
+ consola$1.success(`Scaffolded ${framework.id} skeleton`);
470
+ } else throw error;
471
+ }
472
+ let answers = {
473
+ server: this.meta.source,
474
+ devPort: framework.devPort
475
+ };
476
+ if (!nonInteractive && !dryRun) {
477
+ intro("Zitadel setup");
478
+ const promptCtx = {
479
+ framework,
480
+ serverFlag: this.meta.serverFlag
481
+ };
482
+ for (const prompt of SETUP_PROMPTS) answers = await prompt.ask(answers, promptCtx);
483
+ outro("Configuration captured");
484
+ }
485
+ const issuer = issuerFromPort(answers.devPort);
486
+ consola$1.start(`Creating project on ${answers.server}${dryRun ? " (dry run)" : ""}`);
487
+ const unauthClient = createZitadelClient({ baseUrl: answers.server });
488
+ const project = dryRun ? dryRunProject() : await unauthClient.createProject({ previewOrigins: [] });
489
+ consola$1.success(`Created project ${project.id}`);
490
+ const ctx = {
491
+ framework,
492
+ rendererId: flags.renderer ?? "react",
493
+ project,
494
+ issuer,
495
+ server: answers.server
496
+ };
497
+ consola$1.start(`Patching project files${dryRun ? " (dry run)" : ""}`);
498
+ const result = await orca.patcherFor(framework.id).patch(ctx, {
499
+ cwd,
500
+ dryRun,
501
+ force
502
+ });
503
+ for (const file of result.filesWritten) {
504
+ const sentence = describeWrittenFile(relativeDisplay(cwd, file), dryRun);
505
+ if (sentence) consola$1.info(sentence);
506
+ }
507
+ for (const file of result.filesSkipped) consola$1.info(`Left ${relativeDisplay(cwd, file)} unchanged (already matches target)`);
508
+ consola$1.success(`Patched ${result.filesWritten.length} file${result.filesWritten.length === 1 ? "" : "s"}` + (result.filesSkipped.length > 0 ? ` (${result.filesSkipped.length} unchanged)` : ""));
509
+ const writtenRel = result.filesWritten.map((file) => relativeDisplay(cwd, file));
510
+ if (!this.jsonEnabled()) {
511
+ const sections = buildSummary({
512
+ projectFacts: await detectProjectFacts(cwd, framework.id),
513
+ writtenRel,
514
+ project,
515
+ server: answers.server,
516
+ issuer,
517
+ scaffoldedFramework
518
+ });
519
+ consola$1.box({
520
+ title: "Zitadel is ready",
521
+ message: [
522
+ renderSummary(sections),
523
+ "",
524
+ `Open your app on ${url(`${issuer}/login`)} and register your first user.`
525
+ ].join("\n"),
526
+ style: {
527
+ padding: 1,
528
+ borderStyle: "rounded",
529
+ borderColor: "green"
530
+ }
531
+ });
532
+ }
533
+ return this.emit({
534
+ status: "ok",
535
+ pretty: "",
536
+ data: {
537
+ title: "Zitadel is ready.",
538
+ project: {
539
+ project_id: project.id,
540
+ issuer
541
+ },
542
+ framework: framework.id,
543
+ server: answers.server,
544
+ files_written: result.filesWritten.map((file) => relativeDisplay(cwd, file)),
545
+ files_skipped: result.filesSkipped.map((file) => relativeDisplay(cwd, file)),
546
+ next_actions: [`Start your project: npm install && npm run dev (then open ${issuer}/login)`],
547
+ next_commands: ["npm install", "npm run dev"]
548
+ }
549
+ });
550
+ }
551
+ };
552
+ /**
553
+ * Resolves which framework to scaffold into an empty directory: the explicit
554
+ * `--framework`, else PickFrameworkPrompt, else a hard error in non-interactive
555
+ * mode (an agent must pass `--framework`).
556
+ */
557
+ async function resolveScaffoldFramework(framework, nonInteractive, orca) {
558
+ if (framework) return framework;
559
+ if (nonInteractive) throw new ZitadelError("E_FRAMEWORK_NOT_DETECTED", "Empty directory — pass --framework", { hint: "Example: --framework next" });
560
+ return new PickFrameworkPrompt().ask(orca.availableFrameworks());
561
+ }
562
+ /** A deterministic stand-in project for `--dry-run`, so no remote call is made. */
563
+ function dryRunProject() {
564
+ return {
565
+ id: "dry-run-0000",
566
+ projectSecret: "sk_proj_dry_run_full",
567
+ previewSecret: "sk_proj_dry_run_preview",
568
+ previewOrigins: [],
569
+ createdAt: "2026-04-21T14:03:11.000Z"
570
+ };
571
+ }
572
+ /** Renders an absolute path relative to `cwd` for human-readable output. */
573
+ function relativeDisplay(cwd, path) {
574
+ return path.startsWith(cwd) ? path.slice(cwd.length + 1) : path;
575
+ }
576
+ /**
577
+ * Replaces the user's `$HOME` with `~` in a path for compact terminal output.
578
+ * Falls back to the raw path when `HOME` isn't set or doesn't match.
579
+ */
580
+ function shortPath(absolute) {
581
+ const home = process.env.HOME;
582
+ if (home && absolute.startsWith(home)) return `~${absolute.slice(home.length)}`;
583
+ return absolute;
584
+ }
585
+ /**
586
+ * Picks one written file by suffix so the corresponding INSTALLED row can
587
+ * reference it without hard-coding the path the patcher chose. Returns
588
+ * the first match; falls back to `undefined` when the patcher didn't
589
+ * write that artifact (e.g. a renderer without a register page).
590
+ */
591
+ function pickWrittenFile(written, suffix) {
592
+ return written.find((file) => file.endsWith(suffix));
593
+ }
594
+ /**
595
+ * Translates a patcher-written path into a single sentence the user can
596
+ * read at narration speed. Returns `null` for directories and other
597
+ * scaffolding artefacts that aren't worth narrating individually — the
598
+ * file count in the closing `success(...)` and the summary's INSTALLED
599
+ * section already cover them. The verb tense flips for `--dry-run` so
600
+ * the user sees a preview ("Would write ...") instead of a claim that
601
+ * something happened.
602
+ */
603
+ function describeWrittenFile(relPath, dryRun) {
604
+ if (relPath === ".zitadel" || relPath === ".zitadel/flows" || relPath === ".zitadel/schemas") return null;
605
+ const verb = dryRun ? "Would write" : "Wrote";
606
+ const sentence = SENTENCE_BY_PATH[relPath];
607
+ if (sentence) return `${verb} ${sentence.subject} (${path(relPath)})`;
608
+ return `${verb} ${path(relPath)}`;
609
+ }
610
+ /**
611
+ * Map from the patcher's deterministic output paths to a short noun
612
+ * phrase describing what the file is for. Anything not in the map falls
613
+ * back to the bare path in the narration; add an entry here when a new
614
+ * scaffolded file deserves a clearer label.
615
+ */
616
+ const SENTENCE_BY_PATH = {
617
+ ".gitignore": { subject: "the project's .gitignore additions" },
618
+ ".zitadel/secret": { subject: "the local project secret" },
619
+ "zitadel.json": { subject: "the Zitadel project configuration" },
620
+ ".env.example": { subject: "the .env example template" },
621
+ ".env.local": { subject: "the local development environment variables" },
622
+ ".zitadel/state.json": { subject: "the empty sync state file" },
623
+ "app/login/page.tsx": { subject: "the login page" },
624
+ "app/register/page.tsx": { subject: "the registration page" },
625
+ "app/profile/page.tsx": { subject: "the profile page" },
626
+ "middleware.ts": { subject: "the Next.js middleware" },
627
+ "custom-elements.d.ts": { subject: "the web-component type declarations" },
628
+ "package.json": { subject: "package.json with the SDK dependency" }
629
+ };
630
+ /** Builds the section list driving {@link renderSummary} for the setup command. */
631
+ function buildSummary(opts) {
632
+ const { projectFacts, writtenRel, project, server, issuer, scaffoldedFramework } = opts;
633
+ const sdkPackage = "@zitadel/sdk-next";
634
+ const packageJsonHit = pickWrittenFile(writtenRel, "package.json");
635
+ const detected = [{
636
+ label: "Framework",
637
+ value: formatFrameworkLine(projectFacts)
638
+ }];
639
+ if (scaffoldedFramework) detected.push({
640
+ label: "Scaffold",
641
+ value: "fresh project (no existing files)"
642
+ });
643
+ const installedRows = [];
644
+ if (packageJsonHit) installedRows.push({
645
+ label: "Package",
646
+ value: sdkPackage,
647
+ secondary: path(fileNameOf(packageJsonHit))
648
+ });
649
+ for (const [label, suffix] of [
650
+ ["Login page", "app/login/page.tsx"],
651
+ ["Register page", "app/register/page.tsx"],
652
+ ["Profile page", "app/profile/page.tsx"],
653
+ ["Middleware", "middleware.ts"],
654
+ ["Env vars", ".env.local"]
655
+ ]) {
656
+ const hit = pickWrittenFile(writtenRel, suffix);
657
+ if (hit) installedRows.push({
658
+ label,
659
+ value: path(hit)
660
+ });
661
+ }
662
+ const projectRows = [
663
+ {
664
+ label: "Project id",
665
+ value: id(project.id)
666
+ },
667
+ {
668
+ label: "Server",
669
+ value: url(server)
670
+ },
671
+ {
672
+ label: "App will run",
673
+ value: url(issuer)
674
+ }
675
+ ];
676
+ return [
677
+ {
678
+ title: "Detected",
679
+ rows: detected
680
+ },
681
+ {
682
+ title: "Installed",
683
+ rows: installedRows
684
+ },
685
+ {
686
+ title: "Project",
687
+ rows: projectRows
688
+ }
689
+ ];
690
+ }
691
+ //#endregion
692
+ export { Setup as default };
693
+
694
+ //# sourceMappingURL=setup.mjs.map