@zitadel/cli 0.1.0-alpha.1 → 0.1.0-alpha.10

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 (45) hide show
  1. package/README.md +116 -26
  2. package/SKILLS.md +102 -24
  3. package/dist/commands/apply.mjs +4 -5
  4. package/dist/commands/apply.mjs.map +1 -1
  5. package/dist/commands/doctor.mjs +214 -50
  6. package/dist/commands/doctor.mjs.map +1 -1
  7. package/dist/commands/eject.mjs +14 -7
  8. package/dist/commands/eject.mjs.map +1 -1
  9. package/dist/commands/logs.mjs +15 -7
  10. package/dist/commands/logs.mjs.map +1 -1
  11. package/dist/commands/plan.mjs +4 -5
  12. package/dist/commands/plan.mjs.map +1 -1
  13. package/dist/commands/reset.mjs +28 -12
  14. package/dist/commands/reset.mjs.map +1 -1
  15. package/dist/commands/setup.mjs +266 -106
  16. package/dist/commands/setup.mjs.map +1 -1
  17. package/dist/commands/start.mjs +180 -24
  18. package/dist/commands/start.mjs.map +1 -1
  19. package/dist/commands/status.mjs +40 -16
  20. package/dist/commands/status.mjs.map +1 -1
  21. package/dist/commands/stop.mjs +72 -11
  22. package/dist/commands/stop.mjs.map +1 -1
  23. package/dist/docker-CnGQK3ZK.mjs +432 -0
  24. package/dist/docker-CnGQK3ZK.mjs.map +1 -0
  25. package/dist/docker-guidance-ypN3IM3o.mjs +21 -0
  26. package/dist/docker-guidance-ypN3IM3o.mjs.map +1 -0
  27. package/dist/{oclif-DSPO9Sck.mjs → oclif-B7lBzh3R.mjs} +158 -63
  28. package/dist/oclif-B7lBzh3R.mjs.map +1 -0
  29. package/dist/orca-BoTFU8SI.mjs +2581 -0
  30. package/dist/orca-BoTFU8SI.mjs.map +1 -0
  31. package/dist/ports-B09RjuHx.mjs +111 -0
  32. package/dist/ports-B09RjuHx.mjs.map +1 -0
  33. package/dist/processes-Cw8TO1SY.mjs +120 -0
  34. package/dist/processes-Cw8TO1SY.mjs.map +1 -0
  35. package/dist/{project-Dwb9WVAT.mjs → project-Cd0L3PtM.mjs} +3 -3
  36. package/dist/{project-Dwb9WVAT.mjs.map → project-Cd0L3PtM.mjs.map} +1 -1
  37. package/dist/{sync-DmtTYNmq.mjs → sync-BojoQm2P.mjs} +3 -3
  38. package/dist/{sync-DmtTYNmq.mjs.map → sync-BojoQm2P.mjs.map} +1 -1
  39. package/oclif.manifest.json +49 -5
  40. package/package.json +8 -41
  41. package/dist/docker-C0aVpJqm.mjs +0 -209
  42. package/dist/docker-C0aVpJqm.mjs.map +0 -1
  43. package/dist/oclif-DSPO9Sck.mjs.map +0 -1
  44. package/dist/orca-DOxshV9n.mjs +0 -1009
  45. package/dist/orca-DOxshV9n.mjs.map +0 -1
