@zitadel/cli 0.1.0-alpha.3 → 0.1.0-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +91 -24
- package/SKILLS.md +20 -3
- package/dist/commands/apply.mjs +3 -4
- package/dist/commands/apply.mjs.map +1 -1
- package/dist/commands/doctor.mjs +4 -4
- package/dist/commands/eject.mjs +13 -6
- package/dist/commands/eject.mjs.map +1 -1
- package/dist/commands/logs.mjs +2 -2
- package/dist/commands/plan.mjs +3 -4
- package/dist/commands/plan.mjs.map +1 -1
- package/dist/commands/reset.mjs +2 -2
- package/dist/commands/setup.mjs +69 -13
- package/dist/commands/setup.mjs.map +1 -1
- package/dist/commands/start.mjs +2 -2
- package/dist/commands/status.mjs +3 -3
- package/dist/commands/stop.mjs +2 -2
- package/dist/{docker-D6pJKCLR.mjs → docker--EAWr_WY.mjs} +2 -2
- package/dist/{docker-D6pJKCLR.mjs.map → docker--EAWr_WY.mjs.map} +1 -1
- package/dist/{oclif-D-R4dfQr.mjs → oclif-2t97lHfY.mjs} +2 -2
- package/dist/{oclif-D-R4dfQr.mjs.map → oclif-2t97lHfY.mjs.map} +1 -1
- package/dist/orca-CYqJP4ZJ.mjs +2515 -0
- package/dist/orca-CYqJP4ZJ.mjs.map +1 -0
- package/dist/{project-DZJfxYKW.mjs → project-IzPVR0Pr.mjs} +2 -2
- package/dist/{project-DZJfxYKW.mjs.map → project-IzPVR0Pr.mjs.map} +1 -1
- package/dist/{sync-BJ0Sqb8w.mjs → sync-Df9S8Pio.mjs} +2 -2
- package/dist/{sync-BJ0Sqb8w.mjs.map → sync-Df9S8Pio.mjs.map} +1 -1
- package/oclif.manifest.json +15 -5
- package/package.json +4 -3
- package/dist/orca-BX4AhKLD.mjs +0 -1120
- package/dist/orca-BX4AhKLD.mjs.map +0 -1
|
@@ -0,0 +1,2515 @@
|
|
|
1
|
+
import { D as ZitadelError, E as stableStringify, S as MANAGED_MARKER, T as parseJsonObject, b as npmDistTagForCliVersion, n as DEFAULT_SERVER, w as isObject } from "./oclif-2t97lHfY.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/proxy.ts
|
|
710
|
+
/**
|
|
711
|
+
* The same-origin path the SDK widgets call (`configureZitadel({ proxyPath })`),
|
|
712
|
+
* which every framework's dev proxy forwards to the backend. Framework-agnostic:
|
|
713
|
+
* Vite (React/Vue), Angular's dev-server proxy, and Nuxt's server middleware all
|
|
714
|
+
* key off the same prefix, so it lives here rather than in any one framework's
|
|
715
|
+
* patcher.
|
|
716
|
+
*/
|
|
717
|
+
const PROXY_PATH = "/__nextgen";
|
|
718
|
+
//#endregion
|
|
719
|
+
//#region src/lib/orca/patchers/rule/angular/templates.ts
|
|
720
|
+
/**
|
|
721
|
+
* The managed root component `src/app/app.ts`: a standalone component that
|
|
722
|
+
* renders the `@zitadel/sdk-angular` widgets based on the current path. The
|
|
723
|
+
* project id (public, not secret) is inlined; the dev proxy in `proxy.conf.cjs`
|
|
724
|
+
* attaches the `sk_<project_id>` bearer (derived from that public id)
|
|
725
|
+
* server-side, and no secret reaches the browser.
|
|
726
|
+
*/
|
|
727
|
+
function appComponentTemplate(projectId) {
|
|
728
|
+
return `${MANAGED_MARKER}
|
|
729
|
+
import { Component } from "@angular/core";
|
|
730
|
+
import {
|
|
731
|
+
ZitadelLoginComponent,
|
|
732
|
+
ZitadelLogoutComponent,
|
|
733
|
+
configureZitadel,
|
|
734
|
+
} from "@zitadel/sdk-angular";
|
|
735
|
+
|
|
736
|
+
@Component({
|
|
737
|
+
selector: "app-root",
|
|
738
|
+
standalone: true,
|
|
739
|
+
imports: [ZitadelLoginComponent, ZitadelLogoutComponent],
|
|
740
|
+
templateUrl: "./app.html",
|
|
741
|
+
})
|
|
742
|
+
export class App {
|
|
743
|
+
protected readonly project = configureZitadel({
|
|
744
|
+
projectId: ${JSON.stringify(projectId)},
|
|
745
|
+
proxyPath: "${PROXY_PATH}",
|
|
746
|
+
});
|
|
747
|
+
protected readonly path = window.location.pathname;
|
|
748
|
+
}
|
|
749
|
+
`;
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* The managed `src/app/app.html`. The marker lives in an HTML comment that still
|
|
753
|
+
* contains the literal managed-marker text, so eject/doctor stay marker-aware.
|
|
754
|
+
*/
|
|
755
|
+
function appTemplateHtml() {
|
|
756
|
+
return `<!-- ${MANAGED_MARKER} -->
|
|
757
|
+
@if (path.startsWith('/profile')) {
|
|
758
|
+
<zitadel-auth-logout [project]="project" postSignOutUrl="/login"></zitadel-auth-logout>
|
|
759
|
+
} @else if (path.startsWith('/register')) {
|
|
760
|
+
<zitadel-auth-login
|
|
761
|
+
[project]="project"
|
|
762
|
+
purpose="register"
|
|
763
|
+
postSignInUrl="/profile"
|
|
764
|
+
></zitadel-auth-login>
|
|
765
|
+
} @else {
|
|
766
|
+
<zitadel-auth-login
|
|
767
|
+
[project]="project"
|
|
768
|
+
purpose="login"
|
|
769
|
+
postSignInUrl="/profile"
|
|
770
|
+
></zitadel-auth-login>
|
|
771
|
+
}
|
|
772
|
+
`;
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* The managed `proxy.conf.cjs` for `ng serve`: forwards `/__nextgen/*` to the
|
|
776
|
+
* backend (from `zitadel.json`), strips the prefix, and attaches the project's
|
|
777
|
+
* `sk_<project_id>` bearer to every proxied request. The prefix strip and the
|
|
778
|
+
* bearer are each provided in both the http-proxy-middleware form
|
|
779
|
+
* (`pathRewrite`/`onProxyReq`) and the Vite form (`rewrite`/`configure`), so
|
|
780
|
+
* both fire whichever proxy layer Angular's dev server uses.
|
|
781
|
+
*/
|
|
782
|
+
function proxyConfTemplate() {
|
|
783
|
+
return `${MANAGED_MARKER}
|
|
784
|
+
const { readFileSync } = require("node:fs");
|
|
785
|
+
|
|
786
|
+
const config = JSON.parse(readFileSync("zitadel.json", "utf8"));
|
|
787
|
+
if (!config.project || !config.server) {
|
|
788
|
+
throw new Error("zitadel.json is missing \\"project\\" or \\"server\\"; re-run zitadel setup.");
|
|
789
|
+
}
|
|
790
|
+
const bearer = \`Bearer sk_\${config.project}\`;
|
|
791
|
+
|
|
792
|
+
function setBearer(proxyReq) {
|
|
793
|
+
proxyReq.setHeader("authorization", bearer);
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
function stripPrefix(path) {
|
|
797
|
+
return path.replace(/^\\${PROXY_PATH}/, "").replace(/^(?!\\/)/, "/");
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
module.exports = {
|
|
801
|
+
"${PROXY_PATH}": {
|
|
802
|
+
target: config.server,
|
|
803
|
+
changeOrigin: false,
|
|
804
|
+
pathRewrite: stripPrefix,
|
|
805
|
+
rewrite: stripPrefix,
|
|
806
|
+
onProxyReq: setBearer,
|
|
807
|
+
configure: (proxy) => proxy.on("proxyReq", setBearer),
|
|
808
|
+
},
|
|
809
|
+
};
|
|
810
|
+
`;
|
|
811
|
+
}
|
|
812
|
+
//#endregion
|
|
813
|
+
//#region src/lib/orca/patchers/rule/angular/index.ts
|
|
814
|
+
const SDK_DEPENDENCY$3 = "@zitadel/sdk-angular";
|
|
815
|
+
/**
|
|
816
|
+
* Adds a `dev: "ng serve"` script only when the project does not already define
|
|
817
|
+
* one. `ng new` ships only a `start` script, but the CLI tells every framework
|
|
818
|
+
* to run `npm run dev` (and `ng serve` reads the proxy + port from
|
|
819
|
+
* `angular.json`). Non-destructive: an existing `dev` script is preserved, so
|
|
820
|
+
* patching a project that already wires its own `dev` leaves it untouched.
|
|
821
|
+
*/
|
|
822
|
+
function ensureDevScript(source) {
|
|
823
|
+
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." });
|
|
824
|
+
const pkg = parseJsonObject(source, "package.json");
|
|
825
|
+
const scripts = isObject(pkg.scripts) ? pkg.scripts : void 0;
|
|
826
|
+
if (scripts?.dev !== void 0) return source;
|
|
827
|
+
pkg.scripts = {
|
|
828
|
+
...scripts ?? {},
|
|
829
|
+
dev: "ng serve"
|
|
830
|
+
};
|
|
831
|
+
return `${stableStringify(pkg)}\n`;
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Rule-based patcher for an Angular app. Inherits the shared `.zitadel/` base
|
|
835
|
+
* files from {@link AbstractRulePatcher} and contributes the managed root
|
|
836
|
+
* component (`app.ts`/`app.html`) that renders the `@zitadel/sdk-angular`
|
|
837
|
+
* widgets, a `proxy.conf.cjs` dev proxy (attaching the `sk_<project_id>` bearer
|
|
838
|
+
* to every proxied request) wired into `angular.json`, and the SDK dep.
|
|
839
|
+
*
|
|
840
|
+
* Unlike React/Vue (whose dev proxy lives in `vite.config.ts`), Angular owns its
|
|
841
|
+
* Vite config, so the proxy is a separate `proxy.conf.cjs` referenced from the
|
|
842
|
+
* `serve` target. Production still needs `@zitadel/edge-proxy`.
|
|
843
|
+
*/
|
|
844
|
+
var AngularPatcher = class extends AbstractRulePatcher {
|
|
845
|
+
canPatch(framework) {
|
|
846
|
+
return framework === "angular";
|
|
847
|
+
}
|
|
848
|
+
routeOps(ctx) {
|
|
849
|
+
return [
|
|
850
|
+
{
|
|
851
|
+
kind: "write",
|
|
852
|
+
path: "src/app/app.ts",
|
|
853
|
+
contents: appComponentTemplate(ctx.project.id)
|
|
854
|
+
},
|
|
855
|
+
{
|
|
856
|
+
kind: "write",
|
|
857
|
+
path: "src/app/app.html",
|
|
858
|
+
contents: appTemplateHtml()
|
|
859
|
+
},
|
|
860
|
+
{
|
|
861
|
+
kind: "write",
|
|
862
|
+
path: "proxy.conf.cjs",
|
|
863
|
+
contents: proxyConfTemplate()
|
|
864
|
+
},
|
|
865
|
+
{
|
|
866
|
+
kind: "edit",
|
|
867
|
+
path: "angular.json",
|
|
868
|
+
edit: angularProxyEdit({
|
|
869
|
+
proxyConfig: "proxy.conf.cjs",
|
|
870
|
+
port: ctx.framework.devPort
|
|
871
|
+
})
|
|
872
|
+
},
|
|
873
|
+
{
|
|
874
|
+
kind: "edit",
|
|
875
|
+
path: "package.json",
|
|
876
|
+
edit: ensureDevScript
|
|
877
|
+
},
|
|
878
|
+
{
|
|
879
|
+
kind: "add-dep",
|
|
880
|
+
name: SDK_DEPENDENCY$3,
|
|
881
|
+
version: npmDistTagForCliVersion(ctx.cliVersion)
|
|
882
|
+
}
|
|
883
|
+
];
|
|
884
|
+
}
|
|
885
|
+
routeFiles(_view) {
|
|
886
|
+
return [
|
|
887
|
+
"src/app/app.ts",
|
|
888
|
+
"src/app/app.html",
|
|
889
|
+
"proxy.conf.cjs"
|
|
890
|
+
];
|
|
891
|
+
}
|
|
892
|
+
routeDeps(_view) {
|
|
893
|
+
return [SDK_DEPENDENCY$3];
|
|
894
|
+
}
|
|
895
|
+
routeConfigEdits(_view) {
|
|
896
|
+
return ["angular.json", "package.json"];
|
|
897
|
+
}
|
|
898
|
+
summary(_ctx) {
|
|
899
|
+
return {
|
|
900
|
+
title: "Angular integration",
|
|
901
|
+
detail: "Wrote the app root component + proxy.conf.cjs and wired the /__nextgen dev proxy into angular.json."
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
};
|
|
905
|
+
//#endregion
|
|
906
|
+
//#region src/lib/orca/patchers/rule/next/renderers/lit/index.ts
|
|
907
|
+
/**
|
|
908
|
+
* Placeholder renderer for the `<zitadel-flow>` Lit web component. Declared
|
|
909
|
+
* so the `web-component` renderer id resolves and surfaces a clear
|
|
910
|
+
* "not yet published" error, while reserving the integration shape for when
|
|
911
|
+
* `@zitadel/ui-lit` ships. The `authPage` template emits an illustrative
|
|
912
|
+
* page only; this renderer is never selected for real scaffolding because
|
|
913
|
+
* `getRenderer` rejects any `status: "not-implemented"` spec.
|
|
914
|
+
*/
|
|
915
|
+
const litRenderer = {
|
|
916
|
+
id: "web-component",
|
|
917
|
+
displayName: "Web component (<zitadel-flow>)",
|
|
918
|
+
status: "not-implemented",
|
|
919
|
+
frameworks: [
|
|
920
|
+
"next",
|
|
921
|
+
"astro",
|
|
922
|
+
"remix",
|
|
923
|
+
"sveltekit",
|
|
924
|
+
"nuxt",
|
|
925
|
+
"vanilla"
|
|
926
|
+
],
|
|
927
|
+
dependency: {
|
|
928
|
+
name: "@zitadel/ui-lit",
|
|
929
|
+
version: "workspace:*"
|
|
930
|
+
},
|
|
931
|
+
templates: { authPage(mode) {
|
|
932
|
+
return {
|
|
933
|
+
mode,
|
|
934
|
+
contents: `${MANAGED_MARKER}
|
|
935
|
+
// The web component renderer ships a <zitadel-flow> element. Until
|
|
936
|
+
// @zitadel/ui-lit is published, this template only declares the
|
|
937
|
+
// intended integration point. See docs/design/cli/bdui-renderer.md.
|
|
938
|
+
import "@zitadel/ui-lit";
|
|
939
|
+
|
|
940
|
+
const environment =
|
|
941
|
+
process.env.ZITADEL_ENVIRONMENT ??
|
|
942
|
+
(process.env.NODE_ENV === "production" ? "production" : "development");
|
|
943
|
+
|
|
944
|
+
export default function ${mode === "login" ? "LoginPage" : "RegisterPage"}() {
|
|
945
|
+
return (
|
|
946
|
+
<zitadel-flow
|
|
947
|
+
purpose="${mode === "login" ? "login" : "register"}"
|
|
948
|
+
project-id={process.env.ZITADEL_PROJECT_ID}
|
|
949
|
+
issuer={process.env.ZITADEL_ISSUER}
|
|
950
|
+
environment={environment}
|
|
951
|
+
/>
|
|
952
|
+
);
|
|
953
|
+
}
|
|
954
|
+
`
|
|
955
|
+
};
|
|
956
|
+
} }
|
|
957
|
+
};
|
|
958
|
+
//#endregion
|
|
959
|
+
//#region src/lib/orca/patchers/rule/next/renderers/react/index.ts
|
|
960
|
+
/**
|
|
961
|
+
* The Next.js App Router renderer scaffolds `/login`, `/register`, and
|
|
962
|
+
* `/profile` pages that drive the `<zitadel-login>` and `<zitadel-logout>`
|
|
963
|
+
* Lit web components.
|
|
964
|
+
*
|
|
965
|
+
* Each page is a single client component (`"use client"`) that, inside a
|
|
966
|
+
* `next/dynamic({ ssr: false })` loader, builds the SDK project handle with
|
|
967
|
+
* `configureZitadel({ projectId, proxyPath: "/__nextgen" })` and passes it to
|
|
968
|
+
* the widget via `project={...}`. It also imports
|
|
969
|
+
* `@zitadel/sdk-next/client` for its `customElements.define`
|
|
970
|
+
* side-effect — importing `@zitadel/components` directly would fail on
|
|
971
|
+
* strict-resolution package managers (pnpm, yarn PnP) because the app only
|
|
972
|
+
* declares `sdk-next` as a direct dep. SSR is disabled because Lit's element
|
|
973
|
+
* registration needs a browser.
|
|
974
|
+
*
|
|
975
|
+
* The handle is passed as the `project` DOM property, which relies on React
|
|
976
|
+
* 19's custom-element property binding (the scaffold targets the latest Next /
|
|
977
|
+
* React). The backend URL never reaches the browser: the client talks to the
|
|
978
|
+
* same-origin `/__nextgen` proxy path, and the scaffolded Next request boundary
|
|
979
|
+
* forwards it to `ZITADEL_URL` server-side. `NEXT_PUBLIC_ZITADEL_PROJECT_ID` is
|
|
980
|
+
* public — the project id is not sensitive and the widget needs it to start a
|
|
981
|
+
* flow.
|
|
982
|
+
*/
|
|
983
|
+
const reactRenderer = {
|
|
984
|
+
id: "react",
|
|
985
|
+
displayName: "React (Next.js App Router)",
|
|
986
|
+
status: "available",
|
|
987
|
+
frameworks: ["next"],
|
|
988
|
+
dependency: {
|
|
989
|
+
name: "@zitadel/sdk-next",
|
|
990
|
+
version: "latest"
|
|
991
|
+
},
|
|
992
|
+
templates: {
|
|
993
|
+
authPage(mode) {
|
|
994
|
+
const componentName = mode === "login" ? "LoginPage" : "RegisterPage";
|
|
995
|
+
const elementName = mode === "login" ? "ZitadelLogin" : "ZitadelRegister";
|
|
996
|
+
return {
|
|
997
|
+
mode,
|
|
998
|
+
contents: `${MANAGED_MARKER}
|
|
999
|
+
"use client";
|
|
1000
|
+
|
|
1001
|
+
import dynamic from "next/dynamic";
|
|
1002
|
+
import Link from "next/link";
|
|
1003
|
+
|
|
1004
|
+
const ${elementName} = dynamic(
|
|
1005
|
+
async () => {
|
|
1006
|
+
const { configureZitadel } = await import("@zitadel/sdk-next/client");
|
|
1007
|
+
// Build the SDK project handle and pass it to the component via the
|
|
1008
|
+
// \`project\` prop. The component reads config from this prop directly, so
|
|
1009
|
+
// it works regardless of how the SDK packages are bundled. The backend URL
|
|
1010
|
+
// stays server-side: requests go through the proxy path "/__nextgen",
|
|
1011
|
+
// which the scaffolded request boundary forwards to the Zitadel server.
|
|
1012
|
+
const project = configureZitadel({
|
|
1013
|
+
projectId: process.env.NEXT_PUBLIC_ZITADEL_PROJECT_ID ?? "",
|
|
1014
|
+
proxyPath: "/__nextgen",
|
|
1015
|
+
});
|
|
1016
|
+
return function ${elementName}Element() {
|
|
1017
|
+
return (
|
|
1018
|
+
<zitadel-login
|
|
1019
|
+
project={project}
|
|
1020
|
+
purpose="${mode}"
|
|
1021
|
+
post-sign-in-url="/profile"
|
|
1022
|
+
/>
|
|
1023
|
+
);
|
|
1024
|
+
};
|
|
1025
|
+
},
|
|
1026
|
+
{ ssr: false },
|
|
1027
|
+
);
|
|
1028
|
+
|
|
1029
|
+
export default function ${componentName}() {
|
|
1030
|
+
return (
|
|
1031
|
+
<main style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", position: "relative", padding: "48px 24px" }}>
|
|
1032
|
+
<nav aria-label="Authentication" style={{ position: "absolute", top: "24px", right: "24px", display: "flex", gap: "12px" }}>
|
|
1033
|
+
<Link href="${mode === "login" ? "/register" : "/login"}" style={{ color: "#111827", fontWeight: 700, textDecoration: "none" }}>
|
|
1034
|
+
${mode === "login" ? "Create account" : "Sign in"}
|
|
1035
|
+
</Link>
|
|
1036
|
+
</nav>
|
|
1037
|
+
<${elementName} />
|
|
1038
|
+
</main>
|
|
1039
|
+
);
|
|
1040
|
+
}
|
|
1041
|
+
`
|
|
1042
|
+
};
|
|
1043
|
+
},
|
|
1044
|
+
profilePage() {
|
|
1045
|
+
return { contents: `${MANAGED_MARKER}
|
|
1046
|
+
"use client";
|
|
1047
|
+
|
|
1048
|
+
import dynamic from "next/dynamic";
|
|
1049
|
+
import { useEffect, useState } from "react";
|
|
1050
|
+
|
|
1051
|
+
type SessionProof = {
|
|
1052
|
+
session_id?: string;
|
|
1053
|
+
state?: string;
|
|
1054
|
+
user_id?: string;
|
|
1055
|
+
};
|
|
1056
|
+
|
|
1057
|
+
const ZitadelLogout = dynamic(
|
|
1058
|
+
async () => {
|
|
1059
|
+
const { configureZitadel } = await import("@zitadel/sdk-next/client");
|
|
1060
|
+
const project = configureZitadel({
|
|
1061
|
+
projectId: process.env.NEXT_PUBLIC_ZITADEL_PROJECT_ID ?? "",
|
|
1062
|
+
proxyPath: "/__nextgen",
|
|
1063
|
+
});
|
|
1064
|
+
return function ZitadelLogoutElement() {
|
|
1065
|
+
return (
|
|
1066
|
+
<zitadel-logout
|
|
1067
|
+
project={project}
|
|
1068
|
+
post-sign-out-url="/login"
|
|
1069
|
+
/>
|
|
1070
|
+
);
|
|
1071
|
+
};
|
|
1072
|
+
},
|
|
1073
|
+
{ ssr: false },
|
|
1074
|
+
);
|
|
1075
|
+
|
|
1076
|
+
export default function ProfilePage() {
|
|
1077
|
+
const [session, setSession] = useState<SessionProof | null>(null);
|
|
1078
|
+
const [sessionError, setSessionError] = useState("");
|
|
1079
|
+
|
|
1080
|
+
useEffect(() => {
|
|
1081
|
+
let cancelled = false;
|
|
1082
|
+
|
|
1083
|
+
fetch("/__nextgen/sessions/me", { cache: "no-store" })
|
|
1084
|
+
.then(async (response) => {
|
|
1085
|
+
if (!response.ok) {
|
|
1086
|
+
throw new Error("Session check failed: " + String(response.status));
|
|
1087
|
+
}
|
|
1088
|
+
return response.json() as Promise<SessionProof>;
|
|
1089
|
+
})
|
|
1090
|
+
.then((nextSession) => {
|
|
1091
|
+
if (!cancelled) {
|
|
1092
|
+
setSession(nextSession);
|
|
1093
|
+
}
|
|
1094
|
+
})
|
|
1095
|
+
.catch((error: unknown) => {
|
|
1096
|
+
if (!cancelled) {
|
|
1097
|
+
setSessionError(error instanceof Error ? error.message : "Session check failed");
|
|
1098
|
+
}
|
|
1099
|
+
});
|
|
1100
|
+
|
|
1101
|
+
return () => {
|
|
1102
|
+
cancelled = true;
|
|
1103
|
+
};
|
|
1104
|
+
}, []);
|
|
1105
|
+
|
|
1106
|
+
return (
|
|
1107
|
+
<main style={{ padding: "48px", maxWidth: "680px", margin: "0 auto" }}>
|
|
1108
|
+
<div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: "24px" }}>
|
|
1109
|
+
<h1 style={{ fontSize: "24px", fontWeight: 700, margin: 0 }}>Signed in</h1>
|
|
1110
|
+
<ZitadelLogout />
|
|
1111
|
+
</div>
|
|
1112
|
+
<p style={{ color: "#166534", fontWeight: 600 }}>Signed in profile loaded.</p>
|
|
1113
|
+
{session ? (
|
|
1114
|
+
<dl style={{ display: "grid", gap: "12px", marginTop: "24px" }}>
|
|
1115
|
+
<div>
|
|
1116
|
+
<dt style={{ color: "#6b7280", fontSize: "14px" }}>Session state</dt>
|
|
1117
|
+
<dd style={{ margin: 0, fontWeight: 600 }}>{session.state ?? "active"}</dd>
|
|
1118
|
+
</div>
|
|
1119
|
+
<div>
|
|
1120
|
+
<dt style={{ color: "#6b7280", fontSize: "14px" }}>User id</dt>
|
|
1121
|
+
<dd style={{ margin: 0, fontFamily: "monospace" }}>{session.user_id ?? "available"}</dd>
|
|
1122
|
+
</div>
|
|
1123
|
+
</dl>
|
|
1124
|
+
) : (
|
|
1125
|
+
<p style={{ color: sessionError ? "#b91c1c" : "#6b7280" }}>
|
|
1126
|
+
{sessionError || "Checking session..."}
|
|
1127
|
+
</p>
|
|
1128
|
+
)}
|
|
1129
|
+
</main>
|
|
1130
|
+
);
|
|
1131
|
+
}
|
|
1132
|
+
` };
|
|
1133
|
+
},
|
|
1134
|
+
customElementsDts() {
|
|
1135
|
+
return { contents: `${MANAGED_MARKER}
|
|
1136
|
+
import type React from "react";
|
|
1137
|
+
import type { ZitadelProject } from "@zitadel/sdk-next/client";
|
|
1138
|
+
|
|
1139
|
+
declare module "react" {
|
|
1140
|
+
namespace JSX {
|
|
1141
|
+
interface IntrinsicElements {
|
|
1142
|
+
"zitadel-login": React.HTMLAttributes<HTMLElement> & {
|
|
1143
|
+
project?: ZitadelProject;
|
|
1144
|
+
"session-exchange-path"?: string;
|
|
1145
|
+
"post-sign-in-url"?: string;
|
|
1146
|
+
purpose?: string;
|
|
1147
|
+
};
|
|
1148
|
+
"zitadel-logout": React.HTMLAttributes<HTMLElement> & {
|
|
1149
|
+
project?: ZitadelProject;
|
|
1150
|
+
"post-sign-out-url"?: string;
|
|
1151
|
+
};
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
` };
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
};
|
|
1159
|
+
//#endregion
|
|
1160
|
+
//#region src/lib/orca/patchers/rule/next/renderers/registry.ts
|
|
1161
|
+
/**
|
|
1162
|
+
* Runtime mirror of the {@link RendererId} union, used by {@link isRendererId}
|
|
1163
|
+
* to validate untrusted strings (a TS union has no runtime presence). Must stay
|
|
1164
|
+
* in sync with the {@link RendererId} type.
|
|
1165
|
+
*/
|
|
1166
|
+
const RENDERER_IDS = ["react", "web-component"];
|
|
1167
|
+
/**
|
|
1168
|
+
* Type guard narrowing an arbitrary value to a {@link RendererId}, used to
|
|
1169
|
+
* validate renderer ids read from config before indexing {@link RENDERERS}.
|
|
1170
|
+
*/
|
|
1171
|
+
function isRendererId(value) {
|
|
1172
|
+
return typeof value === "string" && RENDERER_IDS.includes(value);
|
|
1173
|
+
}
|
|
1174
|
+
/**
|
|
1175
|
+
* The single source of truth mapping each {@link RendererId} to its spec.
|
|
1176
|
+
* Keyed by id so {@link getRenderer} can look up and validate a renderer
|
|
1177
|
+
* chosen from persisted config (an arbitrary string) at runtime.
|
|
1178
|
+
*/
|
|
1179
|
+
const RENDERERS = {
|
|
1180
|
+
react: reactRenderer,
|
|
1181
|
+
"web-component": litRenderer
|
|
1182
|
+
};
|
|
1183
|
+
/**
|
|
1184
|
+
* Resolves a renderer id (an untrusted string from config) to its spec,
|
|
1185
|
+
* throwing a typed {@link ZitadelError} rather than returning `undefined`
|
|
1186
|
+
* so callers get an actionable message. Rejects ids that are unknown
|
|
1187
|
+
* (`E_VALIDATION`) or declared-but-unpublished (`E_NOT_IMPLEMENTED`),
|
|
1188
|
+
* guaranteeing the returned spec is safe to scaffold from.
|
|
1189
|
+
*/
|
|
1190
|
+
function getRenderer(id) {
|
|
1191
|
+
if (!isRendererId(id)) throw new ZitadelError("E_VALIDATION", `Unknown renderer "${id}"`, { hint: `Available renderers: ${Object.keys(RENDERERS).join(", ")}` });
|
|
1192
|
+
const renderer = RENDERERS[id];
|
|
1193
|
+
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." });
|
|
1194
|
+
return renderer;
|
|
1195
|
+
}
|
|
1196
|
+
//#endregion
|
|
1197
|
+
//#region src/lib/orca/patchers/rule/next/index.ts
|
|
1198
|
+
/**
|
|
1199
|
+
* Next.js request-boundary file at the project root. Wires `nextgenMiddleware` so the
|
|
1200
|
+
* generated project config's `/__nextgen` proxy path is same-origin proxied
|
|
1201
|
+
* to `ZITADEL_URL` and `/profile` is gated. Next 16 renamed this convention to
|
|
1202
|
+
* `proxy.ts`; older projects keep `middleware.ts`.
|
|
1203
|
+
* Carries the managed marker so `doctor --fix` reclaims it and `eject` removes it.
|
|
1204
|
+
*/
|
|
1205
|
+
function requestBoundaryTemplate(functionName) {
|
|
1206
|
+
return `${MANAGED_MARKER}
|
|
1207
|
+
import { nextgenMiddleware } from "@zitadel/sdk-next/middleware";
|
|
1208
|
+
import type { NextRequest } from "next/server";
|
|
1209
|
+
|
|
1210
|
+
export function ${functionName}(req: NextRequest) {
|
|
1211
|
+
return nextgenMiddleware(req, {
|
|
1212
|
+
url: process.env.ZITADEL_URL,
|
|
1213
|
+
protectedRoutes: ["/profile"],
|
|
1214
|
+
loginPath: "/login",
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
export const config = {
|
|
1219
|
+
matcher: ["/__nextgen/:path*", "/profile/:path*"],
|
|
1220
|
+
};
|
|
1221
|
+
`;
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Rule-based patcher for the Next.js App Router. Inherits the shared
|
|
1225
|
+
* `.zitadel/` base files from {@link AbstractRulePatcher} and contributes the
|
|
1226
|
+
* Next routes and request boundary whose templates come from the chosen renderer.
|
|
1227
|
+
*/
|
|
1228
|
+
var NextPatcher = class extends AbstractRulePatcher {
|
|
1229
|
+
/** Returns true for Next.js projects. */
|
|
1230
|
+
canPatch(framework) {
|
|
1231
|
+
return framework === "next";
|
|
1232
|
+
}
|
|
1233
|
+
routeOps(ctx) {
|
|
1234
|
+
return nextCodeOps(ctx, getRenderer(ctx.rendererId));
|
|
1235
|
+
}
|
|
1236
|
+
routeFiles(view) {
|
|
1237
|
+
return nextCodeFilePaths(view.framework, getRenderer(view.rendererId));
|
|
1238
|
+
}
|
|
1239
|
+
routeDeps(view) {
|
|
1240
|
+
return [getRenderer(view.rendererId).dependency.name];
|
|
1241
|
+
}
|
|
1242
|
+
summary(ctx) {
|
|
1243
|
+
return {
|
|
1244
|
+
title: "Next.js integration",
|
|
1245
|
+
detail: `Scaffolded login/register/profile routes with renderer "${ctx.rendererId}".`
|
|
1246
|
+
};
|
|
1247
|
+
}
|
|
1248
|
+
};
|
|
1249
|
+
/**
|
|
1250
|
+
* Ordered paths of the framework code files the patcher writes. All carry the
|
|
1251
|
+
* managed marker. Shared by {@link NextPatcher.routeOps} (which adds contents)
|
|
1252
|
+
* and {@link NextPatcher.routeFiles} (which only needs the paths) so the two
|
|
1253
|
+
* cannot drift.
|
|
1254
|
+
*/
|
|
1255
|
+
function nextCodeFilePaths(framework, renderer) {
|
|
1256
|
+
const appDir = framework.appDir;
|
|
1257
|
+
const paths = [
|
|
1258
|
+
join(appDir, "page.tsx"),
|
|
1259
|
+
join(appDir, "login/page.tsx"),
|
|
1260
|
+
join(appDir, "register/page.tsx")
|
|
1261
|
+
];
|
|
1262
|
+
if (renderer.templates.profilePage) paths.push(join(appDir, "profile/page.tsx"));
|
|
1263
|
+
paths.push(join(appDir, `../${requestBoundaryFile(framework).filename}`));
|
|
1264
|
+
if (renderer.templates.provider) paths.push(join(appDir, renderer.templates.provider.filename));
|
|
1265
|
+
if (renderer.templates.customElementsDts) paths.push(join(appDir, "../custom-elements.d.ts"));
|
|
1266
|
+
return paths;
|
|
1267
|
+
}
|
|
1268
|
+
/** The Next route/request-boundary write ops plus the SDK dependency. */
|
|
1269
|
+
function nextCodeOps(ctx, renderer) {
|
|
1270
|
+
const appDir = ctx.framework.appDir;
|
|
1271
|
+
const profile = renderer.templates.profilePage?.();
|
|
1272
|
+
const provider = renderer.templates.provider;
|
|
1273
|
+
const dts = renderer.templates.customElementsDts?.();
|
|
1274
|
+
const boundary = requestBoundaryFile(ctx.framework);
|
|
1275
|
+
return [
|
|
1276
|
+
ctx.scaffoldedFramework ? {
|
|
1277
|
+
kind: "edit",
|
|
1278
|
+
path: join(appDir, "page.tsx"),
|
|
1279
|
+
edit: () => homePageTemplate()
|
|
1280
|
+
} : void 0,
|
|
1281
|
+
{
|
|
1282
|
+
kind: "write",
|
|
1283
|
+
path: join(appDir, "login/page.tsx"),
|
|
1284
|
+
contents: renderer.templates.authPage("login").contents
|
|
1285
|
+
},
|
|
1286
|
+
{
|
|
1287
|
+
kind: "write",
|
|
1288
|
+
path: join(appDir, "register/page.tsx"),
|
|
1289
|
+
contents: renderer.templates.authPage("register").contents
|
|
1290
|
+
},
|
|
1291
|
+
profile ? {
|
|
1292
|
+
kind: "write",
|
|
1293
|
+
path: join(appDir, "profile/page.tsx"),
|
|
1294
|
+
contents: profile.contents
|
|
1295
|
+
} : void 0,
|
|
1296
|
+
{
|
|
1297
|
+
kind: "write",
|
|
1298
|
+
path: join(appDir, `../${boundary.filename}`),
|
|
1299
|
+
contents: requestBoundaryTemplate(boundary.functionName)
|
|
1300
|
+
},
|
|
1301
|
+
provider ? {
|
|
1302
|
+
kind: "write",
|
|
1303
|
+
path: join(appDir, provider.filename),
|
|
1304
|
+
contents: provider.contents
|
|
1305
|
+
} : void 0,
|
|
1306
|
+
dts ? {
|
|
1307
|
+
kind: "write",
|
|
1308
|
+
path: join(appDir, "../custom-elements.d.ts"),
|
|
1309
|
+
contents: dts.contents
|
|
1310
|
+
} : void 0,
|
|
1311
|
+
{
|
|
1312
|
+
kind: "merge-env",
|
|
1313
|
+
path: ".env.example",
|
|
1314
|
+
entries: { NEXT_PUBLIC_ZITADEL_PROJECT_ID: "" }
|
|
1315
|
+
},
|
|
1316
|
+
{
|
|
1317
|
+
kind: "merge-env",
|
|
1318
|
+
path: ".env.local",
|
|
1319
|
+
entries: { NEXT_PUBLIC_ZITADEL_PROJECT_ID: ctx.project.id }
|
|
1320
|
+
},
|
|
1321
|
+
{
|
|
1322
|
+
kind: "add-dep",
|
|
1323
|
+
name: renderer.dependency.name,
|
|
1324
|
+
version: dependencyVersionForCli(ctx.cliVersion, renderer.dependency.version)
|
|
1325
|
+
}
|
|
1326
|
+
].filter((op) => op !== void 0);
|
|
1327
|
+
}
|
|
1328
|
+
function homePageTemplate() {
|
|
1329
|
+
return `${MANAGED_MARKER}
|
|
1330
|
+
import Link from "next/link";
|
|
1331
|
+
|
|
1332
|
+
export default function Home() {
|
|
1333
|
+
return (
|
|
1334
|
+
<main style={{ minHeight: "100vh", padding: "48px", display: "flex", alignItems: "center", justifyContent: "center" }}>
|
|
1335
|
+
<section style={{ width: "100%", maxWidth: "560px" }}>
|
|
1336
|
+
<p style={{ margin: "0 0 12px", color: "#4b5563", fontSize: "14px" }}>Zitadel auth</p>
|
|
1337
|
+
<h1 style={{ margin: "0 0 24px", fontSize: "32px", lineHeight: 1.15 }}>Sign in, create an account, or open your profile.</h1>
|
|
1338
|
+
<div style={{ display: "flex", flexWrap: "wrap", gap: "12px" }}>
|
|
1339
|
+
<Link href="/login" style={{ padding: "10px 16px", borderRadius: "8px", background: "#111827", color: "#ffffff", textDecoration: "none", fontWeight: 600 }}>
|
|
1340
|
+
Sign in
|
|
1341
|
+
</Link>
|
|
1342
|
+
<Link href="/register" style={{ padding: "10px 16px", borderRadius: "8px", border: "1px solid #d1d5db", color: "#111827", textDecoration: "none", fontWeight: 600 }}>
|
|
1343
|
+
Create account
|
|
1344
|
+
</Link>
|
|
1345
|
+
<Link href="/profile" style={{ padding: "10px 16px", borderRadius: "8px", border: "1px solid #d1d5db", color: "#111827", textDecoration: "none", fontWeight: 600 }}>
|
|
1346
|
+
Profile
|
|
1347
|
+
</Link>
|
|
1348
|
+
</div>
|
|
1349
|
+
</section>
|
|
1350
|
+
</main>
|
|
1351
|
+
);
|
|
1352
|
+
}
|
|
1353
|
+
`;
|
|
1354
|
+
}
|
|
1355
|
+
function requestBoundaryFile(framework) {
|
|
1356
|
+
if ((framework.versionMajor ?? 0) >= 16) return {
|
|
1357
|
+
filename: "proxy.ts",
|
|
1358
|
+
functionName: "proxy"
|
|
1359
|
+
};
|
|
1360
|
+
return {
|
|
1361
|
+
filename: "middleware.ts",
|
|
1362
|
+
functionName: "middleware"
|
|
1363
|
+
};
|
|
1364
|
+
}
|
|
1365
|
+
function dependencyVersionForCli(cliVersion, fallback) {
|
|
1366
|
+
const normalized = cliVersion.trim().replace(/^v/, "");
|
|
1367
|
+
if (/^\d+\.\d+\.\d+-alpha\.\d+$/.test(normalized)) return normalized;
|
|
1368
|
+
return normalized.match(/^\d+\.\d+\.\d+-([0-9A-Za-z]+)(?:[.-]|$)/)?.[1] ?? fallback;
|
|
1369
|
+
}
|
|
1370
|
+
//#endregion
|
|
1371
|
+
//#region src/lib/orca/patchers/rule/config-paths.ts
|
|
1372
|
+
/**
|
|
1373
|
+
* The module extensions the config edits can actually write, in resolution
|
|
1374
|
+
* priority. magicast injects ESM `import`/`import.meta.url`, so only ESM-capable
|
|
1375
|
+
* extensions are editable; CommonJS (`cts`/`cjs`) is not.
|
|
1376
|
+
*/
|
|
1377
|
+
const CONFIG_EXTENSIONS = [
|
|
1378
|
+
"ts",
|
|
1379
|
+
"mts",
|
|
1380
|
+
"js",
|
|
1381
|
+
"mjs"
|
|
1382
|
+
];
|
|
1383
|
+
/**
|
|
1384
|
+
* The CommonJS extensions we still *probe* (after the ESM ones) so a project
|
|
1385
|
+
* whose only config is `*.cjs`/`*.cts` is found and rejected with a targeted
|
|
1386
|
+
* "CommonJS is unsupported" error, rather than a misleading "file not found".
|
|
1387
|
+
* {@link parseConfigModule} surfaces that error when it sees CommonJS source.
|
|
1388
|
+
*/
|
|
1389
|
+
const COMMONJS_EXTENSIONS = ["cts", "cjs"];
|
|
1390
|
+
/**
|
|
1391
|
+
* Candidate config filenames for `basename`, ESM extensions first then the
|
|
1392
|
+
* CommonJS ones, e.g. `configCandidates("vite.config")` → `["vite.config.ts",
|
|
1393
|
+
* "vite.config.mts", "vite.config.js", "vite.config.mjs", "vite.config.cts",
|
|
1394
|
+
* "vite.config.cjs"]`. Handed to the
|
|
1395
|
+
* generic `edit` file-op, which patches the first one that exists — an ESM
|
|
1396
|
+
* config wins, and a CommonJS-only project is still read so the edit can emit a
|
|
1397
|
+
* clear unsupported-format error.
|
|
1398
|
+
*/
|
|
1399
|
+
function configCandidates(basename) {
|
|
1400
|
+
return [...CONFIG_EXTENSIONS, ...COMMONJS_EXTENSIONS].map((ext) => `${basename}.${ext}`);
|
|
1401
|
+
}
|
|
1402
|
+
//#endregion
|
|
1403
|
+
//#region src/lib/orca/patchers/rule/utils/magicast.ts
|
|
1404
|
+
/**
|
|
1405
|
+
* Generic magicast helpers shared by the config-editing patchers (Vite, Nuxt).
|
|
1406
|
+
* They navigate a module's default export — they carry no framework knowledge
|
|
1407
|
+
* beyond "find the config object literal" and "is this import present".
|
|
1408
|
+
*/
|
|
1409
|
+
/**
|
|
1410
|
+
* Parses a config file with magicast, throwing a clean `E_VALIDATION` (instead
|
|
1411
|
+
* of a raw parse error) when the source is missing or unparseable. `filename` is
|
|
1412
|
+
* only used in the error message, so each patcher can name its own config file.
|
|
1413
|
+
*/
|
|
1414
|
+
function parseConfigModule(source, filename) {
|
|
1415
|
+
if (source === void 0) throw new ZitadelError("E_VALIDATION", `Cannot edit ${filename}: file not found`, { hint: `Run setup from a project that has ${filename}.` });
|
|
1416
|
+
let mod;
|
|
1417
|
+
try {
|
|
1418
|
+
mod = parseModule(source);
|
|
1419
|
+
} catch (error) {
|
|
1420
|
+
throw new ZitadelError("E_VALIDATION", `Could not parse ${filename}`, {
|
|
1421
|
+
hint: `Ensure ${filename} is valid, or apply the Zitadel changes manually.`,
|
|
1422
|
+
details: { cause: error instanceof Error ? error.message : String(error) }
|
|
1423
|
+
});
|
|
1424
|
+
}
|
|
1425
|
+
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.` });
|
|
1426
|
+
return mod;
|
|
1427
|
+
}
|
|
1428
|
+
/**
|
|
1429
|
+
* Whether the module has a top-level CommonJS export assignment —
|
|
1430
|
+
* `module.exports = …`, `module.exports.x = …`, or `exports.x = …` — read from
|
|
1431
|
+
* the parsed AST so comments and string literals can't trigger a false match.
|
|
1432
|
+
*/
|
|
1433
|
+
function hasCommonJsExport(mod) {
|
|
1434
|
+
return ((mod?.$ast?.program ?? mod?.$ast)?.body ?? []).some((node) => {
|
|
1435
|
+
if (node?.type !== "ExpressionStatement" || node.expression?.type !== "AssignmentExpression") return false;
|
|
1436
|
+
const left = node.expression.left;
|
|
1437
|
+
if (left?.type !== "MemberExpression") return false;
|
|
1438
|
+
const object = left.object;
|
|
1439
|
+
if (object?.type === "Identifier" && object.name === "exports") return true;
|
|
1440
|
+
if (object?.type === "Identifier" && object.name === "module" && left.property?.name === "exports") return true;
|
|
1441
|
+
return object?.type === "MemberExpression" && object.object?.name === "module" && object.property?.name === "exports";
|
|
1442
|
+
});
|
|
1443
|
+
}
|
|
1444
|
+
/**
|
|
1445
|
+
* Reaches the object literal of a module's default export — the argument of
|
|
1446
|
+
* `export default <call>({...})` (e.g. `defineConfig`/`defineNuxtConfig`) or a
|
|
1447
|
+
* bare `export default {...}`. Throws `E_VALIDATION` for shapes magicast cannot
|
|
1448
|
+
* safely edit (function-form, configs built elsewhere) so the caller can fall
|
|
1449
|
+
* back to manual steps.
|
|
1450
|
+
*/
|
|
1451
|
+
function resolveDefaultExportObject(mod, filename) {
|
|
1452
|
+
const def = mod.exports?.default;
|
|
1453
|
+
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).` });
|
|
1454
|
+
if (!def) throw unreachable();
|
|
1455
|
+
if (def.$type === "function-call") {
|
|
1456
|
+
const arg = def.$args?.[0];
|
|
1457
|
+
if (!arg || arg.$type !== "object") throw unreachable();
|
|
1458
|
+
return arg;
|
|
1459
|
+
}
|
|
1460
|
+
if (def.$type === "object") return def;
|
|
1461
|
+
throw unreachable();
|
|
1462
|
+
}
|
|
1463
|
+
function importIsPresent(mod, local, from) {
|
|
1464
|
+
try {
|
|
1465
|
+
return (mod.imports?.$items ?? []).some((item) => item.local === local && (from === void 0 || item.from === from));
|
|
1466
|
+
} catch {
|
|
1467
|
+
return false;
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
/**
|
|
1471
|
+
* Appends `item` to a string array at `parent[key]`, creating the array when
|
|
1472
|
+
* absent and skipping it when already present. Reads the proxified array by
|
|
1473
|
+
* index so primitive elements compare as plain values. Returns `true` when it
|
|
1474
|
+
* actually added the item, so callers can tell whether the edit changed
|
|
1475
|
+
* anything (and skip rewriting an already-complete config).
|
|
1476
|
+
*/
|
|
1477
|
+
function ensureArrayItem(parent, key, item) {
|
|
1478
|
+
if (parent[key] === void 0) {
|
|
1479
|
+
parent[key] = [item];
|
|
1480
|
+
return true;
|
|
1481
|
+
}
|
|
1482
|
+
const arr = parent[key];
|
|
1483
|
+
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.` });
|
|
1484
|
+
if (!Array.from({ length: arr.length }, (_unused, i) => arr[i]).includes(item)) {
|
|
1485
|
+
arr.push(item);
|
|
1486
|
+
return true;
|
|
1487
|
+
}
|
|
1488
|
+
return false;
|
|
1489
|
+
}
|
|
1490
|
+
/**
|
|
1491
|
+
* Returns the object literal at `parent[key]`, creating an empty one when
|
|
1492
|
+
* absent, so callers can safely descend into it. Throws `E_VALIDATION` when the
|
|
1493
|
+
* key already holds something that is not an inline object literal (an
|
|
1494
|
+
* identifier, spread, or function call) — magicast cannot edit those, and
|
|
1495
|
+
* assigning into them otherwise throws a raw proxy `TypeError`. The object
|
|
1496
|
+
* sibling of {@link ensureArrayItem}.
|
|
1497
|
+
*/
|
|
1498
|
+
function ensureEditableObject(parent, key) {
|
|
1499
|
+
if (parent[key] === void 0) parent[key] = {};
|
|
1500
|
+
const value = parent[key];
|
|
1501
|
+
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.` });
|
|
1502
|
+
return value;
|
|
1503
|
+
}
|
|
1504
|
+
//#endregion
|
|
1505
|
+
//#region src/lib/orca/patchers/rule/nuxt/nuxt-config.ts
|
|
1506
|
+
const NUXT_MODULE = "@zitadel/sdk-nuxt/module";
|
|
1507
|
+
/**
|
|
1508
|
+
* Builds the pure `edit` transform the file-writer applies to the project's Nuxt
|
|
1509
|
+
* config (`nuxt.config.*`): registers the `@zitadel/sdk-nuxt` module (which wires
|
|
1510
|
+
* the server-side proxy + session middleware), sets the login path, seeds
|
|
1511
|
+
* `runtimeConfig` with the backend URL, the proxy path, and the project id, and
|
|
1512
|
+
* marks the `zitadel-*` Lit elements as custom elements for the Vue compiler —
|
|
1513
|
+
* preserving the user's existing config via magicast. Idempotent. Throws
|
|
1514
|
+
* `E_VALIDATION` when the file is absent or `defineNuxtConfig` cannot be reached.
|
|
1515
|
+
*/
|
|
1516
|
+
function nuxtConfigEdit(opts) {
|
|
1517
|
+
return (source) => {
|
|
1518
|
+
const label = "the Nuxt config (nuxt.config.*)";
|
|
1519
|
+
const mod = parseConfigModule(source, label);
|
|
1520
|
+
const config = resolveDefaultExportObject(mod, label);
|
|
1521
|
+
let changed = ensureArrayItem(config, "modules", NUXT_MODULE);
|
|
1522
|
+
const nextgen = ensureEditableObject(config, "nextgen");
|
|
1523
|
+
if (nextgen.url === void 0) {
|
|
1524
|
+
nextgen.url = builders.raw(`process.env.ZITADEL_URL ?? ${JSON.stringify(opts.server)}`);
|
|
1525
|
+
changed = true;
|
|
1526
|
+
}
|
|
1527
|
+
if (nextgen.loginPath === void 0) {
|
|
1528
|
+
nextgen.loginPath = "/login";
|
|
1529
|
+
changed = true;
|
|
1530
|
+
}
|
|
1531
|
+
if (nextgen.protectedRoutes === void 0) {
|
|
1532
|
+
nextgen.protectedRoutes = ["/profile"];
|
|
1533
|
+
changed = true;
|
|
1534
|
+
}
|
|
1535
|
+
const runtimeConfig = ensureEditableObject(config, "runtimeConfig");
|
|
1536
|
+
if (runtimeConfig.zitadelUrl === void 0) {
|
|
1537
|
+
runtimeConfig.zitadelUrl = builders.raw(`process.env.ZITADEL_URL ?? ${JSON.stringify(opts.server)}`);
|
|
1538
|
+
changed = true;
|
|
1539
|
+
}
|
|
1540
|
+
const publicConfig = ensureEditableObject(runtimeConfig, "public");
|
|
1541
|
+
if (publicConfig.nextgenProxyPath === void 0) {
|
|
1542
|
+
publicConfig.nextgenProxyPath = PROXY_PATH;
|
|
1543
|
+
changed = true;
|
|
1544
|
+
}
|
|
1545
|
+
if (publicConfig.zitadelProjectId === void 0) {
|
|
1546
|
+
publicConfig.zitadelProjectId = builders.raw(`process.env.NUXT_PUBLIC_ZITADEL_PROJECT_ID ?? ${JSON.stringify(opts.projectId)}`);
|
|
1547
|
+
changed = true;
|
|
1548
|
+
}
|
|
1549
|
+
const build = ensureEditableObject(config, "build");
|
|
1550
|
+
for (const dep of [
|
|
1551
|
+
"@zitadel/api",
|
|
1552
|
+
"@zitadel/components",
|
|
1553
|
+
"@zitadel/shared-component-styles",
|
|
1554
|
+
"@zitadel/design-tokens"
|
|
1555
|
+
]) if (ensureArrayItem(build, "transpile", dep)) changed = true;
|
|
1556
|
+
const compilerOptions = ensureEditableObject(ensureEditableObject(config, "vue"), "compilerOptions");
|
|
1557
|
+
if (compilerOptions.isCustomElement === void 0) {
|
|
1558
|
+
compilerOptions.isCustomElement = builders.raw(`(tag) => tag.startsWith("zitadel-")`);
|
|
1559
|
+
changed = true;
|
|
1560
|
+
}
|
|
1561
|
+
if (!changed && source !== void 0) return source;
|
|
1562
|
+
const code = generateCode(mod).code;
|
|
1563
|
+
return code.endsWith("\n") ? code : `${code}\n`;
|
|
1564
|
+
};
|
|
1565
|
+
}
|
|
1566
|
+
//#endregion
|
|
1567
|
+
//#region src/lib/orca/patchers/rule/nuxt/templates.ts
|
|
1568
|
+
const MAIN_STYLE = "min-height: 100vh; display: flex; align-items: center; justify-content: center; background: #f3f4f6";
|
|
1569
|
+
/** `app.vue` — renders the page router. Marker in an HTML comment. */
|
|
1570
|
+
function appVueTemplate() {
|
|
1571
|
+
return `<!-- ${MANAGED_MARKER} -->
|
|
1572
|
+
<template>
|
|
1573
|
+
<NuxtPage />
|
|
1574
|
+
</template>
|
|
1575
|
+
|
|
1576
|
+
<style>
|
|
1577
|
+
body {
|
|
1578
|
+
margin: 0;
|
|
1579
|
+
font-family: sans-serif;
|
|
1580
|
+
}
|
|
1581
|
+
</style>
|
|
1582
|
+
`;
|
|
1583
|
+
}
|
|
1584
|
+
/** A login/register page rendering `<zitadel-login>` inside `<ClientOnly>`. */
|
|
1585
|
+
function authPage(purpose) {
|
|
1586
|
+
return `<script setup lang="ts">
|
|
1587
|
+
${MANAGED_MARKER}
|
|
1588
|
+
import { useZitadelProject } from "@zitadel/sdk-nuxt";
|
|
1589
|
+
|
|
1590
|
+
const project = useZitadelProject();
|
|
1591
|
+
<\/script>
|
|
1592
|
+
|
|
1593
|
+
<template>
|
|
1594
|
+
<main style="${MAIN_STYLE}">
|
|
1595
|
+
<ClientOnly>
|
|
1596
|
+
<zitadel-login
|
|
1597
|
+
:project="project"${purpose === "register" ? "\n purpose=\"register\"" : ""}
|
|
1598
|
+
post-sign-in-url="/profile"
|
|
1599
|
+
/>
|
|
1600
|
+
</ClientOnly>
|
|
1601
|
+
</main>
|
|
1602
|
+
</template>
|
|
1603
|
+
`;
|
|
1604
|
+
}
|
|
1605
|
+
function loginPageTemplate() {
|
|
1606
|
+
return authPage("login");
|
|
1607
|
+
}
|
|
1608
|
+
function registerPageTemplate() {
|
|
1609
|
+
return authPage("register");
|
|
1610
|
+
}
|
|
1611
|
+
/** `pages/profile.vue` — the signed-in view with the logout widget. */
|
|
1612
|
+
function profilePageTemplate() {
|
|
1613
|
+
return `<script setup lang="ts">
|
|
1614
|
+
${MANAGED_MARKER}
|
|
1615
|
+
import { useZitadelProject } from "@zitadel/sdk-nuxt";
|
|
1616
|
+
|
|
1617
|
+
const project = useZitadelProject();
|
|
1618
|
+
<\/script>
|
|
1619
|
+
|
|
1620
|
+
<template>
|
|
1621
|
+
<main style="padding: 24px">
|
|
1622
|
+
<h1>Signed in (Nuxt)</h1>
|
|
1623
|
+
<ClientOnly>
|
|
1624
|
+
<zitadel-logout :project="project" post-sign-out-url="/login" />
|
|
1625
|
+
</ClientOnly>
|
|
1626
|
+
</main>
|
|
1627
|
+
</template>
|
|
1628
|
+
`;
|
|
1629
|
+
}
|
|
1630
|
+
/** `plugins/zitadel-components.client.ts` — register the Lit elements client-side. */
|
|
1631
|
+
function componentsPluginTemplate() {
|
|
1632
|
+
return `${MANAGED_MARKER}
|
|
1633
|
+
// Register Lit custom elements on the client only. Importing @zitadel/components
|
|
1634
|
+
// from a page <script setup> would run during SSR and break the widgets.
|
|
1635
|
+
import "@zitadel/components";
|
|
1636
|
+
|
|
1637
|
+
export default defineNuxtPlugin(() => {});
|
|
1638
|
+
`;
|
|
1639
|
+
}
|
|
1640
|
+
/** `plugins/auth.server.ts` — seed the client auth state from the server context. */
|
|
1641
|
+
function authPluginTemplate() {
|
|
1642
|
+
return `${MANAGED_MARKER}
|
|
1643
|
+
import { defineNuxtPlugin, useRequestEvent, useState } from "#imports";
|
|
1644
|
+
import type { ClientAuthResult } from "@zitadel/sdk-nuxt";
|
|
1645
|
+
|
|
1646
|
+
export default defineNuxtPlugin(() => {
|
|
1647
|
+
const event = useRequestEvent();
|
|
1648
|
+
const auth = event?.context.nextgenAuth ?? {
|
|
1649
|
+
isAuthenticated: false as const,
|
|
1650
|
+
session: null,
|
|
1651
|
+
};
|
|
1652
|
+
|
|
1653
|
+
// Strip the raw JWT before seeding useState — it must not appear in the SSR
|
|
1654
|
+
// payload where client-side scripts could read it.
|
|
1655
|
+
const clientAuth: ClientAuthResult = auth.isAuthenticated
|
|
1656
|
+
? {
|
|
1657
|
+
isAuthenticated: true,
|
|
1658
|
+
session: {
|
|
1659
|
+
userId: auth.session.userId,
|
|
1660
|
+
email: auth.session.email,
|
|
1661
|
+
name: auth.session.name,
|
|
1662
|
+
},
|
|
1663
|
+
}
|
|
1664
|
+
: { isAuthenticated: false, session: null };
|
|
1665
|
+
|
|
1666
|
+
useState<ClientAuthResult>("nextgen-auth", () => clientAuth);
|
|
1667
|
+
});
|
|
1668
|
+
`;
|
|
1669
|
+
}
|
|
1670
|
+
//#endregion
|
|
1671
|
+
//#region src/lib/orca/patchers/rule/nuxt/index.ts
|
|
1672
|
+
const SDK_DEPENDENCY$2 = "@zitadel/sdk-nuxt";
|
|
1673
|
+
const NUXT_CONFIG_PATHS = configCandidates("nuxt.config");
|
|
1674
|
+
/**
|
|
1675
|
+
* Rule-based patcher for a Nuxt app. Like Next.js, Nuxt proxies the backend and
|
|
1676
|
+
* verifies the session through server middleware — here the `@zitadel/sdk-nuxt`
|
|
1677
|
+
* module, registered via a non-destructive `nuxt.config.*` edit. Contributes
|
|
1678
|
+
* the login/register/profile pages (the raw `<zitadel-login>`/`<zitadel-logout>`
|
|
1679
|
+
* elements), the client/server plugins, the `app.vue` router, and the SDK dep.
|
|
1680
|
+
*/
|
|
1681
|
+
var NuxtPatcher = class extends AbstractRulePatcher {
|
|
1682
|
+
canPatch(framework) {
|
|
1683
|
+
return framework === "nuxt";
|
|
1684
|
+
}
|
|
1685
|
+
routeOps(ctx) {
|
|
1686
|
+
const src = (rel) => join(ctx.framework.appDir, rel);
|
|
1687
|
+
return [
|
|
1688
|
+
{
|
|
1689
|
+
kind: "write",
|
|
1690
|
+
path: src("app.vue"),
|
|
1691
|
+
contents: appVueTemplate()
|
|
1692
|
+
},
|
|
1693
|
+
{
|
|
1694
|
+
kind: "write",
|
|
1695
|
+
path: src("pages/login.vue"),
|
|
1696
|
+
contents: loginPageTemplate()
|
|
1697
|
+
},
|
|
1698
|
+
{
|
|
1699
|
+
kind: "write",
|
|
1700
|
+
path: src("pages/register.vue"),
|
|
1701
|
+
contents: registerPageTemplate()
|
|
1702
|
+
},
|
|
1703
|
+
{
|
|
1704
|
+
kind: "write",
|
|
1705
|
+
path: src("pages/profile.vue"),
|
|
1706
|
+
contents: profilePageTemplate()
|
|
1707
|
+
},
|
|
1708
|
+
{
|
|
1709
|
+
kind: "write",
|
|
1710
|
+
path: src("plugins/zitadel-components.client.ts"),
|
|
1711
|
+
contents: componentsPluginTemplate()
|
|
1712
|
+
},
|
|
1713
|
+
{
|
|
1714
|
+
kind: "write",
|
|
1715
|
+
path: src("plugins/auth.server.ts"),
|
|
1716
|
+
contents: authPluginTemplate()
|
|
1717
|
+
},
|
|
1718
|
+
{
|
|
1719
|
+
kind: "edit",
|
|
1720
|
+
path: [...NUXT_CONFIG_PATHS],
|
|
1721
|
+
edit: nuxtConfigEdit({
|
|
1722
|
+
projectId: ctx.project.id,
|
|
1723
|
+
server: ctx.server
|
|
1724
|
+
})
|
|
1725
|
+
},
|
|
1726
|
+
{
|
|
1727
|
+
kind: "merge-env",
|
|
1728
|
+
path: ".env.example",
|
|
1729
|
+
entries: { NUXT_PUBLIC_ZITADEL_PROJECT_ID: "" }
|
|
1730
|
+
},
|
|
1731
|
+
{
|
|
1732
|
+
kind: "merge-env",
|
|
1733
|
+
path: ".env.local",
|
|
1734
|
+
entries: { NUXT_PUBLIC_ZITADEL_PROJECT_ID: ctx.project.id }
|
|
1735
|
+
},
|
|
1736
|
+
{
|
|
1737
|
+
kind: "add-dep",
|
|
1738
|
+
name: SDK_DEPENDENCY$2,
|
|
1739
|
+
version: npmDistTagForCliVersion(ctx.cliVersion)
|
|
1740
|
+
}
|
|
1741
|
+
];
|
|
1742
|
+
}
|
|
1743
|
+
routeFiles(view) {
|
|
1744
|
+
const src = (rel) => join(view.framework.appDir, rel);
|
|
1745
|
+
return [
|
|
1746
|
+
src("app.vue"),
|
|
1747
|
+
src("pages/login.vue"),
|
|
1748
|
+
src("pages/register.vue"),
|
|
1749
|
+
src("pages/profile.vue"),
|
|
1750
|
+
src("plugins/zitadel-components.client.ts"),
|
|
1751
|
+
src("plugins/auth.server.ts")
|
|
1752
|
+
];
|
|
1753
|
+
}
|
|
1754
|
+
routeDeps(_view) {
|
|
1755
|
+
return [SDK_DEPENDENCY$2];
|
|
1756
|
+
}
|
|
1757
|
+
routeConfigEdits(_view) {
|
|
1758
|
+
return ["nuxt.config.*"];
|
|
1759
|
+
}
|
|
1760
|
+
summary(_ctx) {
|
|
1761
|
+
return {
|
|
1762
|
+
title: "Nuxt integration",
|
|
1763
|
+
detail: "Wrote login/register/profile pages + plugins and registered @zitadel/sdk-nuxt in nuxt.config.*."
|
|
1764
|
+
};
|
|
1765
|
+
}
|
|
1766
|
+
};
|
|
1767
|
+
//#endregion
|
|
1768
|
+
//#region src/lib/orca/patchers/rule/vite-support.ts
|
|
1769
|
+
/**
|
|
1770
|
+
* Shared Vite dev-server proxy merged into the project's Vite config for the SPA
|
|
1771
|
+
* frameworks (React, Vue). It forwards same-origin `/__nextgen/*` calls to the
|
|
1772
|
+
* backend, strips the prefix, and attaches the project's `sk_<project_id>`
|
|
1773
|
+
* bearer (read from `ZITADEL_PROJECT_ID` in the env) to every proxied request.
|
|
1774
|
+
*/
|
|
1775
|
+
function proxyEntryCode(server) {
|
|
1776
|
+
return `{
|
|
1777
|
+
target: ${JSON.stringify(server)},
|
|
1778
|
+
changeOrigin: false,
|
|
1779
|
+
rewrite: (path) => path.replace(/^\\${PROXY_PATH}/, "").replace(/^(?!\\/)/, "/"),
|
|
1780
|
+
configure: (proxy) => {
|
|
1781
|
+
const projectId = loadEnv("development", process.cwd(), "ZITADEL_").ZITADEL_PROJECT_ID;
|
|
1782
|
+
if (!projectId) {
|
|
1783
|
+
throw new Error("ZITADEL_PROJECT_ID is not set; add it to .env.local (zitadel setup writes it).");
|
|
1784
|
+
}
|
|
1785
|
+
const bearer = \`Bearer sk_\${projectId}\`;
|
|
1786
|
+
proxy.on("proxyReq", (proxyReq) => {
|
|
1787
|
+
proxyReq.setHeader("authorization", bearer);
|
|
1788
|
+
});
|
|
1789
|
+
},
|
|
1790
|
+
}`;
|
|
1791
|
+
}
|
|
1792
|
+
/** The imports that the injected proxy entry depends on. */
|
|
1793
|
+
const PROXY_IMPORTS = [{
|
|
1794
|
+
from: "vite",
|
|
1795
|
+
imported: "loadEnv",
|
|
1796
|
+
local: "loadEnv"
|
|
1797
|
+
}];
|
|
1798
|
+
/**
|
|
1799
|
+
* Builds the pure `edit` transform the file-writer applies to the project's Vite
|
|
1800
|
+
* config (`vite.config.*`): a non-destructive magicast merge that adds the
|
|
1801
|
+
* `/__nextgen` proxy and sets `server.port`/`strictPort` when they are unset,
|
|
1802
|
+
* preserving the user's plugins, options, and formatting. Leaves `server.host`
|
|
1803
|
+
* alone so the user can still opt into network binding (`--host`/`host: true`);
|
|
1804
|
+
* the issuer/origin requirement is about the port, not the bind host. Idempotent
|
|
1805
|
+
* — entries already present are left as-is. Throws `E_VALIDATION` when the file
|
|
1806
|
+
* is absent or the config object cannot be reached (function-built/exotic
|
|
1807
|
+
* configs), with a hint to add the block manually.
|
|
1808
|
+
*/
|
|
1809
|
+
function viteProxyEdit(devPort, server) {
|
|
1810
|
+
return (source) => {
|
|
1811
|
+
const label = "the Vite config (vite.config.*)";
|
|
1812
|
+
const mod = parseConfigModule(source, label);
|
|
1813
|
+
const config = resolveDefaultExportObject(mod, label);
|
|
1814
|
+
let changed = false;
|
|
1815
|
+
const serverConfig = ensureEditableObject(config, "server");
|
|
1816
|
+
if (serverConfig.port === void 0) {
|
|
1817
|
+
serverConfig.port = devPort;
|
|
1818
|
+
changed = true;
|
|
1819
|
+
}
|
|
1820
|
+
if (serverConfig.strictPort === void 0) {
|
|
1821
|
+
serverConfig.strictPort = true;
|
|
1822
|
+
changed = true;
|
|
1823
|
+
}
|
|
1824
|
+
const proxyConfig = ensureEditableObject(serverConfig, "proxy");
|
|
1825
|
+
if (proxyConfig["/__nextgen"] === void 0) {
|
|
1826
|
+
proxyConfig[PROXY_PATH] = builders.raw(proxyEntryCode(server));
|
|
1827
|
+
changed = true;
|
|
1828
|
+
}
|
|
1829
|
+
for (const imp of PROXY_IMPORTS) if (!importIsPresent(mod, imp.local, imp.from)) {
|
|
1830
|
+
mod.imports.$add({ ...imp });
|
|
1831
|
+
changed = true;
|
|
1832
|
+
}
|
|
1833
|
+
if (!changed && source !== void 0) return source;
|
|
1834
|
+
const code = generateCode(mod).code;
|
|
1835
|
+
return code.endsWith("\n") ? code : `${code}\n`;
|
|
1836
|
+
};
|
|
1837
|
+
}
|
|
1838
|
+
/**
|
|
1839
|
+
* Candidate Vite config filenames, in resolution priority. The patcher hands
|
|
1840
|
+
* this list to the generic `edit` file-op, which patches the first one that
|
|
1841
|
+
* exists — so any project layout (`vite.config.ts`, `.mts`, `.js`, …) is covered.
|
|
1842
|
+
*/
|
|
1843
|
+
const VITE_CONFIG_PATHS = configCandidates("vite.config");
|
|
1844
|
+
/** Builds the shared Vite-config proxy {@link FileOp} for a {@link ViteSupport} patcher. */
|
|
1845
|
+
function buildViteProxyOp(devPort, server) {
|
|
1846
|
+
return {
|
|
1847
|
+
kind: "edit",
|
|
1848
|
+
path: [...VITE_CONFIG_PATHS],
|
|
1849
|
+
edit: viteProxyEdit(devPort, server)
|
|
1850
|
+
};
|
|
1851
|
+
}
|
|
1852
|
+
//#endregion
|
|
1853
|
+
//#region src/lib/orca/patchers/rule/react/templates.ts
|
|
1854
|
+
/**
|
|
1855
|
+
* The managed `src/App.tsx`: a minimal path-based router that renders the
|
|
1856
|
+
* `@zitadel/sdk-react` widgets — login at `/login` (and `/`), register at
|
|
1857
|
+
* `/register`, and the logout widget at `/profile`. The project id comes from
|
|
1858
|
+
* `VITE_ZITADEL_PROJECT_ID` (Vite only exposes `VITE_`-prefixed env to the
|
|
1859
|
+
* client). No secret reaches the browser: the dev proxy in `vite.config.*`
|
|
1860
|
+
* attaches the `sk_<project_id>` bearer (derived from the public project id)
|
|
1861
|
+
* server-side.
|
|
1862
|
+
*/
|
|
1863
|
+
function appTemplate$1() {
|
|
1864
|
+
return `${MANAGED_MARKER}
|
|
1865
|
+
import { ZitadelLogin, ZitadelLogout, configureZitadel } from "@zitadel/sdk-react";
|
|
1866
|
+
|
|
1867
|
+
const project = configureZitadel({
|
|
1868
|
+
projectId: import.meta.env.VITE_ZITADEL_PROJECT_ID,
|
|
1869
|
+
proxyPath: "${PROXY_PATH}",
|
|
1870
|
+
});
|
|
1871
|
+
|
|
1872
|
+
export default function App() {
|
|
1873
|
+
const path = window.location.pathname;
|
|
1874
|
+
|
|
1875
|
+
if (path.startsWith("/profile")) {
|
|
1876
|
+
return <ZitadelLogout project={project} postSignOutUrl="/login" />;
|
|
1877
|
+
}
|
|
1878
|
+
if (path.startsWith("/register")) {
|
|
1879
|
+
return <ZitadelLogin project={project} purpose="register" postSignInUrl="/profile" />;
|
|
1880
|
+
}
|
|
1881
|
+
return <ZitadelLogin project={project} purpose="login" postSignInUrl="/profile" />;
|
|
1882
|
+
}
|
|
1883
|
+
`;
|
|
1884
|
+
}
|
|
1885
|
+
//#endregion
|
|
1886
|
+
//#region src/lib/orca/patchers/rule/react/index.ts
|
|
1887
|
+
const SDK_DEPENDENCY$1 = "@zitadel/sdk-react";
|
|
1888
|
+
/**
|
|
1889
|
+
* Rule-based patcher for a Vite + React single-page app. Inherits the shared
|
|
1890
|
+
* `.zitadel/` base files from {@link AbstractRulePatcher} and contributes the
|
|
1891
|
+
* managed `src/App.tsx` auth entry, a non-destructive `vite.config.*` merge
|
|
1892
|
+
* that adds the `/__nextgen` dev proxy (attaching the `sk_<project_id>` bearer
|
|
1893
|
+
* from `ZITADEL_PROJECT_ID` to every proxied request), the `VITE_`-prefixed
|
|
1894
|
+
* project id, and the SDK dep.
|
|
1895
|
+
*
|
|
1896
|
+
* Unlike Next.js — whose middleware runs the proxy and token exchange
|
|
1897
|
+
* server-side — a SPA has no server, so the dev proxy stands in for
|
|
1898
|
+
* `@zitadel/edge-proxy` locally. Production deployments still need that proxy.
|
|
1899
|
+
*/
|
|
1900
|
+
var ReactPatcher = class extends AbstractRulePatcher {
|
|
1901
|
+
canPatch(framework) {
|
|
1902
|
+
return framework === "react";
|
|
1903
|
+
}
|
|
1904
|
+
viteProxyOp(devPort, server) {
|
|
1905
|
+
return buildViteProxyOp(devPort, server);
|
|
1906
|
+
}
|
|
1907
|
+
routeOps(ctx) {
|
|
1908
|
+
return [
|
|
1909
|
+
{
|
|
1910
|
+
kind: "write",
|
|
1911
|
+
path: "src/App.tsx",
|
|
1912
|
+
contents: appTemplate$1()
|
|
1913
|
+
},
|
|
1914
|
+
this.viteProxyOp(ctx.framework.devPort, ctx.server),
|
|
1915
|
+
{
|
|
1916
|
+
kind: "merge-env",
|
|
1917
|
+
path: ".env.example",
|
|
1918
|
+
entries: { VITE_ZITADEL_PROJECT_ID: "" }
|
|
1919
|
+
},
|
|
1920
|
+
{
|
|
1921
|
+
kind: "merge-env",
|
|
1922
|
+
path: ".env.local",
|
|
1923
|
+
entries: { VITE_ZITADEL_PROJECT_ID: ctx.project.id }
|
|
1924
|
+
},
|
|
1925
|
+
{
|
|
1926
|
+
kind: "add-dep",
|
|
1927
|
+
name: SDK_DEPENDENCY$1,
|
|
1928
|
+
version: npmDistTagForCliVersion(ctx.cliVersion)
|
|
1929
|
+
}
|
|
1930
|
+
];
|
|
1931
|
+
}
|
|
1932
|
+
routeFiles(_view) {
|
|
1933
|
+
return ["src/App.tsx"];
|
|
1934
|
+
}
|
|
1935
|
+
routeDeps(_view) {
|
|
1936
|
+
return [SDK_DEPENDENCY$1];
|
|
1937
|
+
}
|
|
1938
|
+
routeConfigEdits(_view) {
|
|
1939
|
+
return ["vite.config.*"];
|
|
1940
|
+
}
|
|
1941
|
+
summary(_ctx) {
|
|
1942
|
+
return {
|
|
1943
|
+
title: "React (Vite) integration",
|
|
1944
|
+
detail: "Wrote src/App.tsx auth entry and merged the /__nextgen dev proxy into vite.config.*."
|
|
1945
|
+
};
|
|
1946
|
+
}
|
|
1947
|
+
};
|
|
1948
|
+
//#endregion
|
|
1949
|
+
//#region src/lib/orca/patchers/rule/vue/templates.ts
|
|
1950
|
+
/**
|
|
1951
|
+
* The managed `src/App.vue`: a minimal path-based router that renders the
|
|
1952
|
+
* `@zitadel/sdk-vue` widgets — login at `/login` (and `/`), register at
|
|
1953
|
+
* `/register`, and the logout widget at `/profile`. The managed marker lives in
|
|
1954
|
+
* the `<script setup>` block (a JS comment) so eject/doctor stay marker-aware.
|
|
1955
|
+
* The project id comes from `VITE_ZITADEL_PROJECT_ID`. No secret reaches the
|
|
1956
|
+
* browser: the dev proxy in `vite.config.*` attaches the `sk_<project_id>`
|
|
1957
|
+
* bearer (derived from the public project id) server-side.
|
|
1958
|
+
*/
|
|
1959
|
+
function appTemplate() {
|
|
1960
|
+
return `<script setup lang="ts">
|
|
1961
|
+
${MANAGED_MARKER}
|
|
1962
|
+
import { ZitadelLogin, ZitadelLogout, configureZitadel } from "@zitadel/sdk-vue";
|
|
1963
|
+
|
|
1964
|
+
const project = configureZitadel({
|
|
1965
|
+
projectId: import.meta.env.VITE_ZITADEL_PROJECT_ID,
|
|
1966
|
+
proxyPath: "${PROXY_PATH}",
|
|
1967
|
+
});
|
|
1968
|
+
|
|
1969
|
+
const path = window.location.pathname;
|
|
1970
|
+
<\/script>
|
|
1971
|
+
|
|
1972
|
+
<template>
|
|
1973
|
+
<ZitadelLogout
|
|
1974
|
+
v-if="path.startsWith('/profile')"
|
|
1975
|
+
:project="project"
|
|
1976
|
+
postSignOutUrl="/login"
|
|
1977
|
+
/>
|
|
1978
|
+
<ZitadelLogin
|
|
1979
|
+
v-else-if="path.startsWith('/register')"
|
|
1980
|
+
:project="project"
|
|
1981
|
+
purpose="register"
|
|
1982
|
+
postSignInUrl="/profile"
|
|
1983
|
+
/>
|
|
1984
|
+
<ZitadelLogin v-else :project="project" purpose="login" postSignInUrl="/profile" />
|
|
1985
|
+
</template>
|
|
1986
|
+
`;
|
|
1987
|
+
}
|
|
1988
|
+
//#endregion
|
|
1989
|
+
//#region src/lib/orca/patchers/rule/vue/index.ts
|
|
1990
|
+
const SDK_DEPENDENCY = "@zitadel/sdk-vue";
|
|
1991
|
+
/**
|
|
1992
|
+
* Rule-based patcher for a Vite + Vue single-page app. Inherits the shared
|
|
1993
|
+
* `.zitadel/` base files from {@link AbstractRulePatcher} and contributes the
|
|
1994
|
+
* managed `src/App.vue` auth entry, a non-destructive `vite.config.*` merge
|
|
1995
|
+
* that adds the `/__nextgen` dev proxy (attaching the `sk_<project_id>` bearer
|
|
1996
|
+
* from `ZITADEL_PROJECT_ID` to every proxied request), the `VITE_`-prefixed
|
|
1997
|
+
* project id, and the SDK dep.
|
|
1998
|
+
*/
|
|
1999
|
+
var VuePatcher = class extends AbstractRulePatcher {
|
|
2000
|
+
canPatch(framework) {
|
|
2001
|
+
return framework === "vue";
|
|
2002
|
+
}
|
|
2003
|
+
viteProxyOp(devPort, server) {
|
|
2004
|
+
return buildViteProxyOp(devPort, server);
|
|
2005
|
+
}
|
|
2006
|
+
routeOps(ctx) {
|
|
2007
|
+
return [
|
|
2008
|
+
{
|
|
2009
|
+
kind: "write",
|
|
2010
|
+
path: "src/App.vue",
|
|
2011
|
+
contents: appTemplate()
|
|
2012
|
+
},
|
|
2013
|
+
this.viteProxyOp(ctx.framework.devPort, ctx.server),
|
|
2014
|
+
{
|
|
2015
|
+
kind: "merge-env",
|
|
2016
|
+
path: ".env.example",
|
|
2017
|
+
entries: { VITE_ZITADEL_PROJECT_ID: "" }
|
|
2018
|
+
},
|
|
2019
|
+
{
|
|
2020
|
+
kind: "merge-env",
|
|
2021
|
+
path: ".env.local",
|
|
2022
|
+
entries: { VITE_ZITADEL_PROJECT_ID: ctx.project.id }
|
|
2023
|
+
},
|
|
2024
|
+
{
|
|
2025
|
+
kind: "add-dep",
|
|
2026
|
+
name: SDK_DEPENDENCY,
|
|
2027
|
+
version: npmDistTagForCliVersion(ctx.cliVersion)
|
|
2028
|
+
}
|
|
2029
|
+
];
|
|
2030
|
+
}
|
|
2031
|
+
routeFiles(_view) {
|
|
2032
|
+
return ["src/App.vue"];
|
|
2033
|
+
}
|
|
2034
|
+
routeDeps(_view) {
|
|
2035
|
+
return [SDK_DEPENDENCY];
|
|
2036
|
+
}
|
|
2037
|
+
routeConfigEdits(_view) {
|
|
2038
|
+
return ["vite.config.*"];
|
|
2039
|
+
}
|
|
2040
|
+
summary(_ctx) {
|
|
2041
|
+
return {
|
|
2042
|
+
title: "Vue (Vite) integration",
|
|
2043
|
+
detail: "Wrote src/App.vue auth entry and merged the /__nextgen dev proxy into vite.config.*."
|
|
2044
|
+
};
|
|
2045
|
+
}
|
|
2046
|
+
};
|
|
2047
|
+
//#endregion
|
|
2048
|
+
//#region src/lib/orca/patchers/index.ts
|
|
2049
|
+
/**
|
|
2050
|
+
* Active patchers, in priority order; the first whose `canPatch` matches wins.
|
|
2051
|
+
*
|
|
2052
|
+
* Patchers are grouped by family under subdirectories: `rule/` holds the
|
|
2053
|
+
* deterministic, template-driven patchers (extending
|
|
2054
|
+
* {@link import("./rule/base").AbstractRulePatcher}). A future LLM-driven
|
|
2055
|
+
* family lives under `llm/` and registers its concrete patchers here — no
|
|
2056
|
+
* orchestrator or command changes needed. Only Next.js is supported today.
|
|
2057
|
+
*/
|
|
2058
|
+
const patchers = [
|
|
2059
|
+
new NextPatcher(),
|
|
2060
|
+
new NuxtPatcher(),
|
|
2061
|
+
new ReactPatcher(),
|
|
2062
|
+
new VuePatcher(),
|
|
2063
|
+
new AngularPatcher()
|
|
2064
|
+
];
|
|
2065
|
+
//#endregion
|
|
2066
|
+
//#region src/lib/orca/scaffolders/cli.ts
|
|
2067
|
+
/**
|
|
2068
|
+
* Base for scaffolders that delegate to an external CLI (e.g. create-next-app).
|
|
2069
|
+
* Subclasses implement {@link scaffold} and call {@link runCommand}.
|
|
2070
|
+
*/
|
|
2071
|
+
var AbstractCLIScaffolder = class {
|
|
2072
|
+
/** True when the requested framework is in {@link supportedFrameworks}. */
|
|
2073
|
+
canScaffold(framework) {
|
|
2074
|
+
return this.supportedFrameworks.includes(framework);
|
|
2075
|
+
}
|
|
2076
|
+
/**
|
|
2077
|
+
* Runs an external command in `cwd`, throwing a typed {@link ZitadelError} on
|
|
2078
|
+
* failure so the cause surfaces as a categorized CLI error. Distinguishes
|
|
2079
|
+
* "binary not on PATH" (`ENOENT` from the spawn itself) from "binary ran but
|
|
2080
|
+
* exited non-zero" — the former previously got masked as a generic
|
|
2081
|
+
* `exited with status 1`, leaving users to guess. Tests stub
|
|
2082
|
+
* `node:child_process` to assert the command without spawning.
|
|
2083
|
+
*/
|
|
2084
|
+
runCommand(command, args, cwd) {
|
|
2085
|
+
const result = spawnSync(command, [...args], {
|
|
2086
|
+
cwd,
|
|
2087
|
+
encoding: "utf8"
|
|
2088
|
+
});
|
|
2089
|
+
if (result.error) {
|
|
2090
|
+
const err = result.error;
|
|
2091
|
+
const notFound = err.code === "ENOENT";
|
|
2092
|
+
throw new ZitadelError("E_VALIDATION", notFound ? `Command not found: ${command}` : `Failed to spawn "${command}": ${err.message}`, {
|
|
2093
|
+
hint: notFound ? `Ensure '${command}' is installed and on PATH.` : void 0,
|
|
2094
|
+
details: {
|
|
2095
|
+
command,
|
|
2096
|
+
args: [...args],
|
|
2097
|
+
code: err.code
|
|
2098
|
+
}
|
|
2099
|
+
});
|
|
2100
|
+
}
|
|
2101
|
+
const status = result.status ?? 1;
|
|
2102
|
+
if (status !== 0) {
|
|
2103
|
+
const stdout = String(result.stdout ?? "");
|
|
2104
|
+
const stderr = String(result.stderr ?? "");
|
|
2105
|
+
const output = truncateCommandOutput([stderr, stdout].filter(Boolean).join("\n").trim());
|
|
2106
|
+
throw new ZitadelError("E_VALIDATION", `Command "${command} ${args.join(" ")}" exited with status ${String(status)}`, {
|
|
2107
|
+
hint: output ? `Command output:\n${output}` : "Run the command directly for more detail.",
|
|
2108
|
+
details: {
|
|
2109
|
+
command,
|
|
2110
|
+
args: [...args],
|
|
2111
|
+
cwd,
|
|
2112
|
+
stdout,
|
|
2113
|
+
stderr
|
|
2114
|
+
}
|
|
2115
|
+
});
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
};
|
|
2119
|
+
function truncateCommandOutput(output) {
|
|
2120
|
+
const limit = 4e3;
|
|
2121
|
+
if (output.length <= limit) return output;
|
|
2122
|
+
return `${output.slice(0, limit)}\n... output truncated ...`;
|
|
2123
|
+
}
|
|
2124
|
+
//#endregion
|
|
2125
|
+
//#region src/lib/orca/scaffolders/angular.ts
|
|
2126
|
+
/**
|
|
2127
|
+
* Derives a valid Angular project name from the target directory. `ng new`
|
|
2128
|
+
* validates the name against `^[a-zA-Z0-9-~][a-zA-Z0-9-._~]*$` and rejects `.`,
|
|
2129
|
+
* so we slugify the directory's basename (lowercase, non-alphanumerics → `-`)
|
|
2130
|
+
* and guarantee a leading letter by prefixing `app-` when the slug does not
|
|
2131
|
+
* start with one (`app-zitadel` when the basename slugifies to nothing).
|
|
2132
|
+
*/
|
|
2133
|
+
function angularProjectName(cwd) {
|
|
2134
|
+
const slug = basename(cwd).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
2135
|
+
return /^[a-z]/.test(slug) ? slug : `app-${slug || "zitadel"}`;
|
|
2136
|
+
}
|
|
2137
|
+
/**
|
|
2138
|
+
* Scaffolds a new Angular app with the Angular CLI, then removes the starter
|
|
2139
|
+
* `app.ts`/`app.html` root component (and its now-unreferenced `app.css`) so the
|
|
2140
|
+
* patcher can write the managed ones without colliding with boilerplate. The
|
|
2141
|
+
* managed component uses only `templateUrl`, so `app.css` would otherwise be a
|
|
2142
|
+
* dangling file eject never cleans up. Unlike `create-vite`/`nuxi`, `ng new`
|
|
2143
|
+
* needs a real project name plus `--directory .` to populate the current dir.
|
|
2144
|
+
* Requires a Node version Angular supports (^22.22.3 || ^24.15.0 || >=26).
|
|
2145
|
+
*/
|
|
2146
|
+
var AngularScaffolder = class extends AbstractCLIScaffolder {
|
|
2147
|
+
displayName = "Angular";
|
|
2148
|
+
supportedFrameworks = ["angular"];
|
|
2149
|
+
async scaffold(cwd, _framework) {
|
|
2150
|
+
this.runCommand("npx", [
|
|
2151
|
+
"-y",
|
|
2152
|
+
"@angular/cli@latest",
|
|
2153
|
+
"new",
|
|
2154
|
+
angularProjectName(cwd),
|
|
2155
|
+
"--directory",
|
|
2156
|
+
".",
|
|
2157
|
+
"--defaults",
|
|
2158
|
+
"--style=css",
|
|
2159
|
+
"--ssr=false",
|
|
2160
|
+
"--skip-git"
|
|
2161
|
+
], cwd);
|
|
2162
|
+
await rm(join(cwd, "src/app/app.ts"), { force: true });
|
|
2163
|
+
await rm(join(cwd, "src/app/app.html"), { force: true });
|
|
2164
|
+
await rm(join(cwd, "src/app/app.css"), { force: true });
|
|
2165
|
+
}
|
|
2166
|
+
};
|
|
2167
|
+
//#endregion
|
|
2168
|
+
//#region src/lib/orca/scaffolders/next.ts
|
|
2169
|
+
const CREATE_NEXT_APP_VERSION = "16.2.4";
|
|
2170
|
+
/** Scaffolds a new Next.js App Router project with `create-next-app`. */
|
|
2171
|
+
var NextScaffolder = class extends AbstractCLIScaffolder {
|
|
2172
|
+
displayName = "Next.js";
|
|
2173
|
+
supportedFrameworks = ["next"];
|
|
2174
|
+
/**
|
|
2175
|
+
* Runs the pinned `create-next-app` version in `cwd`, creating a TypeScript
|
|
2176
|
+
* App Router project in place. `--yes` accepts all defaults so the command
|
|
2177
|
+
* runs unattended, and `--skip-install` leaves dependency installation to the
|
|
2178
|
+
* setup command's explicit next step after Zitadel patches package.json.
|
|
2179
|
+
*/
|
|
2180
|
+
async scaffold(cwd, _framework) {
|
|
2181
|
+
this.runCommand("npx", [
|
|
2182
|
+
"--yes",
|
|
2183
|
+
`create-next-app@${CREATE_NEXT_APP_VERSION}`,
|
|
2184
|
+
".",
|
|
2185
|
+
"--ts",
|
|
2186
|
+
"--app",
|
|
2187
|
+
"--use-npm",
|
|
2188
|
+
"--disable-git",
|
|
2189
|
+
"--yes",
|
|
2190
|
+
"--skip-install"
|
|
2191
|
+
], cwd);
|
|
2192
|
+
}
|
|
2193
|
+
};
|
|
2194
|
+
//#endregion
|
|
2195
|
+
//#region src/lib/orca/scaffolders/nuxt.ts
|
|
2196
|
+
/**
|
|
2197
|
+
* Scaffolds a new Nuxt app with `nuxi init`, then removes the starter `app.vue`
|
|
2198
|
+
* so the patcher can write the managed one without colliding with boilerplate.
|
|
2199
|
+
* Nuxt 4 (what `nuxi init` scaffolds today) puts it under `app/`; older Nuxt put
|
|
2200
|
+
* it at the root, so both are removed. `nuxt.config.ts` is left in place — the
|
|
2201
|
+
* patcher merges into it via an `edit`, which preserves whatever `nuxi` generated.
|
|
2202
|
+
*/
|
|
2203
|
+
var NuxtScaffolder = class extends AbstractCLIScaffolder {
|
|
2204
|
+
displayName = "Nuxt";
|
|
2205
|
+
supportedFrameworks = ["nuxt"];
|
|
2206
|
+
async scaffold(cwd, _framework) {
|
|
2207
|
+
this.runCommand("npx", [
|
|
2208
|
+
"-y",
|
|
2209
|
+
"nuxi@latest",
|
|
2210
|
+
"init",
|
|
2211
|
+
".",
|
|
2212
|
+
"--template",
|
|
2213
|
+
"minimal",
|
|
2214
|
+
"--packageManager",
|
|
2215
|
+
"npm",
|
|
2216
|
+
"--no-gitInit",
|
|
2217
|
+
"--force"
|
|
2218
|
+
], cwd);
|
|
2219
|
+
await rm(join(cwd, "app/app.vue"), { force: true });
|
|
2220
|
+
await rm(join(cwd, "app.vue"), { force: true });
|
|
2221
|
+
}
|
|
2222
|
+
};
|
|
2223
|
+
//#endregion
|
|
2224
|
+
//#region src/lib/orca/scaffolders/react.ts
|
|
2225
|
+
/**
|
|
2226
|
+
* Scaffolds a new Vite + React (TypeScript) single-page app with `create-vite`,
|
|
2227
|
+
* then removes the starter `App.tsx`/`App.css` demo so the patcher can write the
|
|
2228
|
+
* managed `src/App.tsx` without colliding with boilerplate. `index.css` and
|
|
2229
|
+
* `main.tsx` are left in place — the patched `App.tsx` keeps the same entry.
|
|
2230
|
+
*/
|
|
2231
|
+
var ReactScaffolder = class extends AbstractCLIScaffolder {
|
|
2232
|
+
displayName = "React (Vite)";
|
|
2233
|
+
supportedFrameworks = ["react"];
|
|
2234
|
+
async scaffold(cwd, _framework) {
|
|
2235
|
+
this.runCommand("npm", [
|
|
2236
|
+
"create",
|
|
2237
|
+
"vite@latest",
|
|
2238
|
+
".",
|
|
2239
|
+
"--",
|
|
2240
|
+
"--template",
|
|
2241
|
+
"react-ts"
|
|
2242
|
+
], cwd);
|
|
2243
|
+
await rm(join(cwd, "src/App.tsx"), { force: true });
|
|
2244
|
+
await rm(join(cwd, "src/App.css"), { force: true });
|
|
2245
|
+
}
|
|
2246
|
+
};
|
|
2247
|
+
//#endregion
|
|
2248
|
+
//#region src/lib/orca/scaffolders/vue.ts
|
|
2249
|
+
/**
|
|
2250
|
+
* Scaffolds a new Vite + Vue (TypeScript) single-page app with `create-vite`,
|
|
2251
|
+
* then removes the starter `App.vue`/`components/HelloWorld.vue` demo so the
|
|
2252
|
+
* patcher can write the managed `src/App.vue` without colliding with boilerplate.
|
|
2253
|
+
*/
|
|
2254
|
+
var VueScaffolder = class extends AbstractCLIScaffolder {
|
|
2255
|
+
displayName = "Vue (Vite)";
|
|
2256
|
+
supportedFrameworks = ["vue"];
|
|
2257
|
+
async scaffold(cwd, _framework) {
|
|
2258
|
+
this.runCommand("npm", [
|
|
2259
|
+
"create",
|
|
2260
|
+
"vite@latest",
|
|
2261
|
+
".",
|
|
2262
|
+
"--",
|
|
2263
|
+
"--template",
|
|
2264
|
+
"vue-ts"
|
|
2265
|
+
], cwd);
|
|
2266
|
+
await rm(join(cwd, "src/App.vue"), { force: true });
|
|
2267
|
+
await rm(join(cwd, "src/components/HelloWorld.vue"), { force: true });
|
|
2268
|
+
}
|
|
2269
|
+
};
|
|
2270
|
+
//#endregion
|
|
2271
|
+
//#region src/lib/orca/scaffolders/index.ts
|
|
2272
|
+
/**
|
|
2273
|
+
* Active scaffolders, in priority order. The framework picker derives its
|
|
2274
|
+
* choices from this list. Add a new framework by appending its scaffolder
|
|
2275
|
+
* here — no orchestrator changes needed.
|
|
2276
|
+
*/
|
|
2277
|
+
const scaffolders = [
|
|
2278
|
+
new NextScaffolder(),
|
|
2279
|
+
new NuxtScaffolder(),
|
|
2280
|
+
new ReactScaffolder(),
|
|
2281
|
+
new VueScaffolder(),
|
|
2282
|
+
new AngularScaffolder()
|
|
2283
|
+
];
|
|
2284
|
+
//#endregion
|
|
2285
|
+
//#region src/lib/orca/index.ts
|
|
2286
|
+
/**
|
|
2287
|
+
* Orchestrates the three per-framework strategies — detectors (recognise an
|
|
2288
|
+
* existing project and extract its facts), scaffolders (create a project), and
|
|
2289
|
+
* patchers (integrate Zitadel) — over their respective registries. It resolves
|
|
2290
|
+
* the right strategy for a framework and drives the detect/scaffold lifecycle;
|
|
2291
|
+
* how a patcher applies its work (file operations vs an LLM agent) stays
|
|
2292
|
+
* internal to that patcher. Registries are injected so tests can supply fakes.
|
|
2293
|
+
*/
|
|
2294
|
+
var Orca = class {
|
|
2295
|
+
constructor(detectors, scaffolders, patchers) {
|
|
2296
|
+
this.detectors = detectors;
|
|
2297
|
+
this.scaffolders = scaffolders;
|
|
2298
|
+
this.patchers = patchers;
|
|
2299
|
+
}
|
|
2300
|
+
/**
|
|
2301
|
+
* Detects the framework in `cwd` and extracts its {@link FrameworkFacts},
|
|
2302
|
+
* honouring an explicit `requested` framework. Throws
|
|
2303
|
+
* `E_FRAMEWORK_NOT_DETECTED` when nothing matches; a detector's
|
|
2304
|
+
* `E_UNSUPPORTED_PROJECT_SHAPE` (recognised but unsupported) propagates.
|
|
2305
|
+
*/
|
|
2306
|
+
async detect(cwd, requested) {
|
|
2307
|
+
const candidates = requested ? this.detectors.filter((detector) => detector.framework === requested) : this.detectors;
|
|
2308
|
+
if (requested && candidates.length === 0) throw new ZitadelError("E_FRAMEWORK_NOT_DETECTED", `Unsupported framework "${requested}"`, { hint: `Supported frameworks: ${this.frameworkIds().join(", ")}.` });
|
|
2309
|
+
for (const detector of candidates) {
|
|
2310
|
+
const facts = await detector.detect(cwd);
|
|
2311
|
+
if (facts) return facts;
|
|
2312
|
+
}
|
|
2313
|
+
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." });
|
|
2314
|
+
}
|
|
2315
|
+
/**
|
|
2316
|
+
* Non-throwing detection: returns `undefined` instead of raising for a
|
|
2317
|
+
* project that is absent, unrecognised, or recognised-but-unsupported, so
|
|
2318
|
+
* callers (e.g. `eject`) can probe and degrade gracefully.
|
|
2319
|
+
*/
|
|
2320
|
+
async tryDetect(cwd) {
|
|
2321
|
+
try {
|
|
2322
|
+
return await this.detect(cwd);
|
|
2323
|
+
} catch (error) {
|
|
2324
|
+
if (error instanceof ZitadelError && (error.code === "E_FRAMEWORK_NOT_DETECTED" || error.code === "E_UNSUPPORTED_PROJECT_SHAPE")) return;
|
|
2325
|
+
throw error;
|
|
2326
|
+
}
|
|
2327
|
+
}
|
|
2328
|
+
/** Whether `cwd` is safe for an in-place framework scaffold. */
|
|
2329
|
+
async isFreshScaffoldTarget(cwd) {
|
|
2330
|
+
return (await inspectScaffoldTarget(cwd)).scaffoldable;
|
|
2331
|
+
}
|
|
2332
|
+
/**
|
|
2333
|
+
* Creates a new `framework` project in `cwd`, then re-detects it to return
|
|
2334
|
+
* the resulting {@link FrameworkFacts}. Throws `E_CONFLICT` when the directory
|
|
2335
|
+
* already contains a project ("already scaffolded") and `E_VALIDATION` when no
|
|
2336
|
+
* scaffolder supports the framework.
|
|
2337
|
+
*/
|
|
2338
|
+
async scaffold(cwd, framework) {
|
|
2339
|
+
const target = await inspectScaffoldTarget(cwd);
|
|
2340
|
+
if (!target.scaffoldable) throw new ZitadelError("E_CONFLICT", `Cannot scaffold: ${cwd} is not empty`, {
|
|
2341
|
+
hint: target.reason ?? "Run setup in an empty directory, or run setup from an existing supported app project.",
|
|
2342
|
+
details: { entries: target.entries }
|
|
2343
|
+
});
|
|
2344
|
+
const stash = await stashFreshScaffoldArtifacts(cwd, target);
|
|
2345
|
+
try {
|
|
2346
|
+
await this.scaffolderFor(framework).scaffold(cwd, framework);
|
|
2347
|
+
} finally {
|
|
2348
|
+
await restoreFreshScaffoldArtifacts(cwd, stash);
|
|
2349
|
+
}
|
|
2350
|
+
return this.detect(cwd, framework);
|
|
2351
|
+
}
|
|
2352
|
+
/**
|
|
2353
|
+
* Resolves the scaffolder for a framework, throwing `E_VALIDATION` (with the
|
|
2354
|
+
* available list) when none matches.
|
|
2355
|
+
*/
|
|
2356
|
+
scaffolderFor(framework) {
|
|
2357
|
+
const scaffolder = this.scaffolders.find((candidate) => candidate.canScaffold(framework));
|
|
2358
|
+
if (!scaffolder) throw new ZitadelError("E_VALIDATION", `No scaffolder supports "${framework}"`, { hint: `Available frameworks: ${this.availableFrameworks().map((f) => f.id).join(", ")}.` });
|
|
2359
|
+
return scaffolder;
|
|
2360
|
+
}
|
|
2361
|
+
/**
|
|
2362
|
+
* Resolves the patcher for a framework, throwing `E_VALIDATION` when none
|
|
2363
|
+
* matches (e.g. a framework that can be scaffolded but not yet integrated).
|
|
2364
|
+
*/
|
|
2365
|
+
patcherFor(framework) {
|
|
2366
|
+
const patcher = this.patchers.find((candidate) => candidate.canPatch(framework));
|
|
2367
|
+
if (!patcher) throw new ZitadelError("E_VALIDATION", `No patcher supports "${framework}"`, { hint: "Zitadel integration currently supports Next.js." });
|
|
2368
|
+
return patcher;
|
|
2369
|
+
}
|
|
2370
|
+
/** The frameworks that can be scaffolded, derived from the scaffolder registry. */
|
|
2371
|
+
availableFrameworks() {
|
|
2372
|
+
return this.scaffolders.map((scaffolder) => ({
|
|
2373
|
+
id: scaffolder.supportedFrameworks[0] ?? scaffolder.displayName,
|
|
2374
|
+
displayName: scaffolder.displayName
|
|
2375
|
+
}));
|
|
2376
|
+
}
|
|
2377
|
+
frameworkIds() {
|
|
2378
|
+
return this.detectors.map((detector) => detector.framework);
|
|
2379
|
+
}
|
|
2380
|
+
};
|
|
2381
|
+
/** {@link Orca} wired with the default detector, scaffolder, and patcher registries. */
|
|
2382
|
+
function createOrca() {
|
|
2383
|
+
return new Orca(detectors, scaffolders, patchers);
|
|
2384
|
+
}
|
|
2385
|
+
async function inspectScaffoldTarget(cwd) {
|
|
2386
|
+
const entries = await readdir(cwd, { withFileTypes: true });
|
|
2387
|
+
const names = entries.map((entry) => entry.name).sort();
|
|
2388
|
+
let hasGitignore = false;
|
|
2389
|
+
let hasRuntimeOnlyZitadel = false;
|
|
2390
|
+
for (const entry of entries) {
|
|
2391
|
+
if (entry.name === ".gitignore") {
|
|
2392
|
+
if (!entry.isFile()) return {
|
|
2393
|
+
scaffoldable: false,
|
|
2394
|
+
hasGitignore: false,
|
|
2395
|
+
hasRuntimeOnlyZitadel: false,
|
|
2396
|
+
reason: ".gitignore exists but is not a file.",
|
|
2397
|
+
entries: names
|
|
2398
|
+
};
|
|
2399
|
+
hasGitignore = true;
|
|
2400
|
+
continue;
|
|
2401
|
+
}
|
|
2402
|
+
if (entry.name === ".zitadel") {
|
|
2403
|
+
if (!entry.isDirectory() || !await isRuntimeOnlyZitadelDir(join(cwd, ".zitadel"))) return {
|
|
2404
|
+
scaffoldable: false,
|
|
2405
|
+
hasGitignore,
|
|
2406
|
+
hasRuntimeOnlyZitadel: false,
|
|
2407
|
+
reason: ".zitadel contains project state. Move it aside or run setup from an empty app directory.",
|
|
2408
|
+
entries: names
|
|
2409
|
+
};
|
|
2410
|
+
hasRuntimeOnlyZitadel = true;
|
|
2411
|
+
continue;
|
|
2412
|
+
}
|
|
2413
|
+
return {
|
|
2414
|
+
scaffoldable: false,
|
|
2415
|
+
hasGitignore,
|
|
2416
|
+
hasRuntimeOnlyZitadel: false,
|
|
2417
|
+
reason: `Directory contains ${entry.name}. Run setup from an empty directory to scaffold a new app.`,
|
|
2418
|
+
entries: names
|
|
2419
|
+
};
|
|
2420
|
+
}
|
|
2421
|
+
return {
|
|
2422
|
+
scaffoldable: true,
|
|
2423
|
+
hasGitignore,
|
|
2424
|
+
hasRuntimeOnlyZitadel,
|
|
2425
|
+
entries: names
|
|
2426
|
+
};
|
|
2427
|
+
}
|
|
2428
|
+
async function isRuntimeOnlyZitadelDir(path) {
|
|
2429
|
+
const entries = await readdir(path, { withFileTypes: true });
|
|
2430
|
+
if (entries.length !== 1 || entries[0]?.name !== "local" || !entries[0].isDirectory()) return false;
|
|
2431
|
+
return true;
|
|
2432
|
+
}
|
|
2433
|
+
async function stashFreshScaffoldArtifacts(cwd, target) {
|
|
2434
|
+
if (!target.hasGitignore && !target.hasRuntimeOnlyZitadel) return;
|
|
2435
|
+
const root = join(dirname(cwd), `.${basename(cwd)}.fresh-scaffold-stash-${String(process.pid)}-${String(Date.now())}`);
|
|
2436
|
+
await mkdir(root, { mode: 448 });
|
|
2437
|
+
const stash = { root };
|
|
2438
|
+
if (target.hasRuntimeOnlyZitadel) {
|
|
2439
|
+
stash.zitadel = join(root, ".zitadel");
|
|
2440
|
+
await rename(join(cwd, ".zitadel"), stash.zitadel);
|
|
2441
|
+
}
|
|
2442
|
+
if (target.hasGitignore) {
|
|
2443
|
+
stash.gitignore = join(root, ".gitignore");
|
|
2444
|
+
await rename(join(cwd, ".gitignore"), stash.gitignore);
|
|
2445
|
+
}
|
|
2446
|
+
return stash;
|
|
2447
|
+
}
|
|
2448
|
+
async function restoreFreshScaffoldArtifacts(cwd, stash) {
|
|
2449
|
+
if (!stash) return;
|
|
2450
|
+
try {
|
|
2451
|
+
await restoreRuntimeOnlyZitadel(cwd, stash.zitadel);
|
|
2452
|
+
await restoreGitignore(cwd, stash.gitignore);
|
|
2453
|
+
} finally {
|
|
2454
|
+
await rm(stash.root, {
|
|
2455
|
+
recursive: true,
|
|
2456
|
+
force: true
|
|
2457
|
+
});
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
async function restoreRuntimeOnlyZitadel(cwd, stash) {
|
|
2461
|
+
if (!stash) return;
|
|
2462
|
+
const target = join(cwd, ".zitadel");
|
|
2463
|
+
try {
|
|
2464
|
+
await rename(stash, target);
|
|
2465
|
+
await appendGitignoreEntry(cwd, ".zitadel/local/");
|
|
2466
|
+
return;
|
|
2467
|
+
} catch (error) {
|
|
2468
|
+
if (!isErrno(error, "EEXIST")) throw error;
|
|
2469
|
+
}
|
|
2470
|
+
await mkdir(target, {
|
|
2471
|
+
recursive: true,
|
|
2472
|
+
mode: 448
|
|
2473
|
+
});
|
|
2474
|
+
await rename(join(stash, "local"), join(target, "local"));
|
|
2475
|
+
await rm(stash, {
|
|
2476
|
+
recursive: true,
|
|
2477
|
+
force: true
|
|
2478
|
+
});
|
|
2479
|
+
await appendGitignoreEntry(cwd, ".zitadel/local/");
|
|
2480
|
+
}
|
|
2481
|
+
async function restoreGitignore(cwd, stash) {
|
|
2482
|
+
if (!stash) return;
|
|
2483
|
+
const path = join(cwd, ".gitignore");
|
|
2484
|
+
const stashed = await readFile(stash, "utf8");
|
|
2485
|
+
let current = "";
|
|
2486
|
+
try {
|
|
2487
|
+
current = await readFile(path, "utf8");
|
|
2488
|
+
} catch (error) {
|
|
2489
|
+
if (!isErrno(error, "ENOENT")) throw error;
|
|
2490
|
+
}
|
|
2491
|
+
const existingLines = new Set(current.split(/\r?\n/g).map((line) => line.trim()).filter(Boolean));
|
|
2492
|
+
const missingLines = stashed.split(/\r?\n/g).map((line) => line.trim()).filter((line) => line.length > 0 && !existingLines.has(line));
|
|
2493
|
+
if (missingLines.length === 0) return;
|
|
2494
|
+
const prefix = current.length === 0 || current.endsWith("\n") ? "" : "\n";
|
|
2495
|
+
await writeFile(path, `${current}${prefix}${missingLines.join("\n")}\n`);
|
|
2496
|
+
}
|
|
2497
|
+
async function appendGitignoreEntry(cwd, entry) {
|
|
2498
|
+
const path = join(cwd, ".gitignore");
|
|
2499
|
+
let existing = "";
|
|
2500
|
+
try {
|
|
2501
|
+
existing = await readFile(path, "utf8");
|
|
2502
|
+
} catch (error) {
|
|
2503
|
+
if (!isErrno(error, "ENOENT")) throw error;
|
|
2504
|
+
}
|
|
2505
|
+
if (existing.split(/\r?\n/g).map((line) => line.trim()).includes(entry)) return;
|
|
2506
|
+
const prefix = existing.length === 0 || existing.endsWith("\n") ? "" : "\n";
|
|
2507
|
+
await writeFile(path, `${existing}${prefix}${entry}\n`);
|
|
2508
|
+
}
|
|
2509
|
+
function isErrno(error, code) {
|
|
2510
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === code;
|
|
2511
|
+
}
|
|
2512
|
+
//#endregion
|
|
2513
|
+
export { RENDERER_IDS as n, issuerFromPort as r, createOrca as t };
|
|
2514
|
+
|
|
2515
|
+
//# sourceMappingURL=orca-CYqJP4ZJ.mjs.map
|