@@ -0,0 +1,2581 @@
1
+ import { C as isObject, E as ZitadelError, T as stableStringify, n as DEFAULT_SERVER, w as parseJsonObject, x as MANAGED_MARKER, y as npmDistTagForCliVersion } from "./oclif-B7lBzh3R.mjs";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { chmod, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
4
+ import { builders, generateCode, parseModule } from "magicast";
5
+ import { spawnSync } from "node:child_process";
6
+ //#region src/lib/orca/detectors/package-json.ts
7
+ /**
8
+ * Reads and parses the `package.json` at `cwd`. Rejects if the file is absent
9
+ * or malformed; callers that treat those as "not a project" are expected to
10
+ * catch and fall back rather than have detection swallow the error here.
11
+ */
12
+ async function readPackageJson(cwd) {
13
+ const contents = await readFile(join(cwd, "package.json"), "utf8");
14
+ return JSON.parse(contents);
15
+ }
16
+ /**
17
+ * Reports whether `name` appears in either `dependencies` or `devDependencies`.
18
+ * Both are checked because framework packages may legitimately live in either.
19
+ */
20
+ function hasDependency(pkg, name) {
21
+ return Boolean(pkg.dependencies?.[name] ?? pkg.devDependencies?.[name]);
22
+ }
23
+ function dependencyVersionMajor(pkg, name) {
24
+ const spec = pkg.dependencies?.[name] ?? pkg.devDependencies?.[name];
25
+ if (!spec) return;
26
+ const match = spec.match(/\d+/);
27
+ return match ? Number(match[0]) : void 0;
28
+ }
29
+ //#endregion
30
+ //#region src/lib/orca/detectors/port.ts
31
+ /**
32
+ * Port assumed when no explicit dev port can be discovered. Matches Next.js's
33
+ * own default so the inferred issuer URL lines up with `next dev`.
34
+ */
35
+ const DEFAULT_DEV_PORT = 3e3;
36
+ /**
37
+ * Determines the local dev-server port for `cwd`. The `dev` script is the most
38
+ * authoritative source, then a `PORT` declaration in an env file, falling back
39
+ * to {@link DEFAULT_DEV_PORT}. Used to derive the local issuer URL.
40
+ */
41
+ async function detectDevPort(cwd, pkg) {
42
+ const dev = pkg.scripts?.dev;
43
+ const fromScript = typeof dev === "string" ? extractPort(dev) : void 0;
44
+ if (fromScript) return fromScript;
45
+ const fromEnvFile = await portFromEnvFile(cwd);
46
+ if (fromEnvFile) return fromEnvFile;
47
+ return DEFAULT_DEV_PORT;
48
+ }
49
+ async function portFromEnvFile(cwd) {
50
+ for (const candidate of [".env.local", ".env"]) try {
51
+ const rawPort = (await readFile(join(cwd, candidate), "utf8")).match(/^\s*PORT\s*=\s*(\d+)/m)?.[1];
52
+ if (rawPort) return Number.parseInt(rawPort, 10);
53
+ } catch {
54
+ continue;
55
+ }
56
+ }
57
+ /**
58
+ * Parses a dev port out of an npm `dev` script string, recognizing both flag
59
+ * forms (`-p`/`--port`) and a leading `PORT=` env assignment. Returns
60
+ * `undefined` when no valid positive port is present so callers can fall back.
61
+ */
62
+ function extractPort(script) {
63
+ const inline = script.match(/-p\s+(\d+)|--port[=\s]+(\d+)/);
64
+ if (inline) {
65
+ const raw = inline[1] ?? inline[2];
66
+ if (!raw) return;
67
+ const value = Number.parseInt(raw, 10);
68
+ if (Number.isFinite(value) && value > 0) return value;
69
+ }
70
+ const rawEnvPort = script.match(/(?:^|\s)PORT=(\d+)/)?.[1];
71
+ if (rawEnvPort) return Number.parseInt(rawEnvPort, 10);
72
+ }
73
+ /**
74
+ * Builds the local OIDC issuer URL for a given dev port. Centralized so the
75
+ * `localhost` origin convention is defined in exactly one place.
76
+ */
77
+ function issuerFromPort(port) {
78
+ return `http://localhost:${port}`;
79
+ }
80
+ //#endregion
81
+ //#region src/lib/orca/detectors/angular.ts
82
+ /** The lowest Angular major the generated templates compile on. */
83
+ const MIN_ANGULAR_MAJOR = 17;
84
+ /** Best-effort major version from a dependency range (`^17.3.0` → 17). */
85
+ function angularMajor(spec) {
86
+ const match = spec.match(/\d+/);
87
+ return match ? Number.parseInt(match[0], 10) : void 0;
88
+ }
89
+ /**
90
+ * Detects an Angular project by its `@angular/core` dependency. The app dir is
91
+ * `src/app` (where the patcher writes `app.ts`/`app.html`), the dev port comes
92
+ * from the project (else the default), and the issuer is derived from it.
93
+ * Angular's dev server (`@angular/build:dev-server`)
94
+ * is Vite-based but configured via `angular.json` + a `proxy.conf.cjs`, not a
95
+ * `vite.config.ts` — handled by the Angular patcher.
96
+ *
97
+ * The managed templates use Angular 17+ control flow (`@if`), so a clearly
98
+ * older project fails fast with `E_VALIDATION` instead of scaffolding files
99
+ * that won't compile.
100
+ */
101
+ var AngularDetector = class {
102
+ framework = "angular";
103
+ async detect(cwd) {
104
+ const pkg = await readPackageJson(cwd).catch(() => void 0);
105
+ if (!pkg || !hasDependency(pkg, "@angular/core")) return null;
106
+ const spec = pkg.dependencies?.["@angular/core"] ?? pkg.devDependencies?.["@angular/core"];
107
+ const major = spec ? angularMajor(spec) : void 0;
108
+ if (major !== void 0 && major < MIN_ANGULAR_MAJOR) throw new ZitadelError("E_VALIDATION", `Angular ${major} is unsupported — the generated auth templates use Angular ${MIN_ANGULAR_MAJOR}+ control flow (@if).`, { hint: `Upgrade to Angular ${MIN_ANGULAR_MAJOR} or newer before running setup, or add the Zitadel components to your templates manually.` });
109
+ const devPort = await detectDevPort(cwd, pkg);
110
+ return {
111
+ id: "angular",
112
+ appDir: "src/app",
113
+ devPort,
114
+ url: issuerFromPort(devPort)
115
+ };
116
+ }
117
+ };
118
+ //#endregion
119
+ //#region src/lib/orca/detectors/next.ts
120
+ /**
121
+ * Detects a Next.js App Router project and extracts its facts: the App Router
122
+ * directory (`app` vs `src/app`), the dev-server port (parsed from the `dev`
123
+ * script / env file, else 3000), and the derived local issuer URL. Owns every
124
+ * Next-specific assumption so the orchestrator and commands stay generic.
125
+ */
126
+ var NextDetector = class {
127
+ framework = "next";
128
+ /**
129
+ * Returns `null` when `cwd` is not a Next.js project (no `next` dependency),
130
+ * so the orchestrator can try other detectors. Throws
131
+ * `E_UNSUPPORTED_PROJECT_SHAPE` when it is Next.js but lacks an App Router
132
+ * directory (e.g. a Pages Router project), which is a hard error rather than
133
+ * an empty directory to scaffold.
134
+ */
135
+ async detect(cwd) {
136
+ const pkg = await readPackageJson(cwd).catch(() => void 0);
137
+ if (!pkg || !hasDependency(pkg, "next")) return null;
138
+ const appDir = await dirExists$1(join(cwd, "app")) ? "app" : await dirExists$1(join(cwd, "src/app")) ? "src/app" : void 0;
139
+ if (!appDir) throw new ZitadelError("E_UNSUPPORTED_PROJECT_SHAPE", "Next.js Pages Router projects are not supported in v1", { hint: "Create an App Router project with an app/ or src/app/ directory." });
140
+ const devPort = await detectDevPort(cwd, pkg);
141
+ return {
142
+ id: "next",
143
+ appDir,
144
+ devPort,
145
+ url: issuerFromPort(devPort),
146
+ versionMajor: dependencyVersionMajor(pkg, "next")
147
+ };
148
+ }
149
+ };
150
+ async function dirExists$1(path) {
151
+ try {
152
+ return (await stat(path)).isDirectory();
153
+ } catch (error) {
154
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return false;
155
+ throw error;
156
+ }
157
+ }
158
+ //#endregion
159
+ //#region src/lib/orca/detectors/nuxt.ts
160
+ /**
161
+ * Detects a Nuxt project by its `nuxt` dependency. Like Next.js, Nuxt proxies
162
+ * the auth backend through server middleware (`@zitadel/sdk-nuxt`), not a Vite
163
+ * dev-server proxy — so the patcher wires the module + a `nuxt.config.ts` edit.
164
+ * Runs before the Vue detector (which excludes Nuxt) since Nuxt ships Vue.
165
+ *
166
+ * `appDir` tracks the Nuxt srcDir: Nuxt 4 (what `nuxi init` now scaffolds) keeps
167
+ * `app.vue`/`pages/`/`plugins/` under `app/`, while Nuxt 3 keeps them at the
168
+ * root — so the patcher writes its files relative to whichever this project uses.
169
+ */
170
+ var NuxtDetector = class {
171
+ framework = "nuxt";
172
+ async detect(cwd) {
173
+ const pkg = await readPackageJson(cwd).catch(() => void 0);
174
+ if (!pkg || !hasDependency(pkg, "nuxt")) return null;
175
+ const appDir = await dirExists(join(cwd, "app")) ? "app" : ".";
176
+ const devPort = await detectDevPort(cwd, pkg);
177
+ return {
178
+ id: "nuxt",
179
+ appDir,
180
+ devPort,
181
+ url: issuerFromPort(devPort)
182
+ };
183
+ }
184
+ };
185
+ async function dirExists(path) {
186
+ return stat(path).then((s) => s.isDirectory(), () => false);
187
+ }
188
+ //#endregion
189
+ //#region src/lib/orca/detectors/react.ts
190
+ /**
191
+ * Detects a Vite + React single-page app and extracts its facts: the source
192
+ * directory (`src`), the dev-server port (parsed from the `dev` script / env
193
+ * file, else the framework default), and the derived local issuer URL.
194
+ *
195
+ * Recognises a project that depends on both `react` and `vite` but NOT `next`
196
+ * — Next.js ships React too, so the {@link import("./next").NextDetector} must
197
+ * run first (and does, by registry order) and this detector excludes it.
198
+ */
199
+ var ReactDetector = class {
200
+ framework = "react";
201
+ async detect(cwd) {
202
+ const pkg = await readPackageJson(cwd).catch(() => void 0);
203
+ if (!pkg || hasDependency(pkg, "next") || !hasDependency(pkg, "react") || !hasDependency(pkg, "vite")) return null;
204
+ const devPort = await detectDevPort(cwd, pkg);
205
+ return {
206
+ id: "react",
207
+ appDir: "src",
208
+ devPort,
209
+ url: issuerFromPort(devPort)
210
+ };
211
+ }
212
+ };
213
+ //#endregion
214
+ //#region src/lib/orca/detectors/vue.ts
215
+ /**
216
+ * Detects a Vite + Vue single-page app: depends on `vue` and `vite` but NOT
217
+ * `nuxt` (Nuxt is its own meta-framework and ships Vue) — so the source dir is
218
+ * `src`, the dev port comes from the project, and the issuer is derived from it.
219
+ */
220
+ var VueDetector = class {
221
+ framework = "vue";
222
+ async detect(cwd) {
223
+ const pkg = await readPackageJson(cwd).catch(() => void 0);
224
+ if (!pkg || hasDependency(pkg, "nuxt") || !hasDependency(pkg, "vue") || !hasDependency(pkg, "vite")) return null;
225
+ const devPort = await detectDevPort(cwd, pkg);
226
+ return {
227
+ id: "vue",
228
+ appDir: "src",
229
+ devPort,
230
+ url: issuerFromPort(devPort)
231
+ };
232
+ }
233
+ };
234
+ //#endregion
235
+ //#region src/lib/orca/detectors/index.ts
236
+ /**
237
+ * Active detectors, in probe order. The orchestrator tries each until one
238
+ * recognises the project. Add a framework by appending its detector here — no
239
+ * orchestrator changes needed. Meta-frameworks run before their base: Next
240
+ * before React (Next ships React), and the Vue detector excludes Nuxt — so a
241
+ * Next/Nuxt project is never mistaken for a bare React/Vue SPA.
242
+ */
243
+ const detectors = [
244
+ new NextDetector(),
245
+ new NuxtDetector(),
246
+ new ReactDetector(),
247
+ new VueDetector(),
248
+ new AngularDetector()
249
+ ];
250
+ //#endregion
251
+ //#region src/lib/orca/patchers/rule/file-writer/index.ts
252
+ /**
253
+ * Applies a {@link ScaffoldPlan} to disk, executing its operations in order.
254
+ *
255
+ * Operations are idempotent: writes whose target already matches the desired
256
+ * contents are recorded as skipped rather than rewritten, so re-running setup
257
+ * is safe. With `dryRun` no filesystem changes are made but the result still
258
+ * reflects what would have been written. Existing files are only overwritten
259
+ * when `force` is set; otherwise an `E_CONFLICT` is thrown to protect
260
+ * user-authored content. Paths in the plan are resolved relative to `cwd`.
261
+ */
262
+ async function scaffold(plan, opts) {
263
+ const result = {
264
+ dryRun: opts.dryRun,
265
+ filesWritten: [],
266
+ filesSkipped: [],
267
+ depsAdded: []
268
+ };
269
+ for (const op of plan.ops) await applyOp(op, opts, result);
270
+ return result;
271
+ }
272
+ async function applyOp(op, opts, result) {
273
+ switch (op.kind) {
274
+ case "mkdir":
275
+ await ensureDir(abs(opts.cwd, op.path), op.mode, opts.dryRun, result);
276
+ break;
277
+ case "write":
278
+ await writeText(abs(opts.cwd, op.path), op.contents, {
279
+ mode: op.mode,
280
+ force: opts.force,
281
+ dryRun: opts.dryRun
282
+ }, result);
283
+ break;
284
+ case "append":
285
+ await appendText(abs(opts.cwd, op.path), op.contents, op.ifMissing, opts.dryRun, result);
286
+ break;
287
+ case "merge-env":
288
+ await mergeEnv(abs(opts.cwd, op.path), op.entries, opts.dryRun, result);
289
+ break;
290
+ case "merge-json":
291
+ await mergeJson(abs(opts.cwd, op.path), op.patch, opts.dryRun, result);
292
+ break;
293
+ case "append-gitignore":
294
+ await appendGitignore(abs(opts.cwd, ".gitignore"), op.entries, opts.dryRun, result);
295
+ break;
296
+ case "add-dep":
297
+ await addDependency(abs(opts.cwd, "package.json"), op, opts.dryRun, result);
298
+ break;
299
+ case "edit":
300
+ await editFile(opts.cwd, op.path, op.edit, opts.dryRun, result);
301
+ break;
302
+ }
303
+ }
304
+ /**
305
+ * Generic content edit: read the file, run the patcher-supplied transform, write
306
+ * the result. Framework knowledge lives entirely in `edit` (next to its
307
+ * patcher); this executor only owns candidate resolution, idempotency, dry-run,
308
+ * and the atomic write. `pathOrPaths` may be a single path or a priority list of
309
+ * candidates — the first that exists wins, else the first candidate.
310
+ */
311
+ async function editFile(cwd, pathOrPaths, edit, dryRun, result) {
312
+ const candidates = (typeof pathOrPaths === "string" ? [pathOrPaths] : pathOrPaths).map((p) => abs(cwd, p));
313
+ if (candidates.length === 0) throw new ZitadelError("E_VALIDATION", "An edit op needs at least one candidate path", { hint: "This is an internal patcher error — please report it if you hit it." });
314
+ let path = candidates[0];
315
+ let source;
316
+ let mode;
317
+ for (const candidate of candidates) {
318
+ const contents = await readIfExists(candidate);
319
+ if (contents !== void 0) {
320
+ path = candidate;
321
+ source = contents;
322
+ mode = (await stat(candidate)).mode & 511;
323
+ break;
324
+ }
325
+ }
326
+ const next = edit(source);
327
+ if (next === source) {
328
+ result.filesSkipped.push(path);
329
+ return;
330
+ }
331
+ if (dryRun) {
332
+ result.filesWritten.push(path);
333
+ return;
334
+ }
335
+ await mkdir(dirname(path), { recursive: true });
336
+ const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;
337
+ await writeFile(tmp, next);
338
+ if (mode !== void 0) await chmod(tmp, mode).catch(() => void 0);
339
+ await rename(tmp, path);
340
+ result.filesWritten.push(path);
341
+ }
342
+ async function ensureDir(path, mode, dryRun, result) {
343
+ if (dryRun) {
344
+ result.filesWritten.push(path);
345
+ return;
346
+ }
347
+ await mkdir(path, {
348
+ recursive: true,
349
+ mode
350
+ });
351
+ if (mode) await chmod(path, mode).catch(() => void 0);
352
+ result.filesWritten.push(path);
353
+ }
354
+ async function writeText(path, contents, opts, result) {
355
+ const existing = await readIfExists(path);
356
+ if (existing === contents) {
357
+ result.filesSkipped.push(path);
358
+ return;
359
+ }
360
+ if (existing !== void 0 && !opts.force) throw new ZitadelError("E_CONFLICT", `Refusing to overwrite ${path}`, {
361
+ hint: "Re-run with --force if you want the CLI to replace this file.",
362
+ details: { path }
363
+ });
364
+ if (opts.dryRun) {
365
+ result.filesWritten.push(path);
366
+ return;
367
+ }
368
+ await mkdir(dirname(path), { recursive: true });
369
+ const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;
370
+ await writeFile(tmp, contents, { mode: opts.mode });
371
+ if (opts.mode) await chmod(tmp, opts.mode).catch(() => void 0);
372
+ await rename(tmp, path);
373
+ result.filesWritten.push(path);
374
+ }
375
+ async function appendText(path, contents, ifMissing, dryRun, result) {
376
+ const existing = await readIfExists(path) ?? "";
377
+ if (ifMissing && existing.includes(ifMissing)) {
378
+ result.filesSkipped.push(path);
379
+ return;
380
+ }
381
+ const next = `${existing}${existing && !existing.endsWith("\n") ? "\n" : ""}${contents}`;
382
+ if (next === existing) {
383
+ result.filesSkipped.push(path);
384
+ return;
385
+ }
386
+ if (dryRun) {
387
+ result.filesWritten.push(path);
388
+ return;
389
+ }
390
+ await mkdir(dirname(path), { recursive: true });
391
+ await writeFile(path, next);
392
+ result.filesWritten.push(path);
393
+ }
394
+ async function mergeEnv(path, entries, dryRun, result) {
395
+ const existing = await readIfExists(path) ?? "";
396
+ const present = new Set(existing.split(/\r?\n/g).map((line) => line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)=/)?.[1]).filter((value) => Boolean(value)));
397
+ const additions = Object.entries(entries).filter(([key]) => !present.has(key));
398
+ if (additions.length === 0) {
399
+ result.filesSkipped.push(path);
400
+ return;
401
+ }
402
+ const block = additions.map(([key, value]) => `${key}=${value}`).join("\n");
403
+ const next = `${existing}${existing && !existing.endsWith("\n") ? "\n" : ""}${block}\n`;
404
+ if (dryRun) {
405
+ result.filesWritten.push(path);
406
+ return;
407
+ }
408
+ await mkdir(dirname(path), { recursive: true });
409
+ await writeFile(path, next);
410
+ result.filesWritten.push(path);
411
+ }
412
+ async function mergeJson(path, patch, dryRun, result) {
413
+ const existing = await readIfExists(path);
414
+ const contents = `${stableStringify(deepMerge(existing ? parseJsonObject(existing, path) : {}, patch))}\n`;
415
+ if (existing === contents) {
416
+ result.filesSkipped.push(path);
417
+ return;
418
+ }
419
+ if (dryRun) {
420
+ result.filesWritten.push(path);
421
+ return;
422
+ }
423
+ await mkdir(dirname(path), { recursive: true });
424
+ await writeFile(path, contents);
425
+ result.filesWritten.push(path);
426
+ }
427
+ async function appendGitignore(path, entries, dryRun, result) {
428
+ const existing = await readIfExists(path) ?? "";
429
+ const lines = new Set(existing.split(/\r?\n/g).map((line) => line.trim()));
430
+ const missing = entries.filter((entry) => !lines.has(entry));
431
+ if (missing.length === 0) {
432
+ result.filesSkipped.push(path);
433
+ return;
434
+ }
435
+ const next = `${existing}${existing && !existing.endsWith("\n") ? "\n" : ""}${missing.join("\n")}\n`;
436
+ if (dryRun) {
437
+ result.filesWritten.push(path);
438
+ return;
439
+ }
440
+ await writeFile(path, next);
441
+ result.filesWritten.push(path);
442
+ }
443
+ async function addDependency(path, op, dryRun, result) {
444
+ const existing = await readIfExists(path);
445
+ if (!existing) throw new ZitadelError("E_VALIDATION", "package.json is required to add Zitadel dependencies");
446
+ const current = parseJsonObject(existing, path);
447
+ const key = op.dev ? "devDependencies" : "dependencies";
448
+ const deps = isObject(current[key]) ? current[key] : {};
449
+ if (deps[op.name] === op.version) {
450
+ result.filesSkipped.push(path);
451
+ return;
452
+ }
453
+ current[key] = {
454
+ ...deps,
455
+ [op.name]: op.version
456
+ };
457
+ const contents = `${stableStringify(current)}\n`;
458
+ if (dryRun) {
459
+ result.filesWritten.push(path);
460
+ result.depsAdded.push(op.name);
461
+ return;
462
+ }
463
+ await writeFile(path, contents);
464
+ result.filesWritten.push(path);
465
+ result.depsAdded.push(op.name);
466
+ }
467
+ async function readIfExists(path) {
468
+ try {
469
+ return await readFile(path, "utf8");
470
+ } catch (error) {
471
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return;
472
+ throw error;
473
+ }
474
+ }
475
+ function abs(cwd, path) {
476
+ return join(cwd, path);
477
+ }
478
+ function deepMerge(target, patch) {
479
+ const out = { ...target };
480
+ for (const [key, value] of Object.entries(patch)) if (isObject(value) && isObject(out[key])) out[key] = deepMerge(out[key], value);
481
+ else out[key] = value;
482
+ return out;
483
+ }
484
+ //#endregion
485
+ //#region src/lib/orca/patchers/rule/reclaim.ts
486
+ /**
487
+ * The subset of a patcher plan's operations that `doctor --fix` re-applies:
488
+ * env merges, gitignore entries, dependency additions, marker-bearing managed
489
+ * files (framework routes/middleware), and the `edit` transforms — the
490
+ * `/__nextgen` dev proxy merged into `vite.config`/`nuxt.config`/`angular.json`
491
+ * and the Angular `dev` script added to `package.json`. Every `edit` transform
492
+ * is idempotent and only adds what is missing (an existing value is left as-is,
493
+ * the transform returning the source unchanged), so replaying one restores a
494
+ * removed managed block without clobbering the user's own edits. Deliberately
495
+ * excludes the unmarked `.zitadel/` resource writes and `zitadel.json` — those
496
+ * are user-editable and synced by `apply`, so `--fix` must not clobber them.
497
+ *
498
+ * Pure: filters a freshly-allocated list; the input plan is not mutated.
499
+ */
500
+ function reclaimableOps(plan) {
501
+ return plan.ops.filter((op) => op.kind === "merge-env" || op.kind === "append-gitignore" || op.kind === "add-dep" || op.kind === "edit" || op.kind === "write" && op.contents.includes("// zitadel-cli: managed-file v1"));
502
+ }
503
+ //#endregion
504
+ //#region src/lib/orca/patchers/rule/base.ts
505
+ /**
506
+ * Base for rule-based (deterministic, template-driven) patchers, as opposed to
507
+ * a future LLM-driven family. It applies the integration by building a
508
+ * file-operation plan and running the file-writer — that strategy stays
509
+ * entirely inside this family, so callers only ever see the family-neutral
510
+ * {@link Patcher} surface. Owns the framework-agnostic `.zitadel/` base files
511
+ * and the shared eject classification; subclasses contribute only their
512
+ * framework-specific routes/middleware.
513
+ */
514
+ var AbstractRulePatcher = class {
515
+ /** Apply the full plan (base `.zitadel/` files + framework routes). */
516
+ async patch(ctx, opts) {
517
+ return scaffold(this.plan(ctx), opts);
518
+ }
519
+ /**
520
+ * Re-apply only the reclaimable subset — env files, gitignore, the SDK
521
+ * dependency, and marker-bearing routes — leaving the user-editable
522
+ * `.zitadel/` resources untouched. Backs `doctor --fix`.
523
+ */
524
+ async repair(ctx, opts) {
525
+ const plan = this.plan(ctx);
526
+ return scaffold({
527
+ ops: reclaimableOps(plan),
528
+ summary: plan.summary
529
+ }, opts);
530
+ }
531
+ /** Shared base artifacts plus the subclass's marker-bearing route files. */
532
+ artifacts(view) {
533
+ return {
534
+ markedFiles: this.routeFiles(view),
535
+ rootConfigFiles: ["zitadel.json"],
536
+ directories: [".zitadel"],
537
+ envBackups: [".env.local"],
538
+ dependencies: this.routeDeps(view),
539
+ configEdits: this.routeConfigEdits(view)
540
+ };
541
+ }
542
+ /**
543
+ * User config files this patcher merges into via an `edit` op (e.g.
544
+ * `vite.config.ts`). `eject` can't reverse an in-place merge, so it lists
545
+ * these as manual cleanup steps. Defaults to none; patchers that edit a config
546
+ * (React/Vue/Angular/Nuxt) override it. Next writes whole marker-bearing files
547
+ * instead, so it has none.
548
+ */
549
+ routeConfigEdits(_view) {
550
+ return [];
551
+ }
552
+ /**
553
+ * The full file-operation plan this patcher would apply. Public so rule-family
554
+ * unit tests can assert the planned ops directly; the generic {@link Patcher}
555
+ * interface deliberately does not expose it (an LLM patcher has no such plan).
556
+ */
557
+ plan(ctx) {
558
+ return {
559
+ ops: [...this.baseOps(ctx), ...this.routeOps(ctx)],
560
+ summary: [this.summary(ctx)]
561
+ };
562
+ }
563
+ /**
564
+ * The framework-agnostic `.zitadel/` base files every rule patcher writes:
565
+ * the project secret, `zitadel.json`, env templates, and an empty sync
566
+ * state. The `schemas/` and `flows/` directories are created empty — the
567
+ * server provisions the default user schema and flow definition when the
568
+ * project is created, so nothing is scaffolded into them here. Pure: no
569
+ * filesystem or network.
570
+ */
571
+ baseOps(ctx) {
572
+ return [
573
+ {
574
+ kind: "mkdir",
575
+ path: ".zitadel",
576
+ mode: 448
577
+ },
578
+ {
579
+ kind: "mkdir",
580
+ path: ".zitadel/flows"
581
+ },
582
+ {
583
+ kind: "mkdir",
584
+ path: ".zitadel/schemas"
585
+ },
586
+ {
587
+ kind: "append-gitignore",
588
+ entries: [
589
+ ".zitadel/secret",
590
+ ".env*",
591
+ "!.env.example"
592
+ ]
593
+ },
594
+ {
595
+ kind: "write",
596
+ path: ".zitadel/secret",
597
+ mode: 384,
598
+ contents: `${stableStringify({
599
+ project_id: ctx.project.id,
600
+ project_secret: ctx.project.projectSecret,
601
+ preview_secret: ctx.project.previewSecret,
602
+ preview_origins: ctx.project.previewOrigins,
603
+ created_at: ctx.project.createdAt
604
+ })}\n`
605
+ },
606
+ {
607
+ kind: "write",
608
+ path: "zitadel.json",
609
+ contents: `${stableStringify(projectConfig(ctx))}\n`
610
+ },
611
+ {
612
+ kind: "merge-env",
613
+ path: ".env.example",
614
+ entries: {
615
+ ZITADEL_PROJECT_ID: "",
616
+ ZITADEL_ENVIRONMENT: "",
617
+ ZITADEL_ISSUER: "",
618
+ ZITADEL_URL: ""
619
+ }
620
+ },
621
+ {
622
+ kind: "merge-env",
623
+ path: ".env.local",
624
+ entries: {
625
+ ZITADEL_PROJECT_ID: ctx.project.id,
626
+ ZITADEL_ENVIRONMENT: "development",
627
+ ZITADEL_ISSUER: ctx.issuer,
628
+ ZITADEL_URL: ctx.server
629
+ }
630
+ },
631
+ {
632
+ kind: "write",
633
+ path: ".zitadel/state.json",
634
+ contents: `${stableStringify({
635
+ framework: ctx.framework.id,
636
+ resources: {}
637
+ })}\n`
638
+ }
639
+ ];
640
+ }
641
+ };
642
+ /** Builds the `zitadel.json` body persisted at the project root. */
643
+ function projectConfig(ctx) {
644
+ const environments = { development: { issuer: ctx.issuer } };
645
+ if (ctx.project.previewOrigins.length > 0) environments.preview = { issuer_pattern: [...ctx.project.previewOrigins] };
646
+ return {
647
+ $schema: "https://schemas.zitadel.com/v2/project.schema.json",
648
+ project: ctx.project.id,
649
+ server: resolveServerOrigin(ctx.server),
650
+ framework: { id: ctx.framework.id },
651
+ branding: {
652
+ renderer: ctx.rendererId,
653
+ attribution: "visible"
654
+ },
655
+ environments
656
+ };
657
+ }
658
+ /** Normalizes a server URL to its origin, falling back to {@link DEFAULT_SERVER}. */
659
+ function resolveServerOrigin(source) {
660
+ try {
661
+ return new URL(source).origin;
662
+ } catch {
663
+ return DEFAULT_SERVER;
664
+ }
665
+ }
666
+ //#endregion
667
+ //#region src/lib/orca/patchers/rule/angular/angular-json.ts
668
+ /**
669
+ * Builds the pure `edit` transform the file-writer applies to `angular.json`:
670
+ * wires a dev-server `proxyConfig` (and optional `port`) into the project's
671
+ * `serve` target. The project name is discovered from the file (`defaultProject`,
672
+ * else the sole project) rather than hardcoded, since it varies per app.
673
+ * Idempotent — already-set values are left as-is. Throws `E_VALIDATION` when the
674
+ * file is absent, the project/serve target cannot be located, or the workspace
675
+ * has several projects with no `defaultProject` to disambiguate (rather than
676
+ * guessing and wiring the proxy into an arbitrary one).
677
+ */
678
+ function angularProxyEdit(opts) {
679
+ return (source) => {
680
+ if (source === void 0) throw new ZitadelError("E_VALIDATION", "Cannot wire Angular proxy: angular.json not found", { hint: "Run setup from an Angular project." });
681
+ const root = parseJsonObject(source, "angular.json");
682
+ const projects = isObject(root.projects) ? root.projects : void 0;
683
+ const projectNames = Object.keys(projects ?? {});
684
+ let projectName;
685
+ if (typeof root.defaultProject === "string") projectName = root.defaultProject;
686
+ else if (projectNames.length === 1) projectName = projectNames[0];
687
+ else if (projectNames.length > 1) throw new ZitadelError("E_VALIDATION", "angular.json has multiple projects and no defaultProject to choose from", { hint: `Set "defaultProject" in angular.json, or add "proxyConfig" to the right project's serve target manually. Projects: ${projectNames.join(", ")}.` });
688
+ const project = projects && projectName ? projects[projectName] : void 0;
689
+ if (!isObject(project)) throw new ZitadelError("E_VALIDATION", "No project found in angular.json", { hint: "Add \"proxyConfig\" to your serve target manually." });
690
+ const targets = isObject(project.architect) ? project.architect : isObject(project.targets) ? project.targets : void 0;
691
+ const serve = targets && isObject(targets.serve) ? targets.serve : void 0;
692
+ if (!serve) throw new ZitadelError("E_VALIDATION", "No serve target in angular.json", { hint: "Add \"proxyConfig\" to your serve options manually." });
693
+ const options = isObject(serve.options) ? serve.options : {};
694
+ let changed = false;
695
+ if (options.proxyConfig === void 0) {
696
+ options.proxyConfig = opts.proxyConfig;
697
+ changed = true;
698
+ }
699
+ if (opts.port !== void 0 && options.port === void 0) {
700
+ options.port = opts.port;
701
+ changed = true;
702
+ }
703
+ if (!changed) return source;
704
+ serve.options = options;
705
+ return `${JSON.stringify(root, null, 2)}\n`;
706
+ };
707
+ }
708
+ //#endregion
709
+ //#region src/lib/orca/patchers/rule/utils/magicast.ts
710
+ /**
711
+ * Generic magicast helpers shared by the config-editing patchers (Vite, Nuxt).
712
+ * They navigate a module's default export — they carry no framework knowledge
713
+ * beyond "find the config object literal" and "is this import present".
714
+ */
715
+ /**
716
+ * Parses a config file with magicast, throwing a clean `E_VALIDATION` (instead
717
+ * of a raw parse error) when the source is missing or unparseable. `filename` is
718
+ * only used in the error message, so each patcher can name its own config file.
719
+ */
720
+ function parseConfigModule(source, filename) {
721
+ if (source === void 0) throw new ZitadelError("E_VALIDATION", `Cannot edit ${filename}: file not found`, { hint: `Run setup from a project that has ${filename}.` });
722
+ let mod;
723
+ try {
724
+ mod = parseModule(source);
725
+ } catch (error) {
726
+ throw new ZitadelError("E_VALIDATION", `Could not parse ${filename}`, {
727
+ hint: `Ensure ${filename} is valid, or apply the Zitadel changes manually.`,
728
+ details: { cause: error instanceof Error ? error.message : String(error) }
729
+ });
730
+ }
731
+ if (hasCommonJsExport(mod)) throw new ZitadelError("E_VALIDATION", `${filename} is a CommonJS module, which can't be edited`, { hint: `The Zitadel edits use ESM imports. Convert the config to ESM (a .ts/.mts file, or set "type": "module"), or add the Zitadel block manually.` });
732
+ return mod;
733
+ }
734
+ /**
735
+ * Whether the module has a top-level CommonJS export assignment —
736
+ * `module.exports = …`, `module.exports.x = …`, or `exports.x = …` — read from
737
+ * the parsed AST so comments and string literals can't trigger a false match.
738
+ */
739
+ function hasCommonJsExport(mod) {
740
+ return ((mod?.$ast?.program ?? mod?.$ast)?.body ?? []).some((node) => {
741
+ if (node?.type !== "ExpressionStatement" || node.expression?.type !== "AssignmentExpression") return false;
742
+ const left = node.expression.left;
743
+ if (left?.type !== "MemberExpression") return false;
744
+ const object = left.object;
745
+ if (object?.type === "Identifier" && object.name === "exports") return true;
746
+ if (object?.type === "Identifier" && object.name === "module" && left.property?.name === "exports") return true;
747
+ return object?.type === "MemberExpression" && object.object?.name === "module" && object.property?.name === "exports";
748
+ });
749
+ }
750
+ /**
751
+ * Reaches the object literal of a module's default export — the argument of
752
+ * `export default <call>({...})` (e.g. `defineConfig`/`defineNuxtConfig`) or a
753
+ * bare `export default {...}`. Throws `E_VALIDATION` for shapes magicast cannot
754
+ * safely edit (function-form, configs built elsewhere) so the caller can fall
755
+ * back to manual steps.
756
+ */
757
+ function resolveDefaultExportObject(mod, filename) {
758
+ const def = mod.exports?.default;
759
+ const unreachable = () => new ZitadelError("E_VALIDATION", `Could not locate the config object in ${filename}`, { hint: `Add the Zitadel configuration to ${filename} manually (see the SDK README).` });
760
+ if (!def) throw unreachable();
761
+ if (def.$type === "function-call") {
762
+ const arg = def.$args?.[0];
763
+ if (!arg || arg.$type !== "object") throw unreachable();
764
+ return arg;
765
+ }
766
+ if (def.$type === "object") return def;
767
+ throw unreachable();
768
+ }
769
+ function importIsPresent(mod, local, from) {
770
+ try {
771
+ return (mod.imports?.$items ?? []).some((item) => item.local === local && (from === void 0 || item.from === from));
772
+ } catch {
773
+ return false;
774
+ }
775
+ }
776
+ /**
777
+ * Appends `item` to a string array at `parent[key]`, creating the array when
778
+ * absent and skipping it when already present. Reads the proxified array by
779
+ * index so primitive elements compare as plain values. Returns `true` when it
780
+ * actually added the item, so callers can tell whether the edit changed
781
+ * anything (and skip rewriting an already-complete config).
782
+ */
783
+ function ensureArrayItem(parent, key, item) {
784
+ if (parent[key] === void 0) {
785
+ parent[key] = [item];
786
+ return true;
787
+ }
788
+ const arr = parent[key];
789
+ if (typeof arr?.push !== "function" || typeof arr?.length !== "number") throw new ZitadelError("E_VALIDATION", `Could not add "${item}" to "${key}"`, { hint: `Add "${item}" to "${key}" in your config manually.` });
790
+ if (!Array.from({ length: arr.length }, (_unused, i) => arr[i]).includes(item)) {
791
+ arr.push(item);
792
+ return true;
793
+ }
794
+ return false;
795
+ }
796
+ /**
797
+ * Returns the object literal at `parent[key]`, creating an empty one when
798
+ * absent, so callers can safely descend into it. Throws `E_VALIDATION` when the
799
+ * key already holds something that is not an inline object literal (an
800
+ * identifier, spread, or function call) — magicast cannot edit those, and
801
+ * assigning into them otherwise throws a raw proxy `TypeError`. The object
802
+ * sibling of {@link ensureArrayItem}.
803
+ */
804
+ function ensureEditableObject(parent, key) {
805
+ if (parent[key] === void 0) parent[key] = {};
806
+ const value = parent[key];
807
+ if (value?.$type !== "object") throw new ZitadelError("E_VALIDATION", `Could not edit "${key}" in the config`, { hint: `Set "${key}" to an inline object literal, or add the Zitadel settings manually.` });
808
+ return value;
809
+ }
810
+ //#endregion
811
+ //#region src/lib/orca/patchers/rule/angular/angular-routes.ts
812
+ const AUTH_ROUTE_PATHS = [
813
+ "login",
814
+ "register",
815
+ "profile"
816
+ ];
817
+ /**
818
+ * Angular's default `ng new` app enables the router with an empty route table.
819
+ * That router rejects direct `/login` and `/profile` navigations, then rewrites
820
+ * the URL back to `/`. Add componentless routes for the auth paths so the root
821
+ * component can keep rendering based on `window.location.pathname` without
822
+ * requiring a router outlet.
823
+ */
824
+ function angularRoutesEdit() {
825
+ return (source) => {
826
+ const label = "src/app/app.routes.ts";
827
+ const mod = parseConfigModule(source, label);
828
+ const routes = mod.exports?.routes;
829
+ if (routes?.$type !== "array" || typeof routes.push !== "function") throw new ZitadelError("E_VALIDATION", "Cannot wire Angular auth routes", { hint: `Set "routes" in ${label} to an inline Routes array, or add /login, /register, and /profile manually.` });
830
+ const present = new Set(Array.from({ length: routes.length }, (_unused, index) => routes[index]?.path).filter((path) => typeof path === "string"));
831
+ let changed = false;
832
+ for (const path of AUTH_ROUTE_PATHS) {
833
+ if (present.has(path)) continue;
834
+ routes.push(builders.raw(`{ path: ${JSON.stringify(path)}, children: [] }`));
835
+ changed = true;
836
+ }
837
+ if (!changed && source !== void 0) return source;
838
+ const code = generateCode(mod).code;
839
+ return code.endsWith("\n") ? code : `${code}\n`;
840
+ };
841
+ }
842
+ //#endregion
843
+ //#region src/lib/orca/patchers/rule/proxy.ts
844
+ /**
845
+ * The same-origin path the SDK widgets call (`configureZitadel({ proxyPath })`),
846
+ * which every framework's dev proxy forwards to the backend. Framework-agnostic:
847
+ * Vite (React/Vue), Angular's dev-server proxy, and Nuxt's server middleware all
848
+ * key off the same prefix, so it lives here rather than in any one framework's
849
+ * patcher.
850
+ */
851
+ const PROXY_PATH = "/__nextgen";
852
+ //#endregion
853
+ //#region src/lib/orca/patchers/rule/angular/templates.ts
854
+ /**
855
+ * The managed root component `src/app/app.ts`: a standalone component that
856
+ * renders the `@zitadel/sdk-angular` widgets based on the current path. The
857
+ * project id (public, not secret) is inlined; the dev proxy in `proxy.conf.cjs`
858
+ * attaches the `sk_<project_id>` bearer (derived from that public id)
859
+ * server-side, and no secret reaches the browser.
860
+ */
861
+ function appComponentTemplate(projectId) {
862
+ return `${MANAGED_MARKER}
863
+ import { Component } from "@angular/core";
864
+ import {
865
+ ZitadelLoginComponent,
866
+ ZitadelLogoutComponent,
867
+ configureZitadel,
868
+ } from "@zitadel/sdk-angular";
869
+
870
+ @Component({
871
+ selector: "app-root",
872
+ standalone: true,
873
+ imports: [ZitadelLoginComponent, ZitadelLogoutComponent],
874
+ templateUrl: "./app.html",
875
+ })
876
+ export class App {
877
+ protected readonly project = configureZitadel({
878
+ projectId: ${JSON.stringify(projectId)},
879
+ proxyPath: "${PROXY_PATH}",
880
+ });
881
+ protected readonly path = window.location.pathname;
882
+ }
883
+ `;
884
+ }
885
+ /**
886
+ * The managed `src/app/app.html`. The marker lives in an HTML comment that still
887
+ * contains the literal managed-marker text, so eject/doctor stay marker-aware.
888
+ */
889
+ function appTemplateHtml() {
890
+ return `<!-- ${MANAGED_MARKER} -->
891
+ @if (path.startsWith('/profile')) {
892
+ <zitadel-auth-logout [project]="project" [postSignOutUrl]="'/login'"></zitadel-auth-logout>
893
+ } @else if (path.startsWith('/register')) {
894
+ <zitadel-auth-login
895
+ [project]="project"
896
+ purpose="register"
897
+ [postSignInUrl]="'/profile'"
898
+ ></zitadel-auth-login>
899
+ } @else {
900
+ <zitadel-auth-login
901
+ [project]="project"
902
+ purpose="login"
903
+ [postSignInUrl]="'/profile'"
904
+ ></zitadel-auth-login>
905
+ }
906
+ `;
907
+ }
908
+ /**
909
+ * The managed `proxy.conf.cjs` for `ng serve`: forwards `/__nextgen/*` to the
910
+ * backend (from `zitadel.json`), strips the prefix, and attaches the project's
911
+ * `sk_<project_id>` bearer to every proxied request. The prefix strip and the
912
+ * bearer are each provided in both the http-proxy-middleware form
913
+ * (`pathRewrite`/`onProxyReq`) and the Vite form (`rewrite`/`configure`), so
914
+ * both fire whichever proxy layer Angular's dev server uses.
915
+ */
916
+ function proxyConfTemplate() {
917
+ return `${MANAGED_MARKER}
918
+ const { readFileSync } = require("node:fs");
919
+
920
+ const config = JSON.parse(readFileSync("zitadel.json", "utf8"));
921
+ if (!config.project || !config.server) {
922
+ throw new Error("zitadel.json is missing \\"project\\" or \\"server\\"; re-run zitadel setup.");
923
+ }
924
+ const bearer = \`Bearer sk_\${config.project}\`;
925
+
926
+ function setBearer(proxyReq) {
927
+ proxyReq.setHeader("authorization", bearer);
928
+ }
929
+
930
+ function stripPrefix(path) {
931
+ return path.replace(/^\\${PROXY_PATH}/, "").replace(/^(?!\\/)/, "/");
932
+ }
933
+
934
+ module.exports = {
935
+ "${PROXY_PATH}": {
936
+ target: config.server,
937
+ changeOrigin: false,
938
+ pathRewrite: stripPrefix,
939
+ rewrite: stripPrefix,
940
+ onProxyReq: setBearer,
941
+ configure: (proxy) => proxy.on("proxyReq", setBearer),
942
+ },
943
+ };
944
+ `;
945
+ }
946
+ //#endregion
947
+ //#region src/lib/orca/patchers/rule/angular/index.ts
948
+ const SDK_DEPENDENCY$3 = "@zitadel/sdk-angular";
949
+ /**
950
+ * Adds a `dev: "ng serve"` script only when the project does not already define
951
+ * one. `ng new` ships only a `start` script, but the CLI tells every framework
952
+ * to run `npm run dev` (and `ng serve` reads the proxy + port from
953
+ * `angular.json`). Non-destructive: an existing `dev` script is preserved, so
954
+ * patching a project that already wires its own `dev` leaves it untouched.
955
+ */
956
+ function ensureDevScript(source) {
957
+ if (source === void 0) throw new ZitadelError("E_VALIDATION", "package.json is required to add the dev script", { hint: "Run setup from a project that has a package.json." });
958
+ const pkg = parseJsonObject(source, "package.json");
959
+ const scripts = isObject(pkg.scripts) ? pkg.scripts : void 0;
960
+ if (scripts?.dev !== void 0) return source;
961
+ pkg.scripts = {
962
+ ...scripts ?? {},
963
+ dev: "ng serve"
964
+ };
965
+ return `${stableStringify(pkg)}\n`;
966
+ }
967
+ /**
968
+ * Rule-based patcher for an Angular app. Inherits the shared `.zitadel/` base
969
+ * files from {@link AbstractRulePatcher} and contributes the managed root
970
+ * component (`app.ts`/`app.html`) that renders the `@zitadel/sdk-angular`
971
+ * widgets, a `proxy.conf.cjs` dev proxy (attaching the `sk_<project_id>` bearer
972
+ * to every proxied request) wired into `angular.json`, and the SDK dep.
973
+ *
974
+ * Unlike React/Vue (whose dev proxy lives in `vite.config.ts`), Angular owns its
975
+ * Vite config, so the proxy is a separate `proxy.conf.cjs` referenced from the
976
+ * `serve` target. Production still needs `@zitadel/edge-proxy`.
977
+ */
978
+ var AngularPatcher = class extends AbstractRulePatcher {
979
+ canPatch(framework) {
980
+ return framework === "angular";
981
+ }
982
+ routeOps(ctx) {
983
+ return [
984
+ {
985
+ kind: "write",
986
+ path: "src/app/app.ts",
987
+ contents: appComponentTemplate(ctx.project.id)
988
+ },
989
+ {
990
+ kind: "write",
991
+ path: "src/app/app.html",
992
+ contents: appTemplateHtml()
993
+ },
994
+ {
995
+ kind: "edit",
996
+ path: "src/app/app.routes.ts",
997
+ edit: angularRoutesEdit()
998
+ },
999
+ {
1000
+ kind: "write",
1001
+ path: "proxy.conf.cjs",
1002
+ contents: proxyConfTemplate()
1003
+ },
1004
+ {
1005
+ kind: "edit",
1006
+ path: "angular.json",
1007
+ edit: angularProxyEdit({
1008
+ proxyConfig: "proxy.conf.cjs",
1009
+ port: ctx.framework.devPort
1010
+ })
1011
+ },
1012
+ {
1013
+ kind: "edit",
1014
+ path: "package.json",
1015
+ edit: ensureDevScript
1016
+ },
1017
+ {
1018
+ kind: "add-dep",
1019
+ name: SDK_DEPENDENCY$3,
1020
+ version: npmDistTagForCliVersion(ctx.cliVersion)
1021
+ }
1022
+ ];
1023
+ }
1024
+ routeFiles(_view) {
1025
+ return [
1026
+ "src/app/app.ts",
1027
+ "src/app/app.html",
1028
+ "proxy.conf.cjs"
1029
+ ];
1030
+ }
1031
+ routeDeps(_view) {
1032
+ return [SDK_DEPENDENCY$3];
1033
+ }
1034
+ routeConfigEdits(_view) {
1035
+ return [
1036
+ "angular.json",
1037
+ "src/app/app.routes.ts",
1038
+ "package.json"
1039
+ ];
1040
+ }
1041
+ summary(_ctx) {
1042
+ return {
1043
+ title: "Angular integration",
1044
+ detail: "Wrote the app root component + proxy.conf.cjs, added auth routes, and wired the /__nextgen dev proxy into angular.json."
1045
+ };
1046
+ }
1047
+ };
1048
+ //#endregion
1049
+ //#region src/lib/orca/patchers/rule/next/renderers/lit/index.ts
1050
+ /**
1051
+ * Placeholder renderer for the `<zitadel-flow>` Lit web component. Declared
1052
+ * so the `web-component` renderer id resolves and surfaces a clear
1053
+ * "not yet published" error, while reserving the integration shape for when
1054
+ * `@zitadel/ui-lit` ships. The `authPage` template emits an illustrative
1055
+ * page only; this renderer is never selected for real scaffolding because
1056
+ * `getRenderer` rejects any `status: "not-implemented"` spec.
1057
+ */
1058
+ const litRenderer = {
1059
+ id: "web-component",
1060
+ displayName: "Web component (<zitadel-flow>)",
1061
+ status: "not-implemented",
1062
+ frameworks: [
1063
+ "next",
1064
+ "astro",
1065
+ "remix",
1066
+ "sveltekit",
1067
+ "nuxt",
1068
+ "vanilla"
1069
+ ],
1070
+ dependency: {
1071
+ name: "@zitadel/ui-lit",
1072
+ version: "workspace:*"
1073
+ },
1074
+ templates: { authPage(mode) {
1075
+ return {
1076
+ mode,
1077
+ contents: `${MANAGED_MARKER}
1078
+ // The web component renderer ships a <zitadel-flow> element. Until
1079
+ // @zitadel/ui-lit is published, this template only declares the
1080
+ // intended integration point. See docs/design/cli/bdui-renderer.md.
1081
+ import "@zitadel/ui-lit";
1082
+
1083
+ const environment =
1084
+ process.env.ZITADEL_ENVIRONMENT ??
1085
+ (process.env.NODE_ENV === "production" ? "production" : "development");
1086
+
1087
+ export default function ${mode === "login" ? "LoginPage" : "RegisterPage"}() {
1088
+ return (
1089
+ <zitadel-flow
1090
+ purpose="${mode === "login" ? "login" : "register"}"
1091
+ project-id={process.env.ZITADEL_PROJECT_ID}
1092
+ issuer={process.env.ZITADEL_ISSUER}
1093
+ environment={environment}
1094
+ />
1095
+ );
1096
+ }
1097
+ `
1098
+ };
1099
+ } }
1100
+ };
1101
+ //#endregion
1102
+ //#region src/lib/orca/patchers/rule/next/renderers/react/index.ts
1103
+ /**
1104
+ * The Next.js App Router renderer scaffolds `/login`, `/register`, and
1105
+ * `/profile` pages that drive the `<zitadel-login>` and `<zitadel-logout>`
1106
+ * Lit web components.
1107
+ *
1108
+ * Each page is a single client component (`"use client"`) that, inside a
1109
+ * `next/dynamic({ ssr: false })` loader, builds the SDK project handle with
1110
+ * `configureZitadel({ projectId, proxyPath: "/__nextgen" })` and passes it to
1111
+ * the widget via `project={...}`. It also imports
1112
+ * `@zitadel/sdk-next/client` for its `customElements.define`
1113
+ * side-effect — importing `@zitadel/components` directly would fail on
1114
+ * strict-resolution package managers (pnpm, yarn PnP) because the app only
1115
+ * declares `sdk-next` as a direct dep. SSR is disabled because Lit's element
1116
+ * registration needs a browser.
1117
+ *
1118
+ * The handle is passed as the `project` DOM property, which relies on React
1119
+ * 19's custom-element property binding (the scaffold targets the latest Next /
1120
+ * React). The backend URL never reaches the browser: the client talks to the
1121
+ * same-origin `/__nextgen` proxy path, and the scaffolded Next request boundary
1122
+ * forwards it to `ZITADEL_URL` server-side. `NEXT_PUBLIC_ZITADEL_PROJECT_ID` is
1123
+ * public — the project id is not sensitive and the widget needs it to start a
1124
+ * flow.
1125
+ */
1126
+ const reactRenderer = {
1127
+ id: "react",
1128
+ displayName: "React (Next.js App Router)",
1129
+ status: "available",
1130
+ frameworks: ["next"],
1131
+ dependency: {
1132
+ name: "@zitadel/sdk-next",
1133
+ version: "latest"
1134
+ },
1135
+ templates: {
1136
+ authPage(mode) {
1137
+ const componentName = mode === "login" ? "LoginPage" : "RegisterPage";
1138
+ const elementName = mode === "login" ? "ZitadelLogin" : "ZitadelRegister";
1139
+ return {
1140
+ mode,
1141
+ contents: `${MANAGED_MARKER}
1142
+ "use client";
1143
+
1144
+ import dynamic from "next/dynamic";
1145
+ import Link from "next/link";
1146
+
1147
+ const ${elementName} = dynamic(
1148
+ async () => {
1149
+ const { configureZitadel } = await import("@zitadel/sdk-next/client");
1150
+ // Build the SDK project handle and pass it to the component via the
1151
+ // \`project\` prop. The component reads config from this prop directly, so
1152
+ // it works regardless of how the SDK packages are bundled. The backend URL
1153
+ // stays server-side: requests go through the proxy path "/__nextgen",
1154
+ // which the scaffolded request boundary forwards to the Zitadel server.
1155
+ const project = configureZitadel({
1156
+ projectId: process.env.NEXT_PUBLIC_ZITADEL_PROJECT_ID ?? "",
1157
+ proxyPath: "/__nextgen",
1158
+ });
1159
+ return function ${elementName}Element() {
1160
+ return (
1161
+ <zitadel-login
1162
+ project={project}
1163
+ purpose="${mode}"
1164
+ post-sign-in-url="/profile"
1165
+ />
1166
+ );
1167
+ };
1168
+ },
1169
+ { ssr: false },
1170
+ );
1171
+
1172
+ export default function ${componentName}() {
1173
+ return (
1174
+ <main style={{ minHeight: "100vh", position: "relative", background: "#0f0f11" }}>
1175
+ <nav aria-label="Authentication" style={{ position: "absolute", top: "24px", right: "24px", zIndex: 1, display: "flex", gap: "12px" }}>
1176
+ <Link href="${mode === "login" ? "/register" : "/login"}" style={{ color: "#f4f4f6", fontWeight: 700, textDecoration: "none" }}>
1177
+ ${mode === "login" ? "Create account" : "Sign in"}
1178
+ </Link>
1179
+ </nav>
1180
+ <${elementName} />
1181
+ </main>
1182
+ );
1183
+ }
1184
+ `
1185
+ };
1186
+ },
1187
+ profilePage() {
1188
+ return { contents: `${MANAGED_MARKER}
1189
+ "use client";
1190
+
1191
+ import dynamic from "next/dynamic";
1192
+ import { useEffect, useState } from "react";
1193
+
1194
+ type SessionProof = {
1195
+ session_id?: string;
1196
+ state?: string;
1197
+ user_id?: string;
1198
+ };
1199
+
1200
+ const ZitadelLogout = dynamic(
1201
+ async () => {
1202
+ const { configureZitadel } = await import("@zitadel/sdk-next/client");
1203
+ const project = configureZitadel({
1204
+ projectId: process.env.NEXT_PUBLIC_ZITADEL_PROJECT_ID ?? "",
1205
+ proxyPath: "/__nextgen",
1206
+ });
1207
+ return function ZitadelLogoutElement() {
1208
+ return (
1209
+ <zitadel-logout
1210
+ project={project}
1211
+ post-sign-out-url="/login"
1212
+ />
1213
+ );
1214
+ };
1215
+ },
1216
+ { ssr: false },
1217
+ );
1218
+
1219
+ export default function ProfilePage() {
1220
+ const [session, setSession] = useState<SessionProof | null>(null);
1221
+ const [sessionError, setSessionError] = useState("");
1222
+
1223
+ useEffect(() => {
1224
+ let cancelled = false;
1225
+
1226
+ fetch("/__nextgen/sessions/me", { cache: "no-store" })
1227
+ .then(async (response) => {
1228
+ if (!response.ok) {
1229
+ throw new Error("Session check failed: " + String(response.status));
1230
+ }
1231
+ return response.json() as Promise<SessionProof>;
1232
+ })
1233
+ .then((nextSession) => {
1234
+ if (!cancelled) {
1235
+ setSession(nextSession);
1236
+ }
1237
+ })
1238
+ .catch((error: unknown) => {
1239
+ if (!cancelled) {
1240
+ setSessionError(error instanceof Error ? error.message : "Session check failed");
1241
+ }
1242
+ });
1243
+
1244
+ return () => {
1245
+ cancelled = true;
1246
+ };
1247
+ }, []);
1248
+
1249
+ return (
1250
+ <main style={{ padding: "48px", maxWidth: "680px", margin: "0 auto" }}>
1251
+ <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: "24px" }}>
1252
+ <h1 style={{ fontSize: "24px", fontWeight: 700, margin: 0 }}>Signed in</h1>
1253
+ <ZitadelLogout />
1254
+ </div>
1255
+ <p style={{ color: "#166534", fontWeight: 600 }}>Signed in profile loaded.</p>
1256
+ {session ? (
1257
+ <dl style={{ display: "grid", gap: "12px", marginTop: "24px" }}>
1258
+ <div>
1259
+ <dt style={{ color: "#6b7280", fontSize: "14px" }}>Session state</dt>
1260
+ <dd style={{ margin: 0, fontWeight: 600 }}>{session.state ?? "active"}</dd>
1261
+ </div>
1262
+ <div>
1263
+ <dt style={{ color: "#6b7280", fontSize: "14px" }}>User id</dt>
1264
+ <dd style={{ margin: 0, fontFamily: "monospace" }}>{session.user_id ?? "available"}</dd>
1265
+ </div>
1266
+ </dl>
1267
+ ) : (
1268
+ <p style={{ color: sessionError ? "#b91c1c" : "#6b7280" }}>
1269
+ {sessionError || "Checking session..."}
1270
+ </p>
1271
+ )}
1272
+ </main>
1273
+ );
1274
+ }
1275
+ ` };
1276
+ },
1277
+ customElementsDts() {
1278
+ return { contents: `${MANAGED_MARKER}
1279
+ import type React from "react";
1280
+ import type { ZitadelProject } from "@zitadel/sdk-next/client";
1281
+
1282
+ declare module "react" {
1283
+ namespace JSX {
1284
+ interface IntrinsicElements {
1285
+ "zitadel-login": React.HTMLAttributes<HTMLElement> & {
1286
+ project?: ZitadelProject;
1287
+ "session-exchange-path"?: string;
1288
+ "post-sign-in-url"?: string;
1289
+ purpose?: string;
1290
+ };
1291
+ "zitadel-logout": React.HTMLAttributes<HTMLElement> & {
1292
+ project?: ZitadelProject;
1293
+ "post-sign-out-url"?: string;
1294
+ };
1295
+ }
1296
+ }
1297
+ }
1298
+ ` };
1299
+ }
1300
+ }
1301
+ };
1302
+ //#endregion
1303
+ //#region src/lib/orca/patchers/rule/next/renderers/registry.ts
1304
+ /**
1305
+ * Runtime mirror of the {@link RendererId} union, used by {@link isRendererId}
1306
+ * to validate untrusted strings (a TS union has no runtime presence). Must stay
1307
+ * in sync with the {@link RendererId} type.
1308
+ */
1309
+ const RENDERER_IDS = ["react", "web-component"];
1310
+ /**
1311
+ * Type guard narrowing an arbitrary value to a {@link RendererId}, used to
1312
+ * validate renderer ids read from config before indexing {@link RENDERERS}.
1313
+ */
1314
+ function isRendererId(value) {
1315
+ return typeof value === "string" && RENDERER_IDS.includes(value);
1316
+ }
1317
+ /**
1318
+ * The single source of truth mapping each {@link RendererId} to its spec.
1319
+ * Keyed by id so {@link getRenderer} can look up and validate a renderer
1320
+ * chosen from persisted config (an arbitrary string) at runtime.
1321
+ */
1322
+ const RENDERERS = {
1323
+ react: reactRenderer,
1324
+ "web-component": litRenderer
1325
+ };
1326
+ /**
1327
+ * Resolves a renderer id (an untrusted string from config) to its spec,
1328
+ * throwing a typed {@link ZitadelError} rather than returning `undefined`
1329
+ * so callers get an actionable message. Rejects ids that are unknown
1330
+ * (`E_VALIDATION`) or declared-but-unpublished (`E_NOT_IMPLEMENTED`),
1331
+ * guaranteeing the returned spec is safe to scaffold from.
1332
+ */
1333
+ function getRenderer(id) {
1334
+ if (!isRendererId(id)) throw new ZitadelError("E_VALIDATION", `Unknown renderer "${id}"`, { hint: `Available renderers: ${Object.keys(RENDERERS).join(", ")}` });
1335
+ const renderer = RENDERERS[id];
1336
+ if (renderer.status === "not-implemented") throw new ZitadelError("E_NOT_IMPLEMENTED", `Renderer "${id}" is declared but not yet published`, { hint: "Use --renderer react for now; the <zitadel-flow> web component ships in a later package." });
1337
+ return renderer;
1338
+ }
1339
+ //#endregion
1340
+ //#region src/lib/orca/patchers/rule/next/index.ts
1341
+ /**
1342
+ * Next.js request-boundary file at the project root. Wires `nextgenMiddleware` so the
1343
+ * generated project config's `/__nextgen` proxy path is same-origin proxied
1344
+ * to `ZITADEL_URL` and `/profile` is gated. Next 16 renamed this convention to
1345
+ * `proxy.ts`; older projects keep `middleware.ts`.
1346
+ * Carries the managed marker so `doctor --fix` reclaims it and `eject` removes it.
1347
+ */
1348
+ function requestBoundaryTemplate(functionName) {
1349
+ return `${MANAGED_MARKER}
1350
+ import { nextgenMiddleware } from "@zitadel/sdk-next/middleware";
1351
+ import type { NextRequest } from "next/server";
1352
+
1353
+ export function ${functionName}(req: NextRequest) {
1354
+ return nextgenMiddleware(req, {
1355
+ url: process.env.ZITADEL_URL,
1356
+ protectedRoutes: ["/profile"],
1357
+ loginPath: "/login",
1358
+ });
1359
+ }
1360
+
1361
+ export const config = {
1362
+ matcher: ["/__nextgen/:path*", "/profile/:path*"],
1363
+ };
1364
+ `;
1365
+ }
1366
+ /**
1367
+ * Rule-based patcher for the Next.js App Router. Inherits the shared
1368
+ * `.zitadel/` base files from {@link AbstractRulePatcher} and contributes the
1369
+ * Next routes and request boundary whose templates come from the chosen renderer.
1370
+ */
1371
+ var NextPatcher = class extends AbstractRulePatcher {
1372
+ /** Returns true for Next.js projects. */
1373
+ canPatch(framework) {
1374
+ return framework === "next";
1375
+ }
1376
+ routeOps(ctx) {
1377
+ return nextCodeOps(ctx, getRenderer(ctx.rendererId));
1378
+ }
1379
+ routeFiles(view) {
1380
+ return nextCodeFilePaths(view.framework, getRenderer(view.rendererId));
1381
+ }
1382
+ routeDeps(view) {
1383
+ return [getRenderer(view.rendererId).dependency.name];
1384
+ }
1385
+ summary(ctx) {
1386
+ return {
1387
+ title: "Next.js integration",
1388
+ detail: `Scaffolded login/register/profile routes with renderer "${ctx.rendererId}".`
1389
+ };
1390
+ }
1391
+ };
1392
+ /**
1393
+ * Ordered paths of the framework code files the patcher writes. All carry the
1394
+ * managed marker. Shared by {@link NextPatcher.routeOps} (which adds contents)
1395
+ * and {@link NextPatcher.routeFiles} (which only needs the paths) so the two
1396
+ * cannot drift.
1397
+ */
1398
+ function nextCodeFilePaths(framework, renderer) {
1399
+ const appDir = framework.appDir;
1400
+ const paths = [
1401
+ join(appDir, "page.tsx"),
1402
+ join(appDir, "login/page.tsx"),
1403
+ join(appDir, "register/page.tsx")
1404
+ ];
1405
+ if (renderer.templates.profilePage) paths.push(join(appDir, "profile/page.tsx"));
1406
+ paths.push(join(appDir, `../${requestBoundaryFile(framework).filename}`));
1407
+ if (renderer.templates.provider) paths.push(join(appDir, renderer.templates.provider.filename));
1408
+ if (renderer.templates.customElementsDts) paths.push(join(appDir, "../custom-elements.d.ts"));
1409
+ return paths;
1410
+ }
1411
+ /** The Next route/request-boundary write ops plus the SDK dependency. */
1412
+ function nextCodeOps(ctx, renderer) {
1413
+ const appDir = ctx.framework.appDir;
1414
+ const profile = renderer.templates.profilePage?.();
1415
+ const provider = renderer.templates.provider;
1416
+ const dts = renderer.templates.customElementsDts?.();
1417
+ const boundary = requestBoundaryFile(ctx.framework);
1418
+ return [
1419
+ ctx.scaffoldedFramework ? {
1420
+ kind: "edit",
1421
+ path: join(appDir, "page.tsx"),
1422
+ edit: () => homePageTemplate()
1423
+ } : void 0,
1424
+ {
1425
+ kind: "write",
1426
+ path: join(appDir, "login/page.tsx"),
1427
+ contents: renderer.templates.authPage("login").contents
1428
+ },
1429
+ {
1430
+ kind: "write",
1431
+ path: join(appDir, "register/page.tsx"),
1432
+ contents: renderer.templates.authPage("register").contents
1433
+ },
1434
+ profile ? {
1435
+ kind: "write",
1436
+ path: join(appDir, "profile/page.tsx"),
1437
+ contents: profile.contents
1438
+ } : void 0,
1439
+ {
1440
+ kind: "write",
1441
+ path: join(appDir, `../${boundary.filename}`),
1442
+ contents: requestBoundaryTemplate(boundary.functionName)
1443
+ },
1444
+ provider ? {
1445
+ kind: "write",
1446
+ path: join(appDir, provider.filename),
1447
+ contents: provider.contents
1448
+ } : void 0,
1449
+ dts ? {
1450
+ kind: "write",
1451
+ path: join(appDir, "../custom-elements.d.ts"),
1452
+ contents: dts.contents
1453
+ } : void 0,
1454
+ {
1455
+ kind: "merge-env",
1456
+ path: ".env.example",
1457
+ entries: { NEXT_PUBLIC_ZITADEL_PROJECT_ID: "" }
1458
+ },
1459
+ {
1460
+ kind: "merge-env",
1461
+ path: ".env.local",
1462
+ entries: { NEXT_PUBLIC_ZITADEL_PROJECT_ID: ctx.project.id }
1463
+ },
1464
+ {
1465
+ kind: "add-dep",
1466
+ name: renderer.dependency.name,
1467
+ version: dependencyVersionForCli(ctx.cliVersion, renderer.dependency.version)
1468
+ }
1469
+ ].filter((op) => op !== void 0);
1470
+ }
1471
+ function homePageTemplate() {
1472
+ return `${MANAGED_MARKER}
1473
+ import Link from "next/link";
1474
+
1475
+ export default function Home() {
1476
+ return (
1477
+ <main style={{ minHeight: "100vh", padding: "48px", display: "flex", alignItems: "center", justifyContent: "center" }}>
1478
+ <section style={{ width: "100%", maxWidth: "560px" }}>
1479
+ <p style={{ margin: "0 0 12px", color: "#4b5563", fontSize: "14px" }}>Zitadel auth</p>
1480
+ <h1 style={{ margin: "0 0 24px", fontSize: "32px", lineHeight: 1.15 }}>Sign in, create an account, or open your profile.</h1>
1481
+ <div style={{ display: "flex", flexWrap: "wrap", gap: "12px" }}>
1482
+ <Link href="/login" style={{ padding: "10px 16px", borderRadius: "8px", background: "#111827", color: "#ffffff", textDecoration: "none", fontWeight: 600 }}>
1483
+ Sign in
1484
+ </Link>
1485
+ <Link href="/register" style={{ padding: "10px 16px", borderRadius: "8px", border: "1px solid #d1d5db", color: "#111827", textDecoration: "none", fontWeight: 600 }}>
1486
+ Create account
1487
+ </Link>
1488
+ <Link href="/profile" style={{ padding: "10px 16px", borderRadius: "8px", border: "1px solid #d1d5db", color: "#111827", textDecoration: "none", fontWeight: 600 }}>
1489
+ Profile
1490
+ </Link>
1491
+ </div>
1492
+ </section>
1493
+ </main>
1494
+ );
1495
+ }
1496
+ `;
1497
+ }
1498
+ function requestBoundaryFile(framework) {
1499
+ if ((framework.versionMajor ?? 0) >= 16) return {
1500
+ filename: "proxy.ts",
1501
+ functionName: "proxy"
1502
+ };
1503
+ return {
1504
+ filename: "middleware.ts",
1505
+ functionName: "middleware"
1506
+ };
1507
+ }
1508
+ function dependencyVersionForCli(cliVersion, fallback) {
1509
+ const normalized = cliVersion.trim().replace(/^v/, "");
1510
+ if (/^\d+\.\d+\.\d+-alpha\.\d+$/.test(normalized)) return normalized;
1511
+ return normalized.match(/^\d+\.\d+\.\d+-([0-9A-Za-z]+)(?:[.-]|$)/)?.[1] ?? fallback;
1512
+ }
1513
+ //#endregion
1514
+ //#region src/lib/orca/patchers/rule/config-paths.ts
1515
+ /**
1516
+ * The module extensions the config edits can actually write, in resolution
1517
+ * priority. magicast injects ESM `import`/`import.meta.url`, so only ESM-capable
1518
+ * extensions are editable; CommonJS (`cts`/`cjs`) is not.
1519
+ */
1520
+ const CONFIG_EXTENSIONS = [
1521
+ "ts",
1522
+ "mts",
1523
+ "js",
1524
+ "mjs"
1525
+ ];
1526
+ /**
1527
+ * The CommonJS extensions we still *probe* (after the ESM ones) so a project
1528
+ * whose only config is `*.cjs`/`*.cts` is found and rejected with a targeted
1529
+ * "CommonJS is unsupported" error, rather than a misleading "file not found".
1530
+ * {@link parseConfigModule} surfaces that error when it sees CommonJS source.
1531
+ */
1532
+ const COMMONJS_EXTENSIONS = ["cts", "cjs"];
1533
+ /**
1534
+ * Candidate config filenames for `basename`, ESM extensions first then the
1535
+ * CommonJS ones, e.g. `configCandidates("vite.config")` → `["vite.config.ts",
1536
+ * "vite.config.mts", "vite.config.js", "vite.config.mjs", "vite.config.cts",
1537
+ * "vite.config.cjs"]`. Handed to the
1538
+ * generic `edit` file-op, which patches the first one that exists — an ESM
1539
+ * config wins, and a CommonJS-only project is still read so the edit can emit a
1540
+ * clear unsupported-format error.
1541
+ */
1542
+ function configCandidates(basename) {
1543
+ return [...CONFIG_EXTENSIONS, ...COMMONJS_EXTENSIONS].map((ext) => `${basename}.${ext}`);
1544
+ }
1545
+ //#endregion
1546
+ //#region src/lib/orca/patchers/rule/nuxt/nuxt-config.ts
1547
+ const NUXT_MODULE = "@zitadel/sdk-nuxt/module";
1548
+ /**
1549
+ * Builds the pure `edit` transform the file-writer applies to the project's Nuxt
1550
+ * config (`nuxt.config.*`): registers the `@zitadel/sdk-nuxt` module (which wires
1551
+ * the server-side proxy + session middleware), sets the login path, seeds
1552
+ * `runtimeConfig` with the backend URL, the proxy path, and the project id, and
1553
+ * marks the `zitadel-*` Lit elements as custom elements for the Vue compiler —
1554
+ * preserving the user's existing config via magicast. Idempotent. Throws
1555
+ * `E_VALIDATION` when the file is absent or `defineNuxtConfig` cannot be reached.
1556
+ */
1557
+ function nuxtConfigEdit(opts) {
1558
+ return (source) => {
1559
+ const label = "the Nuxt config (nuxt.config.*)";
1560
+ const mod = parseConfigModule(source, label);
1561
+ const config = resolveDefaultExportObject(mod, label);
1562
+ let changed = ensureArrayItem(config, "modules", NUXT_MODULE);
1563
+ const nextgen = ensureEditableObject(config, "nextgen");
1564
+ if (nextgen.url === void 0) {
1565
+ nextgen.url = builders.raw(`process.env.ZITADEL_URL ?? ${JSON.stringify(opts.server)}`);
1566
+ changed = true;
1567
+ }
1568
+ if (nextgen.loginPath === void 0) {
1569
+ nextgen.loginPath = "/login";
1570
+ changed = true;
1571
+ }
1572
+ if (nextgen.protectedRoutes === void 0) {
1573
+ nextgen.protectedRoutes = ["/profile"];
1574
+ changed = true;
1575
+ }
1576
+ const runtimeConfig = ensureEditableObject(config, "runtimeConfig");
1577
+ if (runtimeConfig.zitadelUrl === void 0) {
1578
+ runtimeConfig.zitadelUrl = builders.raw(`process.env.ZITADEL_URL ?? ${JSON.stringify(opts.server)}`);
1579
+ changed = true;
1580
+ }
1581
+ const publicConfig = ensureEditableObject(runtimeConfig, "public");
1582
+ if (publicConfig.nextgenProxyPath === void 0) {
1583
+ publicConfig.nextgenProxyPath = PROXY_PATH;
1584
+ changed = true;
1585
+ }
1586
+ if (publicConfig.zitadelProjectId === void 0) {
1587
+ publicConfig.zitadelProjectId = builders.raw(`process.env.NUXT_PUBLIC_ZITADEL_PROJECT_ID ?? ${JSON.stringify(opts.projectId)}`);
1588
+ changed = true;
1589
+ }
1590
+ const build = ensureEditableObject(config, "build");
1591
+ for (const dep of [
1592
+ "@zitadel/api",
1593
+ "@zitadel/components",
1594
+ "@zitadel/shared-component-styles",
1595
+ "@zitadel/design-tokens"
1596
+ ]) if (ensureArrayItem(build, "transpile", dep)) changed = true;
1597
+ const compilerOptions = ensureEditableObject(ensureEditableObject(config, "vue"), "compilerOptions");
1598
+ if (compilerOptions.isCustomElement === void 0) {
1599
+ compilerOptions.isCustomElement = builders.raw(`(tag) => tag.startsWith("zitadel-")`);
1600
+ changed = true;
1601
+ }
1602
+ if (!changed && source !== void 0) return source;
1603
+ const code = generateCode(mod).code;
1604
+ return code.endsWith("\n") ? code : `${code}\n`;
1605
+ };
1606
+ }
1607
+ //#endregion
1608
+ //#region src/lib/orca/patchers/rule/nuxt/templates.ts
1609
+ const MAIN_STYLE = "min-height: 100vh; background: #0f0f11";
1610
+ /** `app.vue` — renders the page router. Marker in an HTML comment. */
1611
+ function appVueTemplate() {
1612
+ return `<!-- ${MANAGED_MARKER} -->
1613
+ <template>
1614
+ <NuxtPage />
1615
+ </template>
1616
+
1617
+ <style>
1618
+ body {
1619
+ margin: 0;
1620
+ font-family: sans-serif;
1621
+ }
1622
+ </style>
1623
+ `;
1624
+ }
1625
+ /** A login/register page rendering `<zitadel-login>` inside `<ClientOnly>`. */
1626
+ function authPage(purpose) {
1627
+ return `<script setup lang="ts">
1628
+ ${MANAGED_MARKER}
1629
+ import { useZitadelProject } from "@zitadel/sdk-nuxt";
1630
+
1631
+ const project = useZitadelProject();
1632
+ <\/script>
1633
+
1634
+ <template>
1635
+ <main style="${MAIN_STYLE}">
1636
+ <ClientOnly>
1637
+ <zitadel-login
1638
+ :project="project"${purpose === "register" ? "\n purpose=\"register\"" : ""}
1639
+ post-sign-in-url="/profile"
1640
+ />
1641
+ </ClientOnly>
1642
+ </main>
1643
+ </template>
1644
+ `;
1645
+ }
1646
+ function loginPageTemplate() {
1647
+ return authPage("login");
1648
+ }
1649
+ function registerPageTemplate() {
1650
+ return authPage("register");
1651
+ }
1652
+ /** `pages/profile.vue` — the signed-in view with the logout widget. */
1653
+ function profilePageTemplate() {
1654
+ return `<script setup lang="ts">
1655
+ ${MANAGED_MARKER}
1656
+ import { useZitadelProject } from "@zitadel/sdk-nuxt";
1657
+
1658
+ const project = useZitadelProject();
1659
+ <\/script>
1660
+
1661
+ <template>
1662
+ <main style="padding: 24px">
1663
+ <h1>Signed in (Nuxt)</h1>
1664
+ <ClientOnly>
1665
+ <zitadel-logout :project="project" post-sign-out-url="/login" />
1666
+ </ClientOnly>
1667
+ </main>
1668
+ </template>
1669
+ `;
1670
+ }
1671
+ /** `plugins/zitadel-components.client.ts` — register the Lit elements client-side. */
1672
+ function componentsPluginTemplate() {
1673
+ return `${MANAGED_MARKER}
1674
+ // Register Lit custom elements on the client only. Importing @zitadel/components
1675
+ // from a page <script setup> would run during SSR and break the widgets.
1676
+ import "@zitadel/components";
1677
+
1678
+ export default defineNuxtPlugin(() => {});
1679
+ `;
1680
+ }
1681
+ /** `plugins/auth.server.ts` — seed the client auth state from the server context. */
1682
+ function authPluginTemplate() {
1683
+ return `${MANAGED_MARKER}
1684
+ import { defineNuxtPlugin, useRequestEvent, useState } from "#imports";
1685
+ import type { ClientAuthResult } from "@zitadel/sdk-nuxt";
1686
+
1687
+ export default defineNuxtPlugin(() => {
1688
+ const event = useRequestEvent();
1689
+ const auth = event?.context.nextgenAuth ?? {
1690
+ isAuthenticated: false as const,
1691
+ session: null,
1692
+ };
1693
+
1694
+ // Strip the raw JWT before seeding useState — it must not appear in the SSR
1695
+ // payload where client-side scripts could read it.
1696
+ const clientAuth: ClientAuthResult = auth.isAuthenticated
1697
+ ? {
1698
+ isAuthenticated: true,
1699
+ session: {
1700
+ userId: auth.session.userId,
1701
+ email: auth.session.email,
1702
+ name: auth.session.name,
1703
+ },
1704
+ }
1705
+ : { isAuthenticated: false, session: null };
1706
+
1707
+ useState<ClientAuthResult>("nextgen-auth", () => clientAuth);
1708
+ });
1709
+ `;
1710
+ }
1711
+ //#endregion
1712
+ //#region src/lib/orca/patchers/rule/nuxt/index.ts
1713
+ const SDK_DEPENDENCY$2 = "@zitadel/sdk-nuxt";
1714
+ const NUXT_CONFIG_PATHS = configCandidates("nuxt.config");
1715
+ /**
1716
+ * Rule-based patcher for a Nuxt app. Like Next.js, Nuxt proxies the backend and
1717
+ * verifies the session through server middleware — here the `@zitadel/sdk-nuxt`
1718
+ * module, registered via a non-destructive `nuxt.config.*` edit. Contributes
1719
+ * the login/register/profile pages (the raw `<zitadel-login>`/`<zitadel-logout>`
1720
+ * elements), the client/server plugins, the `app.vue` router, and the SDK dep.
1721
+ */
1722
+ var NuxtPatcher = class extends AbstractRulePatcher {
1723
+ canPatch(framework) {
1724
+ return framework === "nuxt";
1725
+ }
1726
+ routeOps(ctx) {
1727
+ const src = (rel) => join(ctx.framework.appDir, rel);
1728
+ return [
1729
+ {
1730
+ kind: "write",
1731
+ path: src("app.vue"),
1732
+ contents: appVueTemplate()
1733
+ },
1734
+ {
1735
+ kind: "write",
1736
+ path: src("pages/login.vue"),
1737
+ contents: loginPageTemplate()
1738
+ },
1739
+ {
1740
+ kind: "write",
1741
+ path: src("pages/register.vue"),
1742
+ contents: registerPageTemplate()
1743
+ },
1744
+ {
1745
+ kind: "write",
1746
+ path: src("pages/profile.vue"),
1747
+ contents: profilePageTemplate()
1748
+ },
1749
+ {
1750
+ kind: "write",
1751
+ path: src("plugins/zitadel-components.client.ts"),
1752
+ contents: componentsPluginTemplate()
1753
+ },
1754
+ {
1755
+ kind: "write",
1756
+ path: src("plugins/auth.server.ts"),
1757
+ contents: authPluginTemplate()
1758
+ },
1759
+ {
1760
+ kind: "edit",
1761
+ path: [...NUXT_CONFIG_PATHS],
1762
+ edit: nuxtConfigEdit({
1763
+ projectId: ctx.project.id,
1764
+ server: ctx.server
1765
+ })
1766
+ },
1767
+ {
1768
+ kind: "merge-env",
1769
+ path: ".env.example",
1770
+ entries: { NUXT_PUBLIC_ZITADEL_PROJECT_ID: "" }
1771
+ },
1772
+ {
1773
+ kind: "merge-env",
1774
+ path: ".env.local",
1775
+ entries: { NUXT_PUBLIC_ZITADEL_PROJECT_ID: ctx.project.id }
1776
+ },
1777
+ {
1778
+ kind: "add-dep",
1779
+ name: SDK_DEPENDENCY$2,
1780
+ version: npmDistTagForCliVersion(ctx.cliVersion)
1781
+ }
1782
+ ];
1783
+ }
1784
+ routeFiles(view) {
1785
+ const src = (rel) => join(view.framework.appDir, rel);
1786
+ return [
1787
+ src("app.vue"),
1788
+ src("pages/login.vue"),
1789
+ src("pages/register.vue"),
1790
+ src("pages/profile.vue"),
1791
+ src("plugins/zitadel-components.client.ts"),
1792
+ src("plugins/auth.server.ts")
1793
+ ];
1794
+ }
1795
+ routeDeps(_view) {
1796
+ return [SDK_DEPENDENCY$2];
1797
+ }
1798
+ routeConfigEdits(_view) {
1799
+ return ["nuxt.config.*"];
1800
+ }
1801
+ summary(_ctx) {
1802
+ return {
1803
+ title: "Nuxt integration",
1804
+ detail: "Wrote login/register/profile pages + plugins and registered @zitadel/sdk-nuxt in nuxt.config.*."
1805
+ };
1806
+ }
1807
+ };
1808
+ //#endregion
1809
+ //#region src/lib/orca/patchers/rule/vite-support.ts
1810
+ /**
1811
+ * Shared Vite dev-server proxy merged into the project's Vite config for the SPA
1812
+ * frameworks (React, Vue). It forwards same-origin `/__nextgen/*` calls to the
1813
+ * backend, strips the prefix, and attaches the project's `sk_<project_id>`
1814
+ * bearer (read from `ZITADEL_PROJECT_ID` in the env) to every proxied request.
1815
+ */
1816
+ function proxyEntryCode(server) {
1817
+ return `{
1818
+ target: ${JSON.stringify(server)},
1819
+ changeOrigin: false,
1820
+ rewrite: (path) => path.replace(/^\\${PROXY_PATH}/, "").replace(/^(?!\\/)/, "/"),
1821
+ configure: (proxy) => {
1822
+ const projectId = loadEnv("development", process.cwd(), "ZITADEL_").ZITADEL_PROJECT_ID;
1823
+ if (!projectId) {
1824
+ throw new Error("ZITADEL_PROJECT_ID is not set; add it to .env.local (zitadel setup writes it).");
1825
+ }
1826
+ const bearer = \`Bearer sk_\${projectId}\`;
1827
+ proxy.on("proxyReq", (proxyReq) => {
1828
+ proxyReq.setHeader("authorization", bearer);
1829
+ });
1830
+ },
1831
+ }`;
1832
+ }
1833
+ /** The imports that the injected proxy entry depends on. */
1834
+ const PROXY_IMPORTS = [{
1835
+ from: "vite",
1836
+ imported: "loadEnv",
1837
+ local: "loadEnv"
1838
+ }];
1839
+ /**
1840
+ * Builds the pure `edit` transform the file-writer applies to the project's Vite
1841
+ * config (`vite.config.*`): a non-destructive magicast merge that adds the
1842
+ * `/__nextgen` proxy and sets `server.port`/`strictPort` when they are unset,
1843
+ * preserving the user's plugins, options, and formatting. Leaves `server.host`
1844
+ * alone so the user can still opt into network binding (`--host`/`host: true`);
1845
+ * the issuer/origin requirement is about the port, not the bind host. Idempotent
1846
+ * — entries already present are left as-is. Throws `E_VALIDATION` when the file
1847
+ * is absent or the config object cannot be reached (function-built/exotic
1848
+ * configs), with a hint to add the block manually.
1849
+ */
1850
+ function viteProxyEdit(devPort, server) {
1851
+ return (source) => {
1852
+ const label = "the Vite config (vite.config.*)";
1853
+ const mod = parseConfigModule(source, label);
1854
+ const config = resolveDefaultExportObject(mod, label);
1855
+ let changed = false;
1856
+ const serverConfig = ensureEditableObject(config, "server");
1857
+ if (serverConfig.port === void 0) {
1858
+ serverConfig.port = devPort;
1859
+ changed = true;
1860
+ }
1861
+ if (serverConfig.strictPort === void 0) {
1862
+ serverConfig.strictPort = true;
1863
+ changed = true;
1864
+ }
1865
+ const proxyConfig = ensureEditableObject(serverConfig, "proxy");
1866
+ if (proxyConfig["/__nextgen"] === void 0) {
1867
+ proxyConfig[PROXY_PATH] = builders.raw(proxyEntryCode(server));
1868
+ changed = true;
1869
+ }
1870
+ for (const imp of PROXY_IMPORTS) if (!importIsPresent(mod, imp.local, imp.from)) {
1871
+ mod.imports.$add({ ...imp });
1872
+ changed = true;
1873
+ }
1874
+ if (!changed && source !== void 0) return source;
1875
+ const code = generateCode(mod).code;
1876
+ return code.endsWith("\n") ? code : `${code}\n`;
1877
+ };
1878
+ }
1879
+ /**
1880
+ * Candidate Vite config filenames, in resolution priority. The patcher hands
1881
+ * this list to the generic `edit` file-op, which patches the first one that
1882
+ * exists — so any project layout (`vite.config.ts`, `.mts`, `.js`, …) is covered.
1883
+ */
1884
+ const VITE_CONFIG_PATHS = configCandidates("vite.config");
1885
+ /** Builds the shared Vite-config proxy {@link FileOp} for a {@link ViteSupport} patcher. */
1886
+ function buildViteProxyOp(devPort, server) {
1887
+ return {
1888
+ kind: "edit",
1889
+ path: [...VITE_CONFIG_PATHS],
1890
+ edit: viteProxyEdit(devPort, server)
1891
+ };
1892
+ }
1893
+ //#endregion
1894
+ //#region src/lib/orca/patchers/rule/react/templates.ts
1895
+ /**
1896
+ * The managed `src/App.tsx`: a minimal path-based router that renders the
1897
+ * `@zitadel/sdk-react` widgets — login at `/login` (and `/`), register at
1898
+ * `/register`, and the logout widget at `/profile`. The project id comes from
1899
+ * `VITE_ZITADEL_PROJECT_ID` (Vite only exposes `VITE_`-prefixed env to the
1900
+ * client). No secret reaches the browser: the dev proxy in `vite.config.*`
1901
+ * attaches the `sk_<project_id>` bearer (derived from the public project id)
1902
+ * server-side.
1903
+ */
1904
+ function appTemplate$1() {
1905
+ return `${MANAGED_MARKER}
1906
+ import { ZitadelLogin, ZitadelLogout, configureZitadel } from "@zitadel/sdk-react";
1907
+
1908
+ const project = configureZitadel({
1909
+ projectId: import.meta.env.VITE_ZITADEL_PROJECT_ID,
1910
+ proxyPath: "${PROXY_PATH}",
1911
+ });
1912
+
1913
+ export default function App() {
1914
+ const path = window.location.pathname;
1915
+
1916
+ if (path.startsWith("/profile")) {
1917
+ return <ZitadelLogout project={project} postSignOutUrl="/login" />;
1918
+ }
1919
+ if (path.startsWith("/register")) {
1920
+ return <ZitadelLogin project={project} purpose="register" postSignInUrl="/profile" />;
1921
+ }
1922
+ return <ZitadelLogin project={project} purpose="login" postSignInUrl="/profile" />;
1923
+ }
1924
+ `;
1925
+ }
1926
+ //#endregion
1927
+ //#region src/lib/orca/patchers/rule/react/index.ts
1928
+ const SDK_DEPENDENCY$1 = "@zitadel/sdk-react";
1929
+ /**
1930
+ * Rule-based patcher for a Vite + React single-page app. Inherits the shared
1931
+ * `.zitadel/` base files from {@link AbstractRulePatcher} and contributes the
1932
+ * managed `src/App.tsx` auth entry, a non-destructive `vite.config.*` merge
1933
+ * that adds the `/__nextgen` dev proxy (attaching the `sk_<project_id>` bearer
1934
+ * from `ZITADEL_PROJECT_ID` to every proxied request), the `VITE_`-prefixed
1935
+ * project id, and the SDK dep.
1936
+ *
1937
+ * Unlike Next.js — whose middleware runs the proxy and token exchange
1938
+ * server-side — a SPA has no server, so the dev proxy stands in for
1939
+ * `@zitadel/edge-proxy` locally. Production deployments still need that proxy.
1940
+ */
1941
+ var ReactPatcher = class extends AbstractRulePatcher {
1942
+ canPatch(framework) {
1943
+ return framework === "react";
1944
+ }
1945
+ viteProxyOp(devPort, server) {
1946
+ return buildViteProxyOp(devPort, server);
1947
+ }
1948
+ routeOps(ctx) {
1949
+ return [
1950
+ {
1951
+ kind: "write",
1952
+ path: "src/App.tsx",
1953
+ contents: appTemplate$1()
1954
+ },
1955
+ this.viteProxyOp(ctx.framework.devPort, ctx.server),
1956
+ {
1957
+ kind: "merge-env",
1958
+ path: ".env.example",
1959
+ entries: { VITE_ZITADEL_PROJECT_ID: "" }
1960
+ },
1961
+ {
1962
+ kind: "merge-env",
1963
+ path: ".env.local",
1964
+ entries: { VITE_ZITADEL_PROJECT_ID: ctx.project.id }
1965
+ },
1966
+ {
1967
+ kind: "add-dep",
1968
+ name: SDK_DEPENDENCY$1,
1969
+ version: npmDistTagForCliVersion(ctx.cliVersion)
1970
+ }
1971
+ ];
1972
+ }
1973
+ routeFiles(_view) {
1974
+ return ["src/App.tsx"];
1975
+ }
1976
+ routeDeps(_view) {
1977
+ return [SDK_DEPENDENCY$1];
1978
+ }
1979
+ routeConfigEdits(_view) {
1980
+ return ["vite.config.*"];
1981
+ }
1982
+ summary(_ctx) {
1983
+ return {
1984
+ title: "React (Vite) integration",
1985
+ detail: "Wrote src/App.tsx auth entry and merged the /__nextgen dev proxy into vite.config.*."
1986
+ };
1987
+ }
1988
+ };
1989
+ //#endregion
1990
+ //#region src/lib/orca/patchers/rule/vue/templates.ts
1991
+ /**
1992
+ * The managed `src/App.vue`: a minimal path-based router that renders the
1993
+ * `@zitadel/sdk-vue` widgets — login at `/login` (and `/`), register at
1994
+ * `/register`, and the logout widget at `/profile`. The managed marker lives in
1995
+ * the `<script setup>` block (a JS comment) so eject/doctor stay marker-aware.
1996
+ * The project id comes from `VITE_ZITADEL_PROJECT_ID`. No secret reaches the
1997
+ * browser: the dev proxy in `vite.config.*` attaches the `sk_<project_id>`
1998
+ * bearer (derived from the public project id) server-side.
1999
+ */
2000
+ function appTemplate() {
2001
+ return `<script setup lang="ts">
2002
+ ${MANAGED_MARKER}
2003
+ import { ZitadelLogin, ZitadelLogout, configureZitadel } from "@zitadel/sdk-vue";
2004
+
2005
+ const project = configureZitadel({
2006
+ projectId: import.meta.env.VITE_ZITADEL_PROJECT_ID,
2007
+ proxyPath: "${PROXY_PATH}",
2008
+ });
2009
+
2010
+ const path = window.location.pathname;
2011
+ <\/script>
2012
+
2013
+ <template>
2014
+ <ZitadelLogout
2015
+ v-if="path.startsWith('/profile')"
2016
+ :project="project"
2017
+ postSignOutUrl="/login"
2018
+ />
2019
+ <ZitadelLogin
2020
+ v-else-if="path.startsWith('/register')"
2021
+ :project="project"
2022
+ purpose="register"
2023
+ postSignInUrl="/profile"
2024
+ />
2025
+ <ZitadelLogin v-else :project="project" purpose="login" postSignInUrl="/profile" />
2026
+ </template>
2027
+ `;
2028
+ }
2029
+ //#endregion
2030
+ //#region src/lib/orca/patchers/rule/vue/index.ts
2031
+ const SDK_DEPENDENCY = "@zitadel/sdk-vue";
2032
+ /**
2033
+ * Rule-based patcher for a Vite + Vue single-page app. Inherits the shared
2034
+ * `.zitadel/` base files from {@link AbstractRulePatcher} and contributes the
2035
+ * managed `src/App.vue` auth entry, a non-destructive `vite.config.*` merge
2036
+ * that adds the `/__nextgen` dev proxy (attaching the `sk_<project_id>` bearer
2037
+ * from `ZITADEL_PROJECT_ID` to every proxied request), the `VITE_`-prefixed
2038
+ * project id, and the SDK dep.
2039
+ */
2040
+ var VuePatcher = class extends AbstractRulePatcher {
2041
+ canPatch(framework) {
2042
+ return framework === "vue";
2043
+ }
2044
+ viteProxyOp(devPort, server) {
2045
+ return buildViteProxyOp(devPort, server);
2046
+ }
2047
+ routeOps(ctx) {
2048
+ return [
2049
+ {
2050
+ kind: "write",
2051
+ path: "src/App.vue",
2052
+ contents: appTemplate()
2053
+ },
2054
+ this.viteProxyOp(ctx.framework.devPort, ctx.server),
2055
+ {
2056
+ kind: "merge-env",
2057
+ path: ".env.example",
2058
+ entries: { VITE_ZITADEL_PROJECT_ID: "" }
2059
+ },
2060
+ {
2061
+ kind: "merge-env",
2062
+ path: ".env.local",
2063
+ entries: { VITE_ZITADEL_PROJECT_ID: ctx.project.id }
2064
+ },
2065
+ {
2066
+ kind: "add-dep",
2067
+ name: SDK_DEPENDENCY,
2068
+ version: npmDistTagForCliVersion(ctx.cliVersion)
2069
+ }
2070
+ ];
2071
+ }
2072
+ routeFiles(_view) {
2073
+ return ["src/App.vue"];
2074
+ }
2075
+ routeDeps(_view) {
2076
+ return [SDK_DEPENDENCY];
2077
+ }
2078
+ routeConfigEdits(_view) {
2079
+ return ["vite.config.*"];
2080
+ }
2081
+ summary(_ctx) {
2082
+ return {
2083
+ title: "Vue (Vite) integration",
2084
+ detail: "Wrote src/App.vue auth entry and merged the /__nextgen dev proxy into vite.config.*."
2085
+ };
2086
+ }
2087
+ };
2088
+ //#endregion
2089
+ //#region src/lib/orca/patchers/index.ts
2090
+ /**
2091
+ * Active patchers, in priority order; the first whose `canPatch` matches wins.
2092
+ *
2093
+ * Patchers are grouped by family under subdirectories: `rule/` holds the
2094
+ * deterministic, template-driven patchers (extending
2095
+ * {@link import("./rule/base").AbstractRulePatcher}). A future LLM-driven
2096
+ * family lives under `llm/` and registers its concrete patchers here — no
2097
+ * orchestrator or command changes needed. Only Next.js is supported today.
2098
+ */
2099
+ const patchers = [
2100
+ new NextPatcher(),
2101
+ new NuxtPatcher(),
2102
+ new ReactPatcher(),
2103
+ new VuePatcher(),
2104
+ new AngularPatcher()
2105
+ ];
2106
+ //#endregion
2107
+ //#region src/lib/orca/scaffolders/cli.ts
2108
+ /**
2109
+ * Base for scaffolders that delegate to an external CLI (e.g. create-next-app).
2110
+ * Subclasses implement {@link scaffold} and call {@link runCommand}.
2111
+ */
2112
+ var AbstractCLIScaffolder = class {
2113
+ /** True when the requested framework is in {@link supportedFrameworks}. */
2114
+ canScaffold(framework) {
2115
+ return this.supportedFrameworks.includes(framework);
2116
+ }
2117
+ /**
2118
+ * Runs an external command in `cwd`, throwing a typed {@link ZitadelError} on
2119
+ * failure so the cause surfaces as a categorized CLI error. Distinguishes
2120
+ * "binary not on PATH" (`ENOENT` from the spawn itself) from "binary ran but
2121
+ * exited non-zero" — the former previously got masked as a generic
2122
+ * `exited with status 1`, leaving users to guess. Tests stub
2123
+ * `node:child_process` to assert the command without spawning.
2124
+ */
2125
+ runCommand(command, args, cwd) {
2126
+ const result = spawnSync(command, [...args], {
2127
+ cwd,
2128
+ encoding: "utf8"
2129
+ });
2130
+ if (result.error) {
2131
+ const err = result.error;
2132
+ const notFound = err.code === "ENOENT";
2133
+ throw new ZitadelError("E_VALIDATION", notFound ? `Command not found: ${command}` : `Failed to spawn "${command}": ${err.message}`, {
2134
+ hint: notFound ? `Ensure '${command}' is installed and on PATH.` : void 0,
2135
+ details: {
2136
+ command,
2137
+ args: [...args],
2138
+ code: err.code
2139
+ }
2140
+ });
2141
+ }
2142
+ const status = result.status ?? 1;
2143
+ if (status !== 0) {
2144
+ const stdout = String(result.stdout ?? "");
2145
+ const stderr = String(result.stderr ?? "");
2146
+ const output = truncateCommandOutput([stderr, stdout].filter(Boolean).join("\n").trim());
2147
+ throw new ZitadelError("E_VALIDATION", `Command "${command} ${args.join(" ")}" exited with status ${String(status)}`, {
2148
+ hint: output ? `Command output:\n${output}` : "Run the command directly for more detail.",
2149
+ details: {
2150
+ command,
2151
+ args: [...args],
2152
+ cwd,
2153
+ stdout,
2154
+ stderr
2155
+ }
2156
+ });
2157
+ }
2158
+ }
2159
+ };
2160
+ function truncateCommandOutput(output) {
2161
+ const limit = 4e3;
2162
+ if (output.length <= limit) return output;
2163
+ return `${output.slice(0, limit)}\n... output truncated ...`;
2164
+ }
2165
+ //#endregion
2166
+ //#region src/lib/orca/scaffolders/angular.ts
2167
+ /**
2168
+ * Derives a valid Angular project name from the target directory. `ng new`
2169
+ * validates the name against `^[a-zA-Z0-9-~][a-zA-Z0-9-._~]*$` and rejects `.`,
2170
+ * so we slugify the directory's basename (lowercase, non-alphanumerics → `-`)
2171
+ * and guarantee a leading letter by prefixing `app-` when the slug does not
2172
+ * start with one (`app-zitadel` when the basename slugifies to nothing).
2173
+ */
2174
+ function angularProjectName(cwd) {
2175
+ const slug = basename(cwd).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
2176
+ return /^[a-z]/.test(slug) ? slug : `app-${slug || "zitadel"}`;
2177
+ }
2178
+ /**
2179
+ * Scaffolds a new Angular app with the Angular CLI, then removes the starter
2180
+ * `app.ts`/`app.html` root component (and its now-unreferenced `app.css`) so the
2181
+ * patcher can write the managed ones without colliding with boilerplate. The
2182
+ * managed component uses only `templateUrl`, so `app.css` would otherwise be a
2183
+ * dangling file eject never cleans up. Unlike `create-vite`/`nuxi`, `ng new`
2184
+ * needs a real project name plus `--directory .` to populate the current dir.
2185
+ * Requires a Node version Angular supports (^22.22.3 || ^24.15.0 || >=26).
2186
+ */
2187
+ var AngularScaffolder = class extends AbstractCLIScaffolder {
2188
+ displayName = "Angular";
2189
+ supportedFrameworks = ["angular"];
2190
+ async scaffold(cwd, _framework) {
2191
+ this.runCommand("npx", [
2192
+ "-y",
2193
+ "@angular/cli@latest",
2194
+ "new",
2195
+ angularProjectName(cwd),
2196
+ "--directory",
2197
+ ".",
2198
+ "--defaults",
2199
+ "--style=css",
2200
+ "--ssr=false",
2201
+ "--skip-git"
2202
+ ], cwd);
2203
+ await rm(join(cwd, "src/app/app.ts"), { force: true });
2204
+ await rm(join(cwd, "src/app/app.html"), { force: true });
2205
+ await rm(join(cwd, "src/app/app.css"), { force: true });
2206
+ }
2207
+ };
2208
+ //#endregion
2209
+ //#region src/lib/orca/scaffolders/next.ts
2210
+ const CREATE_NEXT_APP_VERSION = "16.2.4";
2211
+ /** Scaffolds a new Next.js App Router project with `create-next-app`. */
2212
+ var NextScaffolder = class extends AbstractCLIScaffolder {
2213
+ displayName = "Next.js";
2214
+ supportedFrameworks = ["next"];
2215
+ /**
2216
+ * Runs the pinned `create-next-app` version in `cwd`, creating a TypeScript
2217
+ * App Router project in place. `--yes` accepts all defaults so the command
2218
+ * runs unattended, and `--skip-install` leaves dependency installation to the
2219
+ * setup command's explicit next step after Zitadel patches package.json.
2220
+ */
2221
+ async scaffold(cwd, _framework) {
2222
+ this.runCommand("npx", [
2223
+ "--yes",
2224
+ `create-next-app@${CREATE_NEXT_APP_VERSION}`,
2225
+ ".",
2226
+ "--ts",
2227
+ "--app",
2228
+ "--use-npm",
2229
+ "--disable-git",
2230
+ "--yes",
2231
+ "--skip-install"
2232
+ ], cwd);
2233
+ }
2234
+ };
2235
+ //#endregion
2236
+ //#region src/lib/orca/scaffolders/nuxt.ts
2237
+ /**
2238
+ * Scaffolds a new Nuxt app with `nuxi init`, then removes the starter `app.vue`
2239
+ * so the patcher can write the managed one without colliding with boilerplate.
2240
+ * Nuxt 4 (what `nuxi init` scaffolds today) puts it under `app/`; older Nuxt put
2241
+ * it at the root, so both are removed. `nuxt.config.ts` is left in place — the
2242
+ * patcher merges into it via an `edit`, which preserves whatever `nuxi` generated.
2243
+ */
2244
+ var NuxtScaffolder = class extends AbstractCLIScaffolder {
2245
+ displayName = "Nuxt";
2246
+ supportedFrameworks = ["nuxt"];
2247
+ async scaffold(cwd, _framework) {
2248
+ this.runCommand("npx", [
2249
+ "-y",
2250
+ "nuxi@latest",
2251
+ "init",
2252
+ ".",
2253
+ "--template",
2254
+ "minimal",
2255
+ "--packageManager",
2256
+ "npm",
2257
+ "--no-gitInit",
2258
+ "--force"
2259
+ ], cwd);
2260
+ await rm(join(cwd, "app/app.vue"), { force: true });
2261
+ await rm(join(cwd, "app.vue"), { force: true });
2262
+ }
2263
+ };
2264
+ //#endregion
2265
+ //#region src/lib/orca/scaffolders/react.ts
2266
+ /**
2267
+ * Scaffolds a new Vite + React (TypeScript) single-page app with `create-vite`,
2268
+ * then removes the starter `App.tsx`/`App.css` demo so the patcher can write the
2269
+ * managed `src/App.tsx` without colliding with boilerplate. `index.css` and
2270
+ * `main.tsx` are left in place — the patched `App.tsx` keeps the same entry.
2271
+ */
2272
+ var ReactScaffolder = class extends AbstractCLIScaffolder {
2273
+ displayName = "React (Vite)";
2274
+ supportedFrameworks = ["react"];
2275
+ async scaffold(cwd, _framework) {
2276
+ this.runCommand("npm", [
2277
+ "create",
2278
+ "vite@latest",
2279
+ ".",
2280
+ "--",
2281
+ "--template",
2282
+ "react-ts"
2283
+ ], cwd);
2284
+ await rm(join(cwd, "src/App.tsx"), { force: true });
2285
+ await rm(join(cwd, "src/App.css"), { force: true });
2286
+ }
2287
+ };
2288
+ //#endregion
2289
+ //#region src/lib/orca/scaffolders/vue.ts
2290
+ /**
2291
+ * Scaffolds a new Vite + Vue (TypeScript) single-page app with `create-vite`,
2292
+ * then removes the starter `App.vue`/`components/HelloWorld.vue` demo so the
2293
+ * patcher can write the managed `src/App.vue` without colliding with boilerplate.
2294
+ */
2295
+ var VueScaffolder = class extends AbstractCLIScaffolder {
2296
+ displayName = "Vue (Vite)";
2297
+ supportedFrameworks = ["vue"];
2298
+ async scaffold(cwd, _framework) {
2299
+ this.runCommand("npm", [
2300
+ "create",
2301
+ "vite@latest",
2302
+ ".",
2303
+ "--",
2304
+ "--template",
2305
+ "vue-ts"
2306
+ ], cwd);
2307
+ await rm(join(cwd, "src/App.vue"), { force: true });
2308
+ await rm(join(cwd, "src/components/HelloWorld.vue"), { force: true });
2309
+ }
2310
+ };
2311
+ //#endregion
2312
+ //#region src/lib/orca/scaffolders/index.ts
2313
+ /**
2314
+ * Active scaffolders, in priority order. The framework picker derives its
2315
+ * choices from this list. Add a new framework by appending its scaffolder
2316
+ * here — no orchestrator changes needed.
2317
+ */
2318
+ const scaffolders = [
2319
+ new NextScaffolder(),
2320
+ new NuxtScaffolder(),
2321
+ new ReactScaffolder(),
2322
+ new VueScaffolder(),
2323
+ new AngularScaffolder()
2324
+ ];
2325
+ //#endregion
2326
+ //#region src/lib/orca/index.ts
2327
+ /**
2328
+ * Orchestrates the three per-framework strategies — detectors (recognise an
2329
+ * existing project and extract its facts), scaffolders (create a project), and
2330
+ * patchers (integrate Zitadel) — over their respective registries. It resolves
2331
+ * the right strategy for a framework and drives the detect/scaffold lifecycle;
2332
+ * how a patcher applies its work (file operations vs an LLM agent) stays
2333
+ * internal to that patcher. Registries are injected so tests can supply fakes.
2334
+ */
2335
+ var Orca = class {
2336
+ constructor(detectors, scaffolders, patchers) {
2337
+ this.detectors = detectors;
2338
+ this.scaffolders = scaffolders;
2339
+ this.patchers = patchers;
2340
+ }
2341
+ /**
2342
+ * Detects the framework in `cwd` and extracts its {@link FrameworkFacts},
2343
+ * honouring an explicit `requested` framework. Throws
2344
+ * `E_FRAMEWORK_NOT_DETECTED` when nothing matches; a detector's
2345
+ * `E_UNSUPPORTED_PROJECT_SHAPE` (recognised but unsupported) propagates.
2346
+ */
2347
+ async detect(cwd, requested) {
2348
+ const candidates = requested ? this.detectors.filter((detector) => detector.framework === requested) : this.detectors;
2349
+ if (requested && candidates.length === 0) throw new ZitadelError("E_FRAMEWORK_NOT_DETECTED", `Unsupported framework "${requested}"`, { hint: `Supported frameworks: ${this.frameworkIds().join(", ")}.` });
2350
+ for (const detector of candidates) {
2351
+ const facts = await detector.detect(cwd);
2352
+ if (facts) return facts;
2353
+ }
2354
+ throw new ZitadelError("E_FRAMEWORK_NOT_DETECTED", "Could not detect a supported app framework", { hint: "Run setup from your app project directory, pass --cwd <path-to-app>, or run setup from an empty directory to scaffold a new app." });
2355
+ }
2356
+ /**
2357
+ * Non-throwing detection: returns `undefined` instead of raising for a
2358
+ * project that is absent, unrecognised, or recognised-but-unsupported, so
2359
+ * callers (e.g. `eject`) can probe and degrade gracefully.
2360
+ */
2361
+ async tryDetect(cwd) {
2362
+ try {
2363
+ return await this.detect(cwd);
2364
+ } catch (error) {
2365
+ if (error instanceof ZitadelError && (error.code === "E_FRAMEWORK_NOT_DETECTED" || error.code === "E_UNSUPPORTED_PROJECT_SHAPE")) return;
2366
+ throw error;
2367
+ }
2368
+ }
2369
+ /** Whether `cwd` is safe for an in-place framework scaffold. */
2370
+ async isFreshScaffoldTarget(cwd) {
2371
+ return (await inspectScaffoldTarget(cwd)).scaffoldable;
2372
+ }
2373
+ /**
2374
+ * Creates a new `framework` project in `cwd`, then re-detects it to return
2375
+ * the resulting {@link FrameworkFacts}. Throws `E_CONFLICT` when the directory
2376
+ * already contains a project ("already scaffolded") and `E_VALIDATION` when no
2377
+ * scaffolder supports the framework.
2378
+ */
2379
+ async scaffold(cwd, framework) {
2380
+ const target = await inspectScaffoldTarget(cwd);
2381
+ if (!target.scaffoldable) throw new ZitadelError("E_CONFLICT", `Cannot scaffold: ${cwd} is not empty`, {
2382
+ hint: target.reason ?? "Run setup in an empty directory, or run setup from an existing supported app project.",
2383
+ details: { entries: target.entries }
2384
+ });
2385
+ assertNpmSafeScaffoldDirectoryName(cwd);
2386
+ const stash = await stashFreshScaffoldArtifacts(cwd, target);
2387
+ try {
2388
+ await this.scaffolderFor(framework).scaffold(cwd, framework);
2389
+ } finally {
2390
+ await restoreFreshScaffoldArtifacts(cwd, stash);
2391
+ }
2392
+ return this.detect(cwd, framework);
2393
+ }
2394
+ /**
2395
+ * Resolves the scaffolder for a framework, throwing `E_VALIDATION` (with the
2396
+ * available list) when none matches.
2397
+ */
2398
+ scaffolderFor(framework) {
2399
+ const scaffolder = this.scaffolders.find((candidate) => candidate.canScaffold(framework));
2400
+ if (!scaffolder) throw new ZitadelError("E_VALIDATION", `No scaffolder supports "${framework}"`, { hint: `Available frameworks: ${this.availableFrameworks().map((f) => f.id).join(", ")}.` });
2401
+ return scaffolder;
2402
+ }
2403
+ /**
2404
+ * Resolves the patcher for a framework, throwing `E_VALIDATION` when none
2405
+ * matches (e.g. a framework that can be scaffolded but not yet integrated).
2406
+ */
2407
+ patcherFor(framework) {
2408
+ const patcher = this.patchers.find((candidate) => candidate.canPatch(framework));
2409
+ if (!patcher) throw new ZitadelError("E_VALIDATION", `No patcher supports "${framework}"`, { hint: "Zitadel integration currently supports Next.js." });
2410
+ return patcher;
2411
+ }
2412
+ /** The frameworks that can be scaffolded, derived from the scaffolder registry. */
2413
+ availableFrameworks() {
2414
+ return this.scaffolders.map((scaffolder) => ({
2415
+ id: scaffolder.supportedFrameworks[0] ?? scaffolder.displayName,
2416
+ displayName: scaffolder.displayName
2417
+ }));
2418
+ }
2419
+ frameworkIds() {
2420
+ return this.detectors.map((detector) => detector.framework);
2421
+ }
2422
+ };
2423
+ function assertNpmSafeScaffoldDirectoryName(cwd) {
2424
+ const name = basename(cwd);
2425
+ const errors = npmPackageNameErrors(name);
2426
+ if (errors.length === 0) return;
2427
+ throw new ZitadelError("E_VALIDATION", `Fresh app directory name "${name}" is not npm-package-safe`, {
2428
+ hint: "Rename the directory to a lowercase npm-package-safe name, for example `my-zitadel-app`, then rerun setup.",
2429
+ details: {
2430
+ cwd,
2431
+ name,
2432
+ validation_errors: errors
2433
+ }
2434
+ });
2435
+ }
2436
+ function npmPackageNameErrors(name) {
2437
+ const errors = [];
2438
+ if (name.length === 0) errors.push("name is empty");
2439
+ if (name.length > 214) errors.push("name is longer than 214 characters");
2440
+ if (name !== name.trim()) errors.push("name contains leading or trailing whitespace");
2441
+ if (/[A-Z]/.test(name)) errors.push("name can no longer contain capital letters");
2442
+ if (name.startsWith(".") || name.startsWith("_")) errors.push("name cannot start with a period or underscore");
2443
+ if (!/^[a-z0-9][a-z0-9._~-]*$/.test(name)) errors.push("name may only contain lowercase letters, numbers, dots, underscores, tildes, and hyphens");
2444
+ if (name === "node_modules" || name === "favicon.ico") errors.push(`name "${name}" is reserved`);
2445
+ return [...new Set(errors)];
2446
+ }
2447
+ /** {@link Orca} wired with the default detector, scaffolder, and patcher registries. */
2448
+ function createOrca() {
2449
+ return new Orca(detectors, scaffolders, patchers);
2450
+ }
2451
+ async function inspectScaffoldTarget(cwd) {
2452
+ const entries = await readdir(cwd, { withFileTypes: true });
2453
+ const names = entries.map((entry) => entry.name).sort();
2454
+ let hasGitignore = false;
2455
+ let hasRuntimeOnlyZitadel = false;
2456
+ for (const entry of entries) {
2457
+ if (entry.name === ".gitignore") {
2458
+ if (!entry.isFile()) return {
2459
+ scaffoldable: false,
2460
+ hasGitignore: false,
2461
+ hasRuntimeOnlyZitadel: false,
2462
+ reason: ".gitignore exists but is not a file.",
2463
+ entries: names
2464
+ };
2465
+ hasGitignore = true;
2466
+ continue;
2467
+ }
2468
+ if (entry.name === ".zitadel") {
2469
+ if (!entry.isDirectory() || !await isRuntimeOnlyZitadelDir(join(cwd, ".zitadel"))) return {
2470
+ scaffoldable: false,
2471
+ hasGitignore,
2472
+ hasRuntimeOnlyZitadel: false,
2473
+ reason: ".zitadel contains project state. Move it aside or run setup from an empty app directory.",
2474
+ entries: names
2475
+ };
2476
+ hasRuntimeOnlyZitadel = true;
2477
+ continue;
2478
+ }
2479
+ return {
2480
+ scaffoldable: false,
2481
+ hasGitignore,
2482
+ hasRuntimeOnlyZitadel: false,
2483
+ reason: `Directory contains ${entry.name}. Run setup from an empty directory to scaffold a new app.`,
2484
+ entries: names
2485
+ };
2486
+ }
2487
+ return {
2488
+ scaffoldable: true,
2489
+ hasGitignore,
2490
+ hasRuntimeOnlyZitadel,
2491
+ entries: names
2492
+ };
2493
+ }
2494
+ async function isRuntimeOnlyZitadelDir(path) {
2495
+ const entries = await readdir(path, { withFileTypes: true });
2496
+ if (entries.length !== 1 || entries[0]?.name !== "local" || !entries[0].isDirectory()) return false;
2497
+ return true;
2498
+ }
2499
+ async function stashFreshScaffoldArtifacts(cwd, target) {
2500
+ if (!target.hasGitignore && !target.hasRuntimeOnlyZitadel) return;
2501
+ const root = join(dirname(cwd), `.${basename(cwd)}.fresh-scaffold-stash-${String(process.pid)}-${String(Date.now())}`);
2502
+ await mkdir(root, { mode: 448 });
2503
+ const stash = { root };
2504
+ if (target.hasRuntimeOnlyZitadel) {
2505
+ stash.zitadel = join(root, ".zitadel");
2506
+ await rename(join(cwd, ".zitadel"), stash.zitadel);
2507
+ }
2508
+ if (target.hasGitignore) {
2509
+ stash.gitignore = join(root, ".gitignore");
2510
+ await rename(join(cwd, ".gitignore"), stash.gitignore);
2511
+ }
2512
+ return stash;
2513
+ }
2514
+ async function restoreFreshScaffoldArtifacts(cwd, stash) {
2515
+ if (!stash) return;
2516
+ try {
2517
+ await restoreRuntimeOnlyZitadel(cwd, stash.zitadel);
2518
+ await restoreGitignore(cwd, stash.gitignore);
2519
+ } finally {
2520
+ await rm(stash.root, {
2521
+ recursive: true,
2522
+ force: true
2523
+ });
2524
+ }
2525
+ }
2526
+ async function restoreRuntimeOnlyZitadel(cwd, stash) {
2527
+ if (!stash) return;
2528
+ const target = join(cwd, ".zitadel");
2529
+ try {
2530
+ await rename(stash, target);
2531
+ await appendGitignoreEntry(cwd, ".zitadel/local/");
2532
+ return;
2533
+ } catch (error) {
2534
+ if (!isErrno(error, "EEXIST")) throw error;
2535
+ }
2536
+ await mkdir(target, {
2537
+ recursive: true,
2538
+ mode: 448
2539
+ });
2540
+ await rename(join(stash, "local"), join(target, "local"));
2541
+ await rm(stash, {
2542
+ recursive: true,
2543
+ force: true
2544
+ });
2545
+ await appendGitignoreEntry(cwd, ".zitadel/local/");
2546
+ }
2547
+ async function restoreGitignore(cwd, stash) {
2548
+ if (!stash) return;
2549
+ const path = join(cwd, ".gitignore");
2550
+ const stashed = await readFile(stash, "utf8");
2551
+ let current = "";
2552
+ try {
2553
+ current = await readFile(path, "utf8");
2554
+ } catch (error) {
2555
+ if (!isErrno(error, "ENOENT")) throw error;
2556
+ }
2557
+ const existingLines = new Set(current.split(/\r?\n/g).map((line) => line.trim()).filter(Boolean));
2558
+ const missingLines = stashed.split(/\r?\n/g).map((line) => line.trim()).filter((line) => line.length > 0 && !existingLines.has(line));
2559
+ if (missingLines.length === 0) return;
2560
+ const prefix = current.length === 0 || current.endsWith("\n") ? "" : "\n";
2561
+ await writeFile(path, `${current}${prefix}${missingLines.join("\n")}\n`);
2562
+ }
2563
+ async function appendGitignoreEntry(cwd, entry) {
2564
+ const path = join(cwd, ".gitignore");
2565
+ let existing = "";
2566
+ try {
2567
+ existing = await readFile(path, "utf8");
2568
+ } catch (error) {
2569
+ if (!isErrno(error, "ENOENT")) throw error;
2570
+ }
2571
+ if (existing.split(/\r?\n/g).map((line) => line.trim()).includes(entry)) return;
2572
+ const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
2573
+ await writeFile(path, `${existing}${prefix}${entry}\n`);
2574
+ }
2575
+ function isErrno(error, code) {
2576
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
2577
+ }
2578
+ //#endregion
2579
+ export { issuerFromPort as i, inspectScaffoldTarget as n, RENDERER_IDS as r, createOrca as t };
2580
+
2581
+ //# sourceMappingURL=orca-BoTFU8SI.mjs.map