@zitadel/testing 0.1.0-alpha.19 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +79 -25
  2. package/dist/app-runner.cjs +4 -3
  3. package/dist/app-runner.cjs.map +1 -1
  4. package/dist/app-runner.d.mts +1 -1
  5. package/dist/app-runner.mjs +4 -3
  6. package/dist/app-runner.mjs.map +1 -1
  7. package/dist/{handshake-ClzWvG8z.mjs → handshake-CwlxMjW0.mjs} +20 -4
  8. package/dist/handshake-CwlxMjW0.mjs.map +1 -0
  9. package/dist/{handshake-CRKcgkfN.cjs → handshake-D6MXSUcd.cjs} +20 -4
  10. package/dist/handshake-D6MXSUcd.cjs.map +1 -0
  11. package/dist/index.cjs +4 -2
  12. package/dist/index.d.mts +10 -16
  13. package/dist/index.d.mts.map +1 -1
  14. package/dist/index.mjs +3 -3
  15. package/dist/{orchestration-C640_1Lg.mjs → orchestration-Clldecyr.mjs} +1 -1
  16. package/dist/{orchestration-C640_1Lg.mjs.map → orchestration-Clldecyr.mjs.map} +1 -1
  17. package/dist/{orchestration-D7QBgQ0l.cjs → orchestration-gIDANMcF.cjs} +1 -1
  18. package/dist/{orchestration-D7QBgQ0l.cjs.map → orchestration-gIDANMcF.cjs.map} +1 -1
  19. package/dist/playwright.cjs +12 -5
  20. package/dist/playwright.cjs.map +1 -1
  21. package/dist/playwright.d.mts +42 -41
  22. package/dist/playwright.d.mts.map +1 -1
  23. package/dist/playwright.mjs +10 -6
  24. package/dist/playwright.mjs.map +1 -1
  25. package/dist/session-BrSkzPpy.d.mts +204 -0
  26. package/dist/session-BrSkzPpy.d.mts.map +1 -0
  27. package/dist/src-CUvV1OWp.cjs +4187 -0
  28. package/dist/src-CUvV1OWp.cjs.map +1 -0
  29. package/dist/{src-9dFjTIAw.mjs → src-DKJ1hMV8.mjs} +37 -14
  30. package/dist/src-DKJ1hMV8.mjs.map +1 -0
  31. package/dist/supervisor.cjs +3 -3
  32. package/dist/supervisor.cjs.map +1 -1
  33. package/dist/supervisor.d.mts +1 -1
  34. package/dist/supervisor.mjs +3 -3
  35. package/dist/supervisor.mjs.map +1 -1
  36. package/package.json +13 -9
  37. package/dist/app-env-Btmfcflb.d.mts +0 -122
  38. package/dist/app-env-Btmfcflb.d.mts.map +0 -1
  39. package/dist/handshake-CRKcgkfN.cjs.map +0 -1
  40. package/dist/handshake-ClzWvG8z.mjs.map +0 -1
  41. package/dist/src-9dFjTIAw.mjs.map +0 -1
  42. package/dist/src-I0KAh1zU.cjs +0 -2374
  43. package/dist/src-I0KAh1zU.cjs.map +0 -1
@@ -0,0 +1,4187 @@
1
+ const require_handshake = require("./handshake-D6MXSUcd.cjs");
2
+ require("node:fs");
3
+ require("node:url");
4
+ let node_fs_promises = require("node:fs/promises");
5
+ let node_os = require("node:os");
6
+ let node_path = require("node:path");
7
+ let node_child_process = require("node:child_process");
8
+ let node_module = require("node:module");
9
+ let node_net = require("node:net");
10
+ let node_crypto = require("node:crypto");
11
+ //#region ../api/dist/runtime/base-url.mjs
12
+ let proxyPath = "";
13
+ function getProxyPath() {
14
+ return proxyPath;
15
+ }
16
+ function setProxyPath(path) {
17
+ proxyPath = path;
18
+ }
19
+ //#endregion
20
+ //#region ../api/dist/runtime/auth.mjs
21
+ /**
22
+ * Module-global bearer token used by the orval-generated client's
23
+ * custom fetch. Set once at command boot (the same lifecycle pattern
24
+ * as `base-url.ts`); every generated request reads from here.
25
+ *
26
+ * Keeping the token here means the CLI doesn't have to thread an
27
+ * `Authorization` header through every generated call site; orval's
28
+ * `mutator` wires `runtime/fetch.ts` in, and that file pulls the token
29
+ * from this module.
30
+ */
31
+ let apiAuthToken;
32
+ function getApiAuthToken() {
33
+ return apiAuthToken;
34
+ }
35
+ function setApiAuthToken(token) {
36
+ apiAuthToken = token;
37
+ }
38
+ /**
39
+ * The CSRF token for the first-party browser surfaces (ADR 053 §5). A
40
+ * state-changing request that the `__nextgen_session` cookie authenticates must
41
+ * carry the session's token — `csrf_token` from `GET /sessions/me/csrf` — in the
42
+ * `X-Zitadel-CSRF` header. The app sets it once it has loaded its session;
43
+ * `runtime/fetch.ts` then adds the header to unsafe requests. Unset (every
44
+ * other caller), nothing is added.
45
+ *
46
+ * The token belongs to the server that issued it, so it is stored with that
47
+ * server's origin and only sent there: another client on the same page, with
48
+ * another base URL, never carries it to a different host. The origin defaults
49
+ * to the page's own, which is where a same-origin app's API lives; with no
50
+ * origin to go by (no page, or an unparsable request URL), nothing is sent.
51
+ *
52
+ * Unlike the bearer slot, the app sets this one rather than the client, so it
53
+ * lives on `globalThis` under a {@link Symbol.for} key, like the project slot in
54
+ * `config.ts`: a second copy of this module (an SDK pinning another version)
55
+ * must read the token the app's copy wrote.
56
+ */
57
+ const CSRF_SLOT = Symbol.for("@zitadel/api/auth:csrf");
58
+ function csrfSlot() {
59
+ const global = globalThis;
60
+ const existing = global[CSRF_SLOT];
61
+ if (existing) return existing;
62
+ const slot = {};
63
+ global[CSRF_SLOT] = slot;
64
+ return slot;
65
+ }
66
+ /** The token to send to `origin`, if it was issued there. */
67
+ function apiCsrfTokenFor(origin) {
68
+ const slot = csrfSlot();
69
+ return origin !== void 0 && slot.tokenOrigin === origin ? slot.token : void 0;
70
+ }
71
+ /** The rejection handler for a refusal from `origin`, if it was registered for it. */
72
+ function apiCsrfRejectionHandlerFor(origin) {
73
+ const slot = csrfSlot();
74
+ return origin !== void 0 && slot.handlerOrigin === origin ? slot.onRejected : void 0;
75
+ }
76
+ //#endregion
77
+ //#region ../api/dist/runtime/fetch.mjs
78
+ /** The header the session-bound CSRF token travels in (ADR 053 §5). */
79
+ const CSRF_HEADER = "X-Zitadel-CSRF";
80
+ const SAFE_METHODS = /* @__PURE__ */ new Set([
81
+ "GET",
82
+ "HEAD",
83
+ "OPTIONS"
84
+ ]);
85
+ /** The code the server answers a refused CSRF check with. */
86
+ const CSRF_INVALID = "auth.csrf_invalid";
87
+ /**
88
+ * Framework-neutral failure type the orval-generated client throws on
89
+ * any non-2xx response. Carries the HTTP status, the parsed error body
90
+ * (the spec's `{code, message, details?}` envelope when the server
91
+ * returned one), and the request URL — enough for callers to map to
92
+ * their own error taxonomy without re-implementing the fetch layer.
93
+ *
94
+ * Callers that don't care about the distinction can catch `ApiError`
95
+ * generically; callers that do (the CLI's `toZitadelError`) read
96
+ * `status` and decide.
97
+ */
98
+ var ApiError = class extends Error {
99
+ status;
100
+ url;
101
+ body;
102
+ constructor(status, url, body, message) {
103
+ super(message);
104
+ this.name = "ApiError";
105
+ this.status = status;
106
+ this.url = url;
107
+ this.body = body;
108
+ }
109
+ };
110
+ /**
111
+ * Thrown when a request got no response at all: the connection was refused or
112
+ * reset, the host did not resolve, or the server accepted the connection but
113
+ * did not answer in time. The counterpart to {@link ApiError}, which is a
114
+ * response that came back with a failing status.
115
+ *
116
+ * `fetch` only rejects when no response arrived, so this is decided by the
117
+ * fact that it rejected, never by how a runtime words the failure. The
118
+ * runtime's own error stays on `cause` for debugging.
119
+ */
120
+ var NetworkError = class extends Error {
121
+ url;
122
+ /** `timeout` when a deadline cut the request off, `unreachable` otherwise. */
123
+ reason;
124
+ constructor(url, reason, message, options) {
125
+ super(message, options);
126
+ this.name = "NetworkError";
127
+ this.url = url;
128
+ this.reason = reason;
129
+ }
130
+ };
131
+ let requestPolicy = {};
132
+ function setRequestPolicy(policy) {
133
+ requestPolicy = policy;
134
+ }
135
+ /**
136
+ * The orval `mutator` for the fetch client. Every generated operation
137
+ * routes its request through this function instead of the global
138
+ * `fetch`. We pin three concerns here so generated call sites stay
139
+ * focused on the shape of one HTTP call:
140
+ *
141
+ * - bearer auth — read from `runtime/auth.ts` and attached automatically;
142
+ * - the CSRF header — the session-bound token from `runtime/auth.ts`, on
143
+ * unsafe methods to the origin it was issued for, when a first-party surface
144
+ * has set one; an unsafe request to that origin refused with
145
+ * `403 auth.csrf_invalid` asks the registered rejection handler for a fresh
146
+ * token and is retried once with it, only if the handler returns one (the
147
+ * session still belongs to the same person);
148
+ * - non-2xx → throw — orval's stock client parses the body regardless
149
+ * of status, so callers would have to inspect every response. Throw
150
+ * `ApiError` on `!res.ok` so failures interrupt control flow;
151
+ * - body parsing — return the parsed JSON typed as `T` (the operation's
152
+ * return type, threaded through by orval), or `undefined` for the
153
+ * spec's `204`/`205`/`304` no-body responses;
154
+ * - no response → throw {@link NetworkError}, or the abort reason when the
155
+ * caller cancelled (see {@link request}).
156
+ */
157
+ async function customFetch(url, options) {
158
+ const policy = requestPolicy;
159
+ const token = getApiAuthToken();
160
+ const headers = new Headers(options.headers);
161
+ if (token && !headers.has("authorization")) headers.set("authorization", `Bearer ${token}`);
162
+ const method = (options.method ?? "GET").toUpperCase();
163
+ const unsafe = !SAFE_METHODS.has(method) && !headers.has("X-Zitadel-CSRF");
164
+ const target = originOf(url);
165
+ const csrfToken = apiCsrfTokenFor(target);
166
+ if (unsafe && csrfToken) headers.set(CSRF_HEADER, csrfToken);
167
+ let { res, rawBody: parsed } = await request(url, {
168
+ ...options,
169
+ headers
170
+ }, policy, readBody);
171
+ const onRejected = apiCsrfRejectionHandlerFor(target);
172
+ if (unsafe && onRejected && res.status === 403 && apiErrorCode(parsed) === CSRF_INVALID && !isStream(options.body)) {
173
+ const fresh = await onRejected().catch(() => void 0);
174
+ if (fresh && fresh !== csrfToken) {
175
+ headers.set(CSRF_HEADER, fresh);
176
+ ({res, rawBody: parsed} = await request(url, {
177
+ ...options,
178
+ headers
179
+ }, policy, readBody));
180
+ }
181
+ }
182
+ if (!res.ok) {
183
+ const message = `${options.method ?? "GET"} ${url} returned ${res.status}`;
184
+ throw new ApiError(res.status, url, parsed, message);
185
+ }
186
+ return parsed;
187
+ }
188
+ /** The parsed body, or `undefined` for the spec's no-body responses. */
189
+ async function readBody(res) {
190
+ if ([
191
+ 204,
192
+ 205,
193
+ 304
194
+ ].includes(res.status)) return void 0;
195
+ const rawBody = await res.text();
196
+ return rawBody ? safeJsonParse(rawBody) : void 0;
197
+ }
198
+ /** The request's origin, resolved against the page for a relative URL. */
199
+ function originOf(url) {
200
+ try {
201
+ return new URL(url, globalThis.location?.href).origin;
202
+ } catch {
203
+ return;
204
+ }
205
+ }
206
+ function isStream(body) {
207
+ return typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
208
+ }
209
+ /**
210
+ * `fetch` bound by a {@link RequestPolicy}, with its failures typed.
211
+ *
212
+ * The policy's signal, its deadline and any signal on `init` are combined, and
213
+ * `read` runs under them too, so a server that sends headers and then stalls
214
+ * mid-body is cut off as well. When the request does not complete:
215
+ *
216
+ * - a deadline fired → {@link NetworkError} with reason `timeout`;
217
+ * - any other abort → the signal's own reason, rethrown untouched, because a
218
+ * cancellation is the caller's decision and the caller knows what it means;
219
+ * - anything else → {@link NetworkError} with reason `unreachable`.
220
+ *
221
+ * Exported for the few callers that need the raw {@link Response} (a
222
+ * `Set-Cookie` header the generated client does not expose).
223
+ */
224
+ async function request(url, init, policy = {}, read) {
225
+ const signals = [init.signal, policy.signal].filter((signal) => signal != null);
226
+ if (policy.timeoutMs !== void 0) signals.push(AbortSignal.timeout(policy.timeoutMs));
227
+ const signal = signals.length > 0 ? AbortSignal.any(signals) : void 0;
228
+ const method = init.method ?? "GET";
229
+ try {
230
+ const res = await fetch(url, {
231
+ ...init,
232
+ signal
233
+ });
234
+ return {
235
+ res,
236
+ rawBody: read ? await read(res) : void 0
237
+ };
238
+ } catch (error) {
239
+ if (signal?.aborted) {
240
+ const reason = signal.reason;
241
+ if (reason instanceof DOMException && reason.name === "TimeoutError") throw new NetworkError(url, "timeout", `${method} ${url} timed out`, { cause: reason });
242
+ throw reason;
243
+ }
244
+ const code = errnoOf(error);
245
+ throw new NetworkError(url, "unreachable", `${method} ${url} got no response${code ? ` (${code})` : ""}`, { cause: error });
246
+ }
247
+ }
248
+ /**
249
+ * The errno a runtime attached to a failed request, if any, for the message.
250
+ * Undici nests it on `cause`, inside an `AggregateError` when it tried more
251
+ * than one address. Only ever used to describe the failure, never to decide
252
+ * that it was one.
253
+ */
254
+ function errnoOf(error) {
255
+ let node = error;
256
+ for (let depth = 0; depth < 4 && typeof node === "object" && node !== null; depth += 1) {
257
+ const { code, errors } = node;
258
+ if (typeof code === "string") return code;
259
+ node = Array.isArray(errors) ? errors[0] : node.cause;
260
+ }
261
+ }
262
+ /**
263
+ * `JSON.parse` wrapped so a non-JSON body (e.g. an HTML 502 from a
264
+ * proxy) becomes `{ raw: "<text>" }` instead of throwing inside
265
+ * `customFetch`. The thrown `ApiError` then carries something useful
266
+ * for the user to see.
267
+ */
268
+ function safeJsonParse(text) {
269
+ try {
270
+ return JSON.parse(text);
271
+ } catch {
272
+ return { raw: text };
273
+ }
274
+ }
275
+ /**
276
+ * The `code` of the server's `{code, message, details}` error envelope: from an
277
+ * {@link ApiError}, or from a parsed response body. `undefined` when there is
278
+ * none, e.g. an HTML error page from a proxy.
279
+ */
280
+ function apiErrorCode(errorOrBody) {
281
+ const body = errorOrBody instanceof ApiError ? errorOrBody.body : errorOrBody;
282
+ return isRecord(body) && typeof body.code === "string" ? body.code : void 0;
283
+ }
284
+ function isRecord(value) {
285
+ return typeof value === "object" && value !== null && !Array.isArray(value);
286
+ }
287
+ //#endregion
288
+ //#region ../api/dist/rolldown-runtime-D7D4PA-g.mjs
289
+ var __defProp = Object.defineProperty;
290
+ var __exportAll = (all, no_symbols) => {
291
+ let target = {};
292
+ for (var name in all) __defProp(target, name, {
293
+ get: all[name],
294
+ enumerable: true
295
+ });
296
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
297
+ return target;
298
+ };
299
+ //#endregion
300
+ //#region ../api/dist/generated/endpoints/zitadelNextGen.mjs
301
+ /**
302
+ * Generated by orval 🍺
303
+ * Do not edit manually.
304
+ * Zitadel NextGen
305
+ * This is the next generation of the Zitadel identity platform.
306
+ * OpenAPI spec version: 0.0.1
307
+ */
308
+ var zitadelNextGen_exports = /* @__PURE__ */ __exportAll({
309
+ addOrigin: () => addOrigin,
310
+ beginUserPasskeyRegistration: () => beginUserPasskeyRegistration,
311
+ buildRelease: () => buildRelease,
312
+ completeClaim: () => completeClaim,
313
+ createAuthAttempt: () => createAuthAttempt,
314
+ createBranding: () => createBranding,
315
+ createDeployment: () => createDeployment,
316
+ createFlow: () => createFlow,
317
+ createFlowDefinition: () => createFlowDefinition,
318
+ createGrant: () => createGrant,
319
+ createHandoff: () => createHandoff,
320
+ createIdp: () => createIdp,
321
+ createProject: () => createProject,
322
+ createRelease: () => createRelease,
323
+ createSchema: () => createSchema,
324
+ createSession: () => createSession,
325
+ createTeam: () => createTeam,
326
+ createUser: () => createUser,
327
+ deleteGrant: () => deleteGrant,
328
+ deleteTeam: () => deleteTeam,
329
+ deleteUserByID: () => deleteUserByID,
330
+ deleteVariable: () => deleteVariable,
331
+ exchangeHandoff: () => exchangeHandoff,
332
+ finishUserPasskeyRegistration: () => finishUserPasskeyRegistration,
333
+ getAddOriginUrl: () => getAddOriginUrl,
334
+ getAuthAttempt: () => getAuthAttempt,
335
+ getBeginUserPasskeyRegistrationUrl: () => getBeginUserPasskeyRegistrationUrl,
336
+ getBrandingById: () => getBrandingById,
337
+ getBuildReleaseUrl: () => getBuildReleaseUrl,
338
+ getClaimStatus: () => getClaimStatus,
339
+ getClaimWindow: () => getClaimWindow,
340
+ getCompleteClaimUrl: () => getCompleteClaimUrl,
341
+ getCreateAuthAttemptUrl: () => getCreateAuthAttemptUrl,
342
+ getCreateBrandingUrl: () => getCreateBrandingUrl,
343
+ getCreateDeploymentUrl: () => getCreateDeploymentUrl,
344
+ getCreateFlowDefinitionUrl: () => getCreateFlowDefinitionUrl,
345
+ getCreateFlowUrl: () => getCreateFlowUrl,
346
+ getCreateGrantUrl: () => getCreateGrantUrl,
347
+ getCreateHandoffUrl: () => getCreateHandoffUrl,
348
+ getCreateIdpUrl: () => getCreateIdpUrl,
349
+ getCreateProjectUrl: () => getCreateProjectUrl,
350
+ getCreateReleaseUrl: () => getCreateReleaseUrl,
351
+ getCreateSchemaUrl: () => getCreateSchemaUrl,
352
+ getCreateSessionUrl: () => getCreateSessionUrl,
353
+ getCreateTeamUrl: () => getCreateTeamUrl,
354
+ getCreateUserUrl: () => getCreateUserUrl,
355
+ getDeleteGrantUrl: () => getDeleteGrantUrl,
356
+ getDeleteTeamUrl: () => getDeleteTeamUrl,
357
+ getDeleteUserByIDUrl: () => getDeleteUserByIDUrl,
358
+ getDeleteVariableUrl: () => getDeleteVariableUrl,
359
+ getDeploymentById: () => getDeploymentById,
360
+ getDeploymentVariables: () => getDeploymentVariables,
361
+ getEvent: () => getEvent,
362
+ getExchangeHandoffUrl: () => getExchangeHandoffUrl,
363
+ getFinishUserPasskeyRegistrationUrl: () => getFinishUserPasskeyRegistrationUrl,
364
+ getFlowDefinition: () => getFlowDefinition,
365
+ getFlowStep: () => getFlowStep,
366
+ getGetAuthAttemptUrl: () => getGetAuthAttemptUrl,
367
+ getGetBrandingByIdUrl: () => getGetBrandingByIdUrl,
368
+ getGetClaimStatusUrl: () => getGetClaimStatusUrl,
369
+ getGetClaimWindowUrl: () => getGetClaimWindowUrl,
370
+ getGetDeploymentByIdUrl: () => getGetDeploymentByIdUrl,
371
+ getGetDeploymentVariablesUrl: () => getGetDeploymentVariablesUrl,
372
+ getGetEventUrl: () => getGetEventUrl,
373
+ getGetFlowDefinitionUrl: () => getGetFlowDefinitionUrl,
374
+ getGetFlowStepUrl: () => getGetFlowStepUrl,
375
+ getGetGrantUrl: () => getGetGrantUrl,
376
+ getGetHealthUrl: () => getGetHealthUrl,
377
+ getGetIdpByIdUrl: () => getGetIdpByIdUrl,
378
+ getGetIdpRevisionByIdUrl: () => getGetIdpRevisionByIdUrl,
379
+ getGetLiveUrl: () => getGetLiveUrl,
380
+ getGetMyPasswordStateUrl: () => getGetMyPasswordStateUrl,
381
+ getGetMySessionCsrfTokenUrl: () => getGetMySessionCsrfTokenUrl,
382
+ getGetMySessionUrl: () => getGetMySessionUrl,
383
+ getGetMyUserSchemaUrl: () => getGetMyUserSchemaUrl,
384
+ getGetMyUserUrl: () => getGetMyUserUrl,
385
+ getGetProjectUrl: () => getGetProjectUrl,
386
+ getGetReadyUrl: () => getGetReadyUrl,
387
+ getGetReleaseByIdUrl: () => getGetReleaseByIdUrl,
388
+ getGetSchemaByIdUrl: () => getGetSchemaByIdUrl,
389
+ getGetSessionUrl: () => getGetSessionUrl,
390
+ getGetTeamUrl: () => getGetTeamUrl,
391
+ getGetUserByIDUrl: () => getGetUserByIDUrl,
392
+ getGetUserPasswordStateUrl: () => getGetUserPasswordStateUrl,
393
+ getGetVariableUrl: () => getGetVariableUrl,
394
+ getGetVariablesUrl: () => getGetVariablesUrl,
395
+ getGrant: () => getGrant,
396
+ getHealth: () => getHealth,
397
+ getIdpById: () => getIdpById,
398
+ getIdpRevisionById: () => getIdpRevisionById,
399
+ getInitClaimUrl: () => getInitClaimUrl,
400
+ getIssueChallengeUrl: () => getIssueChallengeUrl,
401
+ getListBrandingUrl: () => getListBrandingUrl,
402
+ getListDeploymentsUrl: () => getListDeploymentsUrl,
403
+ getListEventsUrl: () => getListEventsUrl,
404
+ getListFlowDefinitionsUrl: () => getListFlowDefinitionsUrl,
405
+ getListIdpRevisionsUrl: () => getListIdpRevisionsUrl,
406
+ getListMyIdentityLinksUrl: () => getListMyIdentityLinksUrl,
407
+ getListMyPasskeysUrl: () => getListMyPasskeysUrl,
408
+ getListMyProjectsUrl: () => getListMyProjectsUrl,
409
+ getListMyTeamsUrl: () => getListMyTeamsUrl,
410
+ getListPreviewsUrl: () => getListPreviewsUrl,
411
+ getListReleasesUrl: () => getListReleasesUrl,
412
+ getListSchemasUrl: () => getListSchemasUrl,
413
+ getListUserIdentityLinksUrl: () => getListUserIdentityLinksUrl,
414
+ getListUserPasskeysUrl: () => getListUserPasskeysUrl,
415
+ getListUserTeamsUrl: () => getListUserTeamsUrl,
416
+ getLive: () => getLive,
417
+ getMyPasswordState: () => getMyPasswordState,
418
+ getMySession: () => getMySession,
419
+ getMySessionCsrfToken: () => getMySessionCsrfToken,
420
+ getMyUser: () => getMyUser,
421
+ getMyUserSchema: () => getMyUserSchema,
422
+ getPatchMyUserUrl: () => getPatchMyUserUrl,
423
+ getPatchProjectUrl: () => getPatchProjectUrl,
424
+ getPatchUserByIDUrl: () => getPatchUserByIDUrl,
425
+ getProject: () => getProject,
426
+ getQueryGrantsUrl: () => getQueryGrantsUrl,
427
+ getQueryIdpsUrl: () => getQueryIdpsUrl,
428
+ getQueryProjectsUrl: () => getQueryProjectsUrl,
429
+ getQuerySessionsUrl: () => getQuerySessionsUrl,
430
+ getQueryTeamsUrl: () => getQueryTeamsUrl,
431
+ getQueryUsersUrl: () => getQueryUsersUrl,
432
+ getReady: () => getReady,
433
+ getReleaseById: () => getReleaseById,
434
+ getRemoveOriginUrl: () => getRemoveOriginUrl,
435
+ getRemovePreviewUrl: () => getRemovePreviewUrl,
436
+ getRevokeMySessionUrl: () => getRevokeMySessionUrl,
437
+ getRevokeReleaseUrl: () => getRevokeReleaseUrl,
438
+ getRevokeSessionUrl: () => getRevokeSessionUrl,
439
+ getRollbackDeploymentUrl: () => getRollbackDeploymentUrl,
440
+ getSchemaById: () => getSchemaById,
441
+ getSession: () => getSession,
442
+ getSetUserPasswordUrl: () => getSetUserPasswordUrl,
443
+ getSubmitFlowStepUrl: () => getSubmitFlowStepUrl,
444
+ getTeam: () => getTeam,
445
+ getUpdateTeamUrl: () => getUpdateTeamUrl,
446
+ getUpdateVariablesUrl: () => getUpdateVariablesUrl,
447
+ getUserByID: () => getUserByID,
448
+ getUserPasswordState: () => getUserPasswordState,
449
+ getVariable: () => getVariable,
450
+ getVariables: () => getVariables,
451
+ getVerifyChallengeProofUrl: () => getVerifyChallengeProofUrl,
452
+ initClaim: () => initClaim,
453
+ issueChallenge: () => issueChallenge,
454
+ listBranding: () => listBranding,
455
+ listDeployments: () => listDeployments,
456
+ listEvents: () => listEvents,
457
+ listFlowDefinitions: () => listFlowDefinitions,
458
+ listIdpRevisions: () => listIdpRevisions,
459
+ listMyIdentityLinks: () => listMyIdentityLinks,
460
+ listMyPasskeys: () => listMyPasskeys,
461
+ listMyProjects: () => listMyProjects,
462
+ listMyTeams: () => listMyTeams,
463
+ listPreviews: () => listPreviews,
464
+ listReleases: () => listReleases,
465
+ listSchemas: () => listSchemas,
466
+ listUserIdentityLinks: () => listUserIdentityLinks,
467
+ listUserPasskeys: () => listUserPasskeys,
468
+ listUserTeams: () => listUserTeams,
469
+ patchMyUser: () => patchMyUser,
470
+ patchProject: () => patchProject,
471
+ patchUserByID: () => patchUserByID,
472
+ queryGrants: () => queryGrants,
473
+ queryIdps: () => queryIdps,
474
+ queryProjects: () => queryProjects,
475
+ querySessions: () => querySessions,
476
+ queryTeams: () => queryTeams,
477
+ queryUsers: () => queryUsers,
478
+ removeOrigin: () => removeOrigin,
479
+ removePreview: () => removePreview,
480
+ revokeMySession: () => revokeMySession,
481
+ revokeRelease: () => revokeRelease,
482
+ revokeSession: () => revokeSession,
483
+ rollbackDeployment: () => rollbackDeployment,
484
+ setUserPassword: () => setUserPassword,
485
+ submitFlowStep: () => submitFlowStep,
486
+ updateTeam: () => updateTeam,
487
+ updateVariables: () => updateVariables,
488
+ verifyChallengeProof: () => verifyChallengeProof
489
+ });
490
+ const getGetHealthUrl = () => {
491
+ return `${getProxyPath()}/healthz`;
492
+ };
493
+ /**
494
+ * Check whether the server is healthy
495
+ * @summary Check server health
496
+ */
497
+ const getHealth = async (options) => {
498
+ return customFetch(getGetHealthUrl(), {
499
+ ...options,
500
+ method: "GET"
501
+ });
502
+ };
503
+ const getGetLiveUrl = () => {
504
+ return `${getProxyPath()}/livez`;
505
+ };
506
+ /**
507
+ * Check whether the server is started
508
+ * @summary Check server liveness
509
+ */
510
+ const getLive = async (options) => {
511
+ return customFetch(getGetLiveUrl(), {
512
+ ...options,
513
+ method: "GET"
514
+ });
515
+ };
516
+ const getGetReadyUrl = () => {
517
+ return `${getProxyPath()}/readyz`;
518
+ };
519
+ /**
520
+ * Check whether the server is ready to accept requests
521
+ * @summary Check server readiness
522
+ */
523
+ const getReady = async (options) => {
524
+ return customFetch(getGetReadyUrl(), {
525
+ ...options,
526
+ method: "GET"
527
+ });
528
+ };
529
+ const getCreateUserUrl = (params) => {
530
+ const normalizedParams = new URLSearchParams();
531
+ Object.entries(params || {}).forEach(([key, value]) => {
532
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
533
+ });
534
+ const stringifiedParams = normalizedParams.toString();
535
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/users?${stringifiedParams}` : `${getProxyPath()}/users`;
536
+ };
537
+ /**
538
+ * Creates a user whose attributes satisfy the user schema the request names.
539
+ *
540
+ * The server assigns the user's id. With `team_id`, the user also becomes an
541
+ * active member of that team. A value the schema marks unique that another
542
+ * user already holds is refused with `409`.
543
+ * @summary Create user
544
+ */
545
+ const createUser = async (createUserBody, params, options) => {
546
+ const getHeaders = (h) => {
547
+ if (!h) return {};
548
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
549
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
550
+ const headers = {};
551
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
552
+ return headers;
553
+ };
554
+ return customFetch(getCreateUserUrl(params), {
555
+ ...options,
556
+ method: "POST",
557
+ headers: {
558
+ "Content-Type": "application/json",
559
+ ...getHeaders(options?.headers)
560
+ },
561
+ body: JSON.stringify(createUserBody)
562
+ });
563
+ };
564
+ const getQueryUsersUrl = (params) => {
565
+ const normalizedParams = new URLSearchParams();
566
+ Object.entries(params || {}).forEach(([key, value]) => {
567
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
568
+ });
569
+ const stringifiedParams = normalizedParams.toString();
570
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/users/query?${stringifiedParams}` : `${getProxyPath()}/users/query`;
571
+ };
572
+ /**
573
+ * Returns the users of a project, paginated with a cursor.
574
+ *
575
+ * `project_id` names the project to list; without it, the credential's own
576
+ * project is listed.
577
+ *
578
+ * Accepts either a project secret (`oauth2`) or a user-bound Console
579
+ * session cookie (`nextgenSession`). Cookie-authenticated requests
580
+ * follow the scheme's CSRF rules (`nextgenSession`).
581
+ * @summary Query users
582
+ */
583
+ const queryUsers = async (queryUsersBody, params, options) => {
584
+ const getHeaders = (h) => {
585
+ if (!h) return {};
586
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
587
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
588
+ const headers = {};
589
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
590
+ return headers;
591
+ };
592
+ return customFetch(getQueryUsersUrl(params), {
593
+ ...options,
594
+ method: "POST",
595
+ headers: {
596
+ "Content-Type": "application/json",
597
+ ...getHeaders(options?.headers)
598
+ },
599
+ body: JSON.stringify(queryUsersBody)
600
+ });
601
+ };
602
+ const getGetUserByIDUrl = (userId, params) => {
603
+ const normalizedParams = new URLSearchParams();
604
+ Object.entries(params || {}).forEach(([key, value]) => {
605
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
606
+ });
607
+ const stringifiedParams = normalizedParams.toString();
608
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/users/${encodeURIComponent(String(userId))}?${stringifiedParams}` : `${getProxyPath()}/users/${encodeURIComponent(String(userId))}`;
609
+ };
610
+ /**
611
+ * Returns a user by its id, with the attributes its schema defines.
612
+ *
613
+ * With `team_id`, the user is returned only while they are an active member of
614
+ * that team.
615
+ * @summary Get user by ID
616
+ */
617
+ const getUserByID = async (userId, params, options) => {
618
+ return customFetch(getGetUserByIDUrl(userId, params), {
619
+ ...options,
620
+ method: "GET"
621
+ });
622
+ };
623
+ const getPatchUserByIDUrl = (userId) => {
624
+ return `${getProxyPath()}/users/${encodeURIComponent(String(userId))}`;
625
+ };
626
+ /**
627
+ * Partially updates a user's schema-defined attributes, and optionally
628
+ * moves the user to another registered schema. The merged result is
629
+ * validated against the schema before commit. Concurrent writes are
630
+ * last-write-wins.
631
+ * @summary Update user by ID
632
+ */
633
+ const patchUserByID = async (userId, patchUserByIDBody, options) => {
634
+ const getHeaders = (h) => {
635
+ if (!h) return {};
636
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
637
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
638
+ const headers = {};
639
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
640
+ return headers;
641
+ };
642
+ return customFetch(getPatchUserByIDUrl(userId), {
643
+ ...options,
644
+ method: "PATCH",
645
+ headers: {
646
+ "Content-Type": "application/json",
647
+ ...getHeaders(options?.headers)
648
+ },
649
+ body: JSON.stringify(patchUserByIDBody)
650
+ });
651
+ };
652
+ const getDeleteUserByIDUrl = (userId) => {
653
+ return `${getProxyPath()}/users/${encodeURIComponent(String(userId))}`;
654
+ };
655
+ /**
656
+ * Deletes a user and removes them from every team they belong to.
657
+ *
658
+ * The user is removed, not deactivated, and the deletion emits `user.deleted`.
659
+ * With a project secret the request is idempotent: deleting a user that exists
660
+ * in no project succeeds without changing anything.
661
+ * @summary Delete user by ID
662
+ */
663
+ const deleteUserByID = async (userId, options) => {
664
+ return customFetch(getDeleteUserByIDUrl(userId), {
665
+ ...options,
666
+ method: "DELETE"
667
+ });
668
+ };
669
+ const getListUserIdentityLinksUrl = (userId, params) => {
670
+ const normalizedParams = new URLSearchParams();
671
+ Object.entries(params || {}).forEach(([key, value]) => {
672
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
673
+ });
674
+ const stringifiedParams = normalizedParams.toString();
675
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/identity_links?${stringifiedParams}` : `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/identity_links`;
676
+ };
677
+ /**
678
+ * The identity provider accounts a sign-in linked to the user, oldest first.
679
+ * The provider's subject and claims are never returned.
680
+ * @summary List the provider accounts linked to a user
681
+ */
682
+ const listUserIdentityLinks = async (userId, params, options) => {
683
+ return customFetch(getListUserIdentityLinksUrl(userId, params), {
684
+ ...options,
685
+ method: "GET"
686
+ });
687
+ };
688
+ const getListUserPasskeysUrl = (userId, params) => {
689
+ const normalizedParams = new URLSearchParams();
690
+ Object.entries(params || {}).forEach(([key, value]) => {
691
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
692
+ });
693
+ const stringifiedParams = normalizedParams.toString();
694
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/passkeys?${stringifiedParams}` : `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/passkeys`;
695
+ };
696
+ /**
697
+ * Returns the passkeys registered for a user, newest first, paginated with a
698
+ * cursor.
699
+ *
700
+ * Each passkey carries its id, its name and when it was registered, never the
701
+ * credential itself.
702
+ * @summary List user passkeys
703
+ */
704
+ const listUserPasskeys = async (userId, params, options) => {
705
+ return customFetch(getListUserPasskeysUrl(userId, params), {
706
+ ...options,
707
+ method: "GET"
708
+ });
709
+ };
710
+ const getBeginUserPasskeyRegistrationUrl = (userId) => {
711
+ return `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/passkeys/registrations`;
712
+ };
713
+ /**
714
+ * Starts a WebAuthn registration ceremony for the user and returns the
715
+ * creation options for `navigator.credentials.create()`. Complete the
716
+ * ceremony with `POST /users/{user_id}/passkeys/registrations/{registration_id}` within
717
+ * five minutes. Credentials already registered for the user are excluded
718
+ * automatically.
719
+ * @summary Begin passkey registration
720
+ */
721
+ const beginUserPasskeyRegistration = async (userId, beginUserPasskeyRegistrationBody, options) => {
722
+ const getHeaders = (h) => {
723
+ if (!h) return {};
724
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
725
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
726
+ const headers = {};
727
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
728
+ return headers;
729
+ };
730
+ return customFetch(getBeginUserPasskeyRegistrationUrl(userId), {
731
+ ...options,
732
+ method: "POST",
733
+ headers: {
734
+ "Content-Type": "application/json",
735
+ ...getHeaders(options?.headers)
736
+ },
737
+ body: JSON.stringify(beginUserPasskeyRegistrationBody)
738
+ });
739
+ };
740
+ const getFinishUserPasskeyRegistrationUrl = (userId, registrationId) => {
741
+ return `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/passkeys/registrations/${encodeURIComponent(String(registrationId))}`;
742
+ };
743
+ /**
744
+ * Verifies the attestation against the ceremony started by
745
+ * `POST /users/{user_id}/passkeys/registrations` and persists the new credential. A
746
+ * rejected attestation counts against the ceremony's failure budget and the
747
+ * ceremony stays open for a retry. An expired ceremony surfaces as
748
+ * `att.stale_challenge`; an unknown or already-consumed registration id
749
+ * surfaces as `att.not_found`.
750
+ * @summary Finish passkey registration
751
+ */
752
+ const finishUserPasskeyRegistration = async (userId, registrationId, finishUserPasskeyRegistrationBody, options) => {
753
+ const getHeaders = (h) => {
754
+ if (!h) return {};
755
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
756
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
757
+ const headers = {};
758
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
759
+ return headers;
760
+ };
761
+ return customFetch(getFinishUserPasskeyRegistrationUrl(userId, registrationId), {
762
+ ...options,
763
+ method: "POST",
764
+ headers: {
765
+ "Content-Type": "application/json",
766
+ ...getHeaders(options?.headers)
767
+ },
768
+ body: JSON.stringify(finishUserPasskeyRegistrationBody)
769
+ });
770
+ };
771
+ const getGetUserPasswordStateUrl = (userId) => {
772
+ return `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/password`;
773
+ };
774
+ /**
775
+ * Reports when the user's current password was set, and leaves `set_at` out
776
+ * when the user has none. The password and its hash are never returned;
777
+ * setting one is `PUT` on the same path.
778
+ * @summary Get user password state
779
+ */
780
+ const getUserPasswordState = async (userId, options) => {
781
+ return customFetch(getGetUserPasswordStateUrl(userId), {
782
+ ...options,
783
+ method: "GET"
784
+ });
785
+ };
786
+ const getSetUserPasswordUrl = (userId) => {
787
+ return `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/password`;
788
+ };
789
+ /**
790
+ * Sets a user's password, hashed with the project's current password hashing
791
+ * policy.
792
+ *
793
+ * The new password replaces the current one, and setting it emits
794
+ * `auth.factor.password.set`.
795
+ * @summary Set user password
796
+ */
797
+ const setUserPassword = async (userId, setUserPasswordBody, options) => {
798
+ const getHeaders = (h) => {
799
+ if (!h) return {};
800
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
801
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
802
+ const headers = {};
803
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
804
+ return headers;
805
+ };
806
+ return customFetch(getSetUserPasswordUrl(userId), {
807
+ ...options,
808
+ method: "PUT",
809
+ headers: {
810
+ "Content-Type": "application/json",
811
+ ...getHeaders(options?.headers)
812
+ },
813
+ body: JSON.stringify(setUserPasswordBody)
814
+ });
815
+ };
816
+ const getListUserTeamsUrl = (userId, params) => {
817
+ const normalizedParams = new URLSearchParams();
818
+ Object.entries(params || {}).forEach(([key, value]) => {
819
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
820
+ });
821
+ const stringifiedParams = normalizedParams.toString();
822
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/teams?${stringifiedParams}` : `${getProxyPath()}/users/${encodeURIComponent(String(userId))}/teams`;
823
+ };
824
+ /**
825
+ * The user's team roster, ordered by team name. Each entry carries the
826
+ * team's name, so a client renders a page without resolving ids one by one.
827
+ *
828
+ * This is the N:N roster and it is not lifecycle ownership: the single team
829
+ * that owns the user's lifecycle is reported as `metadata.lifecycle_owner_team_id`
830
+ * on the user read endpoints. Memberships the user was removed from are not
831
+ * returned.
832
+ * @summary List the teams a user belongs to
833
+ */
834
+ const listUserTeams = async (userId, params, options) => {
835
+ return customFetch(getListUserTeamsUrl(userId, params), {
836
+ ...options,
837
+ method: "GET"
838
+ });
839
+ };
840
+ const getGetMyUserUrl = (params) => {
841
+ const normalizedParams = new URLSearchParams();
842
+ Object.entries(params || {}).forEach(([key, value]) => {
843
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
844
+ });
845
+ const stringifiedParams = normalizedParams.toString();
846
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me?${stringifiedParams}` : `${getProxyPath()}/users/me`;
847
+ };
848
+ /**
849
+ * Returns the user signed in to the session that authenticates the request.
850
+ *
851
+ * The project and the user both come from the session cookie, so a caller only
852
+ * ever reads their own user.
853
+ *
854
+ * With `project_id`, the user is returned only when the session belongs to
855
+ * that project.
856
+ * @summary Get my user information
857
+ */
858
+ const getMyUser = async (params, options) => {
859
+ return customFetch(getGetMyUserUrl(params), {
860
+ ...options,
861
+ method: "GET"
862
+ });
863
+ };
864
+ const getPatchMyUserUrl = (params) => {
865
+ const normalizedParams = new URLSearchParams();
866
+ Object.entries(params || {}).forEach(([key, value]) => {
867
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
868
+ });
869
+ const stringifiedParams = normalizedParams.toString();
870
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me?${stringifiedParams}` : `${getProxyPath()}/users/me`;
871
+ };
872
+ /**
873
+ * Partially updates the caller's own schema-defined attributes. The merged
874
+ * result is validated against the user's schema before commit. Concurrent
875
+ * writes are last-write-wins.
876
+ *
877
+ * With `project_id`, the user is updated only when the session belongs to
878
+ * that project.
879
+ * @summary Update my user information
880
+ */
881
+ const patchMyUser = async (patchMyUserBody, params, options) => {
882
+ const getHeaders = (h) => {
883
+ if (!h) return {};
884
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
885
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
886
+ const headers = {};
887
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
888
+ return headers;
889
+ };
890
+ return customFetch(getPatchMyUserUrl(params), {
891
+ ...options,
892
+ method: "PATCH",
893
+ headers: {
894
+ "Content-Type": "application/json",
895
+ ...getHeaders(options?.headers)
896
+ },
897
+ body: JSON.stringify(patchMyUserBody)
898
+ });
899
+ };
900
+ const getListMyIdentityLinksUrl = (params) => {
901
+ const normalizedParams = new URLSearchParams();
902
+ Object.entries(params || {}).forEach(([key, value]) => {
903
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
904
+ });
905
+ const stringifiedParams = normalizedParams.toString();
906
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me/identity_links?${stringifiedParams}` : `${getProxyPath()}/users/me/identity_links`;
907
+ };
908
+ /**
909
+ * The identity provider accounts a sign-in linked to the signed-in user,
910
+ * oldest first. The provider's subject and claims are never returned.
911
+ *
912
+ * With `project_id`, the links are listed only when the session belongs to
913
+ * that project.
914
+ * @summary List the provider accounts linked to me
915
+ */
916
+ const listMyIdentityLinks = async (params, options) => {
917
+ return customFetch(getListMyIdentityLinksUrl(params), {
918
+ ...options,
919
+ method: "GET"
920
+ });
921
+ };
922
+ const getListMyPasskeysUrl = (params) => {
923
+ const normalizedParams = new URLSearchParams();
924
+ Object.entries(params || {}).forEach(([key, value]) => {
925
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
926
+ });
927
+ const stringifiedParams = normalizedParams.toString();
928
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me/passkeys?${stringifiedParams}` : `${getProxyPath()}/users/me/passkeys`;
929
+ };
930
+ /**
931
+ * The signed-in user's own passkeys, newest first, paginated with a cursor.
932
+ * Each passkey carries its id, its name and when it was registered, never the
933
+ * credential itself.
934
+ *
935
+ * With `project_id`, the passkeys are listed only when the session belongs to
936
+ * that project.
937
+ * @summary List my passkeys
938
+ */
939
+ const listMyPasskeys = async (params, options) => {
940
+ return customFetch(getListMyPasskeysUrl(params), {
941
+ ...options,
942
+ method: "GET"
943
+ });
944
+ };
945
+ const getGetMyPasswordStateUrl = (params) => {
946
+ const normalizedParams = new URLSearchParams();
947
+ Object.entries(params || {}).forEach(([key, value]) => {
948
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
949
+ });
950
+ const stringifiedParams = normalizedParams.toString();
951
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me/password?${stringifiedParams}` : `${getProxyPath()}/users/me/password`;
952
+ };
953
+ /**
954
+ * Reports when the signed-in user's current password was set, and leaves
955
+ * `set_at` out when they have none. The password and its hash are never
956
+ * returned.
957
+ *
958
+ * With `project_id`, the state is read only when the session belongs to that
959
+ * project.
960
+ * @summary Get my password state
961
+ */
962
+ const getMyPasswordState = async (params, options) => {
963
+ return customFetch(getGetMyPasswordStateUrl(params), {
964
+ ...options,
965
+ method: "GET"
966
+ });
967
+ };
968
+ const getListMyProjectsUrl = (params) => {
969
+ const normalizedParams = new URLSearchParams();
970
+ Object.entries(params || {}).forEach(([key, value]) => {
971
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
972
+ });
973
+ const stringifiedParams = normalizedParams.toString();
974
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me/projects?${stringifiedParams}` : `${getProxyPath()}/users/me/projects`;
975
+ };
976
+ /**
977
+ * The projects the signed-in user holds an active grant on, either directly or
978
+ * through a team they are a member of. Ordered by project id and paged with an
979
+ * opaque cursor.
980
+ *
981
+ * This is not the same question as `queryProjects`, which answers with the one
982
+ * project the calling credential is bound to. Here the session is the caller
983
+ * and the grants are the answer, so the list spans projects.
984
+ *
985
+ * With `project_id`, the projects are listed only when the session belongs to
986
+ * that project. It names the project the session was signed in to, not one to
987
+ * list.
988
+ * @summary List the projects I can act on
989
+ */
990
+ const listMyProjects = async (params, options) => {
991
+ return customFetch(getListMyProjectsUrl(params), {
992
+ ...options,
993
+ method: "GET"
994
+ });
995
+ };
996
+ const getGetMyUserSchemaUrl = (params) => {
997
+ const normalizedParams = new URLSearchParams();
998
+ Object.entries(params || {}).forEach(([key, value]) => {
999
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1000
+ });
1001
+ const stringifiedParams = normalizedParams.toString();
1002
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me/schema?${stringifiedParams}` : `${getProxyPath()}/users/me/schema`;
1003
+ };
1004
+ /**
1005
+ * The schema the signed-in user's own record is validated against.
1006
+ *
1007
+ * With `project_id`, the schema is returned only when the session belongs to
1008
+ * that project.
1009
+ * @summary Get my user schema
1010
+ */
1011
+ const getMyUserSchema = async (params, options) => {
1012
+ return customFetch(getGetMyUserSchemaUrl(params), {
1013
+ ...options,
1014
+ method: "GET"
1015
+ });
1016
+ };
1017
+ const getListMyTeamsUrl = (params) => {
1018
+ const normalizedParams = new URLSearchParams();
1019
+ Object.entries(params || {}).forEach(([key, value]) => {
1020
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1021
+ });
1022
+ const stringifiedParams = normalizedParams.toString();
1023
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/users/me/teams?${stringifiedParams}` : `${getProxyPath()}/users/me/teams`;
1024
+ };
1025
+ /**
1026
+ * The signed-in user's own team roster, ordered by team name.
1027
+ *
1028
+ * With `project_id`, the teams are listed only when the session belongs to
1029
+ * that project.
1030
+ * @summary List the teams I belong to
1031
+ */
1032
+ const listMyTeams = async (params, options) => {
1033
+ return customFetch(getListMyTeamsUrl(params), {
1034
+ ...options,
1035
+ method: "GET"
1036
+ });
1037
+ };
1038
+ const getCreateFlowUrl = () => {
1039
+ return `${getProxyPath()}/flow`;
1040
+ };
1041
+ /**
1042
+ * Resolves a flow definition based on purpose + audience context and returns
1043
+ * the first capability step. Creates a new session implicitly unless
1044
+ * `session_id` is provided, together with that session's `session_token`
1045
+ * (for step-up / reauth on an existing session).
1046
+ *
1047
+ * The browser `Origin` header selects which deployment serves this attempt:
1048
+ * the gate admits the origin against the project's origin patterns and live
1049
+ * previews, the newest deployment to that exact origin is the target, and
1050
+ * that deployment's release supplies flow definitions, user schemas and
1051
+ * branding. The resolved deployment is sealed into the `_zflow` cookie so
1052
+ * later steps keep the same configuration. An origin that matches no pattern
1053
+ * answers `403` with `proj.origin_not_allowed`; one that matches a preview
1054
+ * pattern with no live preview answers `403` with `proj.preview_not_live`;
1055
+ * nothing deployed to the target answers `409` with `rel.not_deployed`; a
1056
+ * revoked release answers `409` with `rel.revoked`. A request with no
1057
+ * `Origin` passes the gate and still needs a deployment target.
1058
+ *
1059
+ * The response contains an `id` field — the flow handle. Use it as the path
1060
+ * parameter for all subsequent `/flow/{id}/submit` calls.
1061
+ *
1062
+ * The response also sets an encrypted `HttpOnly` cookie (`_zflow`) containing
1063
+ * the flow's orchestration state (current step, collected data, history).
1064
+ * The server is stateless between requests — all flow state lives in this
1065
+ * cookie. The browser sends it automatically on subsequent requests.
1066
+ * @summary Start a new flow
1067
+ */
1068
+ const createFlow = async (createFlowBody, options) => {
1069
+ const getHeaders = (h) => {
1070
+ if (!h) return {};
1071
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1072
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1073
+ const headers = {};
1074
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1075
+ return headers;
1076
+ };
1077
+ return customFetch(getCreateFlowUrl(), {
1078
+ ...options,
1079
+ method: "POST",
1080
+ headers: {
1081
+ "Content-Type": "application/json",
1082
+ ...getHeaders(options?.headers)
1083
+ },
1084
+ body: JSON.stringify(createFlowBody)
1085
+ });
1086
+ };
1087
+ const getGetFlowStepUrl = (id) => {
1088
+ return `${getProxyPath()}/flow/${encodeURIComponent(String(id))}`;
1089
+ };
1090
+ /**
1091
+ * Returns the current capability step without advancing the state machine.
1092
+ * Useful for page reloads or re-rendering after a network error.
1093
+ *
1094
+ * Reuses the deployment sealed into `_zflow` at `createFlow`; it does not
1095
+ * re-resolve from `Origin`. If that release was revoked since the attempt
1096
+ * started, the response is `409` with `rel.revoked`.
1097
+ * @summary Get current step (re-render)
1098
+ */
1099
+ const getFlowStep = async (id, options) => {
1100
+ return customFetch(getGetFlowStepUrl(id), {
1101
+ ...options,
1102
+ method: "GET"
1103
+ });
1104
+ };
1105
+ const getSubmitFlowStepUrl = (id) => {
1106
+ return `${getProxyPath()}/flow/${encodeURIComponent(String(id))}/submit`;
1107
+ };
1108
+ /**
1109
+ * Submits user input for the current step. The server validates,
1110
+ * processes (e.g., verifies a credential), advances the state machine
1111
+ * through any invisible steps, and returns the next visible step.
1112
+ *
1113
+ * The response sets an updated encrypted `HttpOnly` cookie (`_zflow`)
1114
+ * with the new flow state. The server is stateless — all orchestration
1115
+ * state is carried in this cookie between requests.
1116
+ *
1117
+ * **Important:** The `id` in the response may differ from the `id` used in
1118
+ * the request. This happens when a flow pivots (pushes a new flow onto the
1119
+ * stack) or when a stacked flow completes (auto-pops to the parent flow).
1120
+ * Always use the `id` from the latest response for the next request.
1121
+ *
1122
+ * ## Flow completion
1123
+ *
1124
+ * When `step.type` is `complete`, the flow is terminal. The `step.behavior`
1125
+ * field tells the frontend what to do:
1126
+ *
1127
+ * | `behavior` | Action |
1128
+ * |------------- |------------------------------------------------------------|
1129
+ * | `redirect` | Navigate to `redirect_uri` (OIDC/SAML auth request done). |
1130
+ * | `show` | Render the step as a success screen (e.g., registration). |
1131
+ *
1132
+ * A `complete` step is only returned when the **entire flow stack** is done.
1133
+ * If a stacked flow (e.g., recovery pivoted from login) finishes, the server
1134
+ * auto-pops to the parent flow and returns the parent's next step — the
1135
+ * frontend never sees a `complete` for intermediate flows.
1136
+ *
1137
+ * ## External sign-in
1138
+ *
1139
+ * `{action: "sso", sso_provider_id, return_target}` on a step that offers
1140
+ * `sso_providers` returns the engine-emitted `sso-redirect` step, whose
1141
+ * `redirect_url` the frontend navigates to.
1142
+ *
1143
+ * - The flow state does not change, but `_zflow` is re-sealed like on
1144
+ * every response, so its ten-minute window restarts at this submission;
1145
+ * the external sign-in and the return must complete within it.
1146
+ * - A second `Set-Cookie` line carries the browser-binding cookie the
1147
+ * callback checks: `HttpOnly`, `Path=/`, `SameSite=Lax`.
1148
+ * - On every host except http loopback it is `__Host-_zsso` with `Secure`.
1149
+ * - When the request host is http loopback (local development, where
1150
+ * Safari rejects `Secure`), it is `_zsso` with no `Secure`; the
1151
+ * `__Host-` prefix is dropped because it requires `Secure`.
1152
+ *
1153
+ * A connection whose `client_id` is a `${{ NAME }}` reference has it filled
1154
+ * from the project's variables. A provider the engine cannot start a
1155
+ * sign-in with, including a reference with no variable behind it,
1156
+ * re-renders the step with `error.sso_unavailable`.
1157
+ *
1158
+ * Reuses the deployment sealed into `_zflow` at `createFlow`; it does not
1159
+ * re-resolve from `Origin`. If that release was revoked since the attempt
1160
+ * started, the response is `409` with `rel.revoked`.
1161
+ * @summary Submit step data and advance
1162
+ */
1163
+ const submitFlowStep = async (id, submitFlowStepBody, options) => {
1164
+ const getHeaders = (h) => {
1165
+ if (!h) return {};
1166
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1167
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1168
+ const headers = {};
1169
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1170
+ return headers;
1171
+ };
1172
+ return customFetch(getSubmitFlowStepUrl(id), {
1173
+ ...options,
1174
+ method: "POST",
1175
+ headers: {
1176
+ "Content-Type": "application/json",
1177
+ ...getHeaders(options?.headers)
1178
+ },
1179
+ body: JSON.stringify(submitFlowStepBody)
1180
+ });
1181
+ };
1182
+ const getCreateAuthAttemptUrl = () => {
1183
+ return `${getProxyPath()}/auth_attempts`;
1184
+ };
1185
+ /**
1186
+ * Starts a new authentication attempt. This is the entry point for the auth_attempts state machine.
1187
+ *
1188
+ * An attempt is an ephemeral (15-minute TTL) state machine that drives a single authentication round.
1189
+ * It accepts factor challenges, verifies proofs, and completes into a session or handoff token.
1190
+ *
1191
+ * Accepts a project_id and challenge_nonce (from POST /bootstrap/challenge). For step-up re-auth,
1192
+ * also include session_id and that session's session_token to add factors to an existing session.
1193
+ *
1194
+ * The project comes from the project secret. A body `project_id` that disagrees
1195
+ * answers `403` with `proj.mismatch`. The attempt resolves a deployment the
1196
+ * same way as other runtime operations and seals it; with no browser `Origin`
1197
+ * and nothing deployed to the resolved target the response is `409` with
1198
+ * `rel.not_deployed`. A revoked release answers `409` with `rel.revoked`.
1199
+ * @summary Create a new authentication attempt
1200
+ */
1201
+ const createAuthAttempt = async (createAuthAttemptBody, options) => {
1202
+ const getHeaders = (h) => {
1203
+ if (!h) return {};
1204
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1205
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1206
+ const headers = {};
1207
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1208
+ return headers;
1209
+ };
1210
+ return customFetch(getCreateAuthAttemptUrl(), {
1211
+ ...options,
1212
+ method: "POST",
1213
+ headers: {
1214
+ "Content-Type": "application/json",
1215
+ ...getHeaders(options?.headers)
1216
+ },
1217
+ body: JSON.stringify(createAuthAttemptBody)
1218
+ });
1219
+ };
1220
+ const getGetAuthAttemptUrl = (attemptId) => {
1221
+ return `${getProxyPath()}/auth_attempts/${encodeURIComponent(String(attemptId))}`;
1222
+ };
1223
+ /**
1224
+ * Polls the current state of an authentication attempt.
1225
+ *
1226
+ * Returns the attempt's state, available factors for the next challenge,
1227
+ * challenges issued so far, and any errors preventing progress.
1228
+ *
1229
+ * Use this for polling during long-running factor verifications (e.g., waiting for
1230
+ * a federated IdP callback or a device flow).
1231
+ *
1232
+ * Reuses the deployment sealed when the attempt was created. If that release
1233
+ * was revoked since, the response is `409` with `rel.revoked`.
1234
+ * @summary Get authentication attempt state
1235
+ */
1236
+ const getAuthAttempt = async (attemptId, options) => {
1237
+ return customFetch(getGetAuthAttemptUrl(attemptId), {
1238
+ ...options,
1239
+ method: "GET"
1240
+ });
1241
+ };
1242
+ const getIssueChallengeUrl = (attemptId) => {
1243
+ return `${getProxyPath()}/auth_attempts/${encodeURIComponent(String(attemptId))}/challenges`;
1244
+ };
1245
+ /**
1246
+ * Issues a single-factor verification challenge within an auth attempt.
1247
+ *
1248
+ * This advances the authentication state machine by requesting a specific factor method
1249
+ * (password, passkey, TOTP, OTP via SMS, etc.). The server responds with challenge details
1250
+ * including method, metadata, and any UI hints. The client then verifies the proof
1251
+ * by calling POST /auth_attempts/{attempt_id}/challenges/{challenge_id}/verify.
1252
+ *
1253
+ * Reuses the deployment sealed when the attempt was created. If that release
1254
+ * was revoked since, the response is `409` with `rel.revoked`.
1255
+ * @summary Issue a factor challenge
1256
+ */
1257
+ const issueChallenge = async (attemptId, issueChallengeBody, options) => {
1258
+ const getHeaders = (h) => {
1259
+ if (!h) return {};
1260
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1261
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1262
+ const headers = {};
1263
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1264
+ return headers;
1265
+ };
1266
+ return customFetch(getIssueChallengeUrl(attemptId), {
1267
+ ...options,
1268
+ method: "POST",
1269
+ headers: {
1270
+ "Content-Type": "application/json",
1271
+ ...getHeaders(options?.headers)
1272
+ },
1273
+ body: JSON.stringify(issueChallengeBody)
1274
+ });
1275
+ };
1276
+ const getVerifyChallengeProofUrl = (attemptId, challengeId) => {
1277
+ return `${getProxyPath()}/auth_attempts/${encodeURIComponent(String(attemptId))}/challenges/${encodeURIComponent(String(challengeId))}/verify`;
1278
+ };
1279
+ /**
1280
+ * Submits a proof (credential, code, assertion) to verify a factor challenge.
1281
+ *
1282
+ * The proof format depends on the challenge method. For example:
1283
+ * - `password` method: { password: "…" }
1284
+ * - `totp` method: { totp: { code: "123456" } }
1285
+ * - `passkey` method: { passkey: { assertion: "…" } }
1286
+ * - `recovery_code` method: { recovery_code: "…" }
1287
+ *
1288
+ * On successful verification, the factor is written to the auth attempt.
1289
+ * The attempt moves to the next pending challenge or completes if all required factors are verified.
1290
+ *
1291
+ * Reuses the deployment sealed when the attempt was created. If that release
1292
+ * was revoked since, the response is `409` with `rel.revoked`.
1293
+ * @summary Verify a factor proof
1294
+ */
1295
+ const verifyChallengeProof = async (attemptId, challengeId, verifyChallengeProofBody, options) => {
1296
+ const getHeaders = (h) => {
1297
+ if (!h) return {};
1298
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1299
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1300
+ const headers = {};
1301
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1302
+ return headers;
1303
+ };
1304
+ return customFetch(getVerifyChallengeProofUrl(attemptId, challengeId), {
1305
+ ...options,
1306
+ method: "POST",
1307
+ headers: {
1308
+ "Content-Type": "application/json",
1309
+ ...getHeaders(options?.headers)
1310
+ },
1311
+ body: JSON.stringify(verifyChallengeProofBody)
1312
+ });
1313
+ };
1314
+ const getCreateHandoffUrl = (attemptId) => {
1315
+ return `${getProxyPath()}/auth_attempts/${encodeURIComponent(String(attemptId))}/handoff`;
1316
+ };
1317
+ /**
1318
+ * Completes the authentication attempt and mints a `handoff_token`.
1319
+ *
1320
+ * Call this after all required factors have been verified and the attempt is in `completed` state.
1321
+ * The handoff token is short-lived (≤60 seconds) and must be exchanged at
1322
+ * POST /sessions/exchange to receive the final session and session_token.
1323
+ *
1324
+ * The handoff token is:
1325
+ * - Single-use (atomic exchange, no retry)
1326
+ * - Audience-bound (requires matching project key for exchange)
1327
+ * - Idempotency-safe within a 5-minute window (see conventions)
1328
+ *
1329
+ * Reuses the deployment sealed when the attempt was created. If that release
1330
+ * was revoked since, the response is `409` with `rel.revoked`.
1331
+ * @summary Complete authentication and create handoff token
1332
+ */
1333
+ const createHandoff = async (attemptId, options) => {
1334
+ return customFetch(getCreateHandoffUrl(attemptId), {
1335
+ ...options,
1336
+ method: "POST"
1337
+ });
1338
+ };
1339
+ const getCreateProjectUrl = () => {
1340
+ return `${getProxyPath()}/projects`;
1341
+ };
1342
+ /**
1343
+ * Creates a project and returns its project secret and preview secret, which no
1344
+ * other endpoint returns.
1345
+ *
1346
+ * The request needs no credential and is rate-limited. Unless `seed_defaults` is
1347
+ * `false`, the project starts with a default user schema and flow; the CLI turns
1348
+ * that off and uploads its own from `.zitadel/`.
1349
+ * @summary Create project
1350
+ */
1351
+ const createProject = async (createProjectBody, options) => {
1352
+ const getHeaders = (h) => {
1353
+ if (!h) return {};
1354
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1355
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1356
+ const headers = {};
1357
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1358
+ return headers;
1359
+ };
1360
+ return customFetch(getCreateProjectUrl(), {
1361
+ ...options,
1362
+ method: "POST",
1363
+ headers: {
1364
+ "Content-Type": "application/json",
1365
+ ...getHeaders(options?.headers)
1366
+ },
1367
+ body: JSON.stringify(createProjectBody)
1368
+ });
1369
+ };
1370
+ const getQueryProjectsUrl = () => {
1371
+ return `${getProxyPath()}/projects/query`;
1372
+ };
1373
+ /**
1374
+ * Returns the project the project secret belongs to, as a page of at most one
1375
+ * project.
1376
+ *
1377
+ * A credential is scoped to one project until ADR 036 widens it, so the filters
1378
+ * and sorting apply to that project alone. The projects a signed-in person can
1379
+ * act on are listed by `GET /users/me/projects`.
1380
+ * @summary Query projects
1381
+ */
1382
+ const queryProjects = async (queryProjectsBody, options) => {
1383
+ const getHeaders = (h) => {
1384
+ if (!h) return {};
1385
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1386
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1387
+ const headers = {};
1388
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1389
+ return headers;
1390
+ };
1391
+ return customFetch(getQueryProjectsUrl(), {
1392
+ ...options,
1393
+ method: "POST",
1394
+ headers: {
1395
+ "Content-Type": "application/json",
1396
+ ...getHeaders(options?.headers)
1397
+ },
1398
+ body: JSON.stringify(queryProjectsBody)
1399
+ });
1400
+ };
1401
+ const getGetProjectUrl = (projectId) => {
1402
+ return `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}`;
1403
+ };
1404
+ /**
1405
+ * Returns the current state of a project.
1406
+ * @summary Get project
1407
+ */
1408
+ const getProject = async (projectId, options) => {
1409
+ return customFetch(getGetProjectUrl(projectId), {
1410
+ ...options,
1411
+ method: "GET"
1412
+ });
1413
+ };
1414
+ const getPatchProjectUrl = (projectId) => {
1415
+ return `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}`;
1416
+ };
1417
+ /**
1418
+ * Updates the state of a project.
1419
+ * @summary Update project
1420
+ */
1421
+ const patchProject = async (projectId, patchProjectBody, options) => {
1422
+ const getHeaders = (h) => {
1423
+ if (!h) return {};
1424
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1425
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1426
+ const headers = {};
1427
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1428
+ return headers;
1429
+ };
1430
+ return customFetch(getPatchProjectUrl(projectId), {
1431
+ ...options,
1432
+ method: "PATCH",
1433
+ headers: {
1434
+ "Content-Type": "application/json",
1435
+ ...getHeaders(options?.headers)
1436
+ },
1437
+ body: JSON.stringify(patchProjectBody)
1438
+ });
1439
+ };
1440
+ const getInitClaimUrl = (projectId) => {
1441
+ return `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/claim/init`;
1442
+ };
1443
+ /**
1444
+ * Starts a claim challenge for an unclaimed project. Authenticated by the
1445
+ * project secret, this mints a single-use, short-lived challenge and returns
1446
+ * the `claim_url` the developer opens in a browser to complete the claim,
1447
+ * together with the `challenge_id` the CLI polls with. The exact expiry is
1448
+ * carried by `expires_at` on the response.
1449
+ * @summary Initialize a project claim
1450
+ */
1451
+ const initClaim = async (projectId, options) => {
1452
+ return customFetch(getInitClaimUrl(projectId), {
1453
+ ...options,
1454
+ method: "POST"
1455
+ });
1456
+ };
1457
+ const getGetClaimStatusUrl = (projectId, params) => {
1458
+ const normalizedParams = new URLSearchParams();
1459
+ Object.entries(params || {}).forEach(([key, value]) => {
1460
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1461
+ });
1462
+ const stringifiedParams = normalizedParams.toString();
1463
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/claim/status?${stringifiedParams}` : `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/claim/status`;
1464
+ };
1465
+ /**
1466
+ * Polled by the CLI while a browser completes the claim. Authorized by the
1467
+ * project secret that initiated the challenge. Returns `pending`, or
1468
+ * `completed` with the owning team, the claim timestamp, and the dashboard
1469
+ * URL once the project is claimed. The claim grant, not the polled
1470
+ * challenge, is the source of truth: a project claimed through another
1471
+ * concurrent challenge also reports `completed`, and a completed claim
1472
+ * keeps reporting `completed` past this challenge's expiry and past the
1473
+ * project's claim window.
1474
+ * @summary Get claim status
1475
+ */
1476
+ const getClaimStatus = async (projectId, params, options) => {
1477
+ return customFetch(getGetClaimStatusUrl(projectId, params), {
1478
+ ...options,
1479
+ method: "GET"
1480
+ });
1481
+ };
1482
+ const getCompleteClaimUrl = (projectId) => {
1483
+ return `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/claim/complete`;
1484
+ };
1485
+ /**
1486
+ * Called by the browser after the developer authenticates on the claim page.
1487
+ * Authenticated by the `__nextgen_session` cookie, it attaches the project to
1488
+ * the developer's personal team using the `challenge_id` from the claim URL as
1489
+ * its single-use, browser-safe authorization.
1490
+ * @summary Complete a project claim
1491
+ */
1492
+ const completeClaim = async (projectId, completeClaimBody, options) => {
1493
+ const getHeaders = (h) => {
1494
+ if (!h) return {};
1495
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1496
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1497
+ const headers = {};
1498
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1499
+ return headers;
1500
+ };
1501
+ return customFetch(getCompleteClaimUrl(projectId), {
1502
+ ...options,
1503
+ method: "POST",
1504
+ headers: {
1505
+ "Content-Type": "application/json",
1506
+ ...getHeaders(options?.headers)
1507
+ },
1508
+ body: JSON.stringify(completeClaimBody)
1509
+ });
1510
+ };
1511
+ const getGetClaimWindowUrl = (projectId, params) => {
1512
+ const normalizedParams = new URLSearchParams();
1513
+ Object.entries(params || {}).forEach(([key, value]) => {
1514
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1515
+ });
1516
+ const stringifiedParams = normalizedParams.toString();
1517
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/claim/window?${stringifiedParams}` : `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/claim/window`;
1518
+ };
1519
+ /**
1520
+ * Read by the claim page in the browser to show how long is left to claim the
1521
+ * project. Unauthenticated by design: the claim page runs this before the
1522
+ * developer has signed in, and holding the `challenge_id` from the claim URL
1523
+ * is the authorization — the same capability `claim/complete` accepts. It
1524
+ * reveals only the window, never the project itself, and unlike
1525
+ * `claim/complete` it spends nothing, so a reload is free.
1526
+ * @summary Get the claim window for a project
1527
+ */
1528
+ const getClaimWindow = async (projectId, params, options) => {
1529
+ return customFetch(getGetClaimWindowUrl(projectId, params), {
1530
+ ...options,
1531
+ method: "GET"
1532
+ });
1533
+ };
1534
+ const getAddOriginUrl = (projectId) => {
1535
+ return `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/origins`;
1536
+ };
1537
+ /**
1538
+ * Adds one `{pattern, kind}` to the project's origins. A primary pattern
1539
+ * must be an exact URL (no wildcard). Preview patterns may include a single
1540
+ * DNS-label wildcard. Adding a pattern that already exists with the same
1541
+ * kind is idempotent and answers 201 with the stored origin.
1542
+ * @summary Add an origin pattern
1543
+ */
1544
+ const addOrigin = async (projectId, addOriginBody, options) => {
1545
+ const getHeaders = (h) => {
1546
+ if (!h) return {};
1547
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1548
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1549
+ const headers = {};
1550
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1551
+ return headers;
1552
+ };
1553
+ return customFetch(getAddOriginUrl(projectId), {
1554
+ ...options,
1555
+ method: "POST",
1556
+ headers: {
1557
+ "Content-Type": "application/json",
1558
+ ...getHeaders(options?.headers)
1559
+ },
1560
+ body: JSON.stringify(addOriginBody)
1561
+ });
1562
+ };
1563
+ const getRemoveOriginUrl = (projectId) => {
1564
+ return `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/origins/remove`;
1565
+ };
1566
+ /**
1567
+ * Removes one pattern from the project's origins. Requests from URLs only
1568
+ * that pattern admitted are refused from then on; live previews and
1569
+ * deployment history are untouched. Removing a pattern that is already
1570
+ * absent is idempotent and answers 204.
1571
+ * @summary Remove an origin pattern
1572
+ */
1573
+ const removeOrigin = async (projectId, removeOriginBody, options) => {
1574
+ const getHeaders = (h) => {
1575
+ if (!h) return {};
1576
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1577
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1578
+ const headers = {};
1579
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1580
+ return headers;
1581
+ };
1582
+ return customFetch(getRemoveOriginUrl(projectId), {
1583
+ ...options,
1584
+ method: "POST",
1585
+ headers: {
1586
+ "Content-Type": "application/json",
1587
+ ...getHeaders(options?.headers)
1588
+ },
1589
+ body: JSON.stringify(removeOriginBody)
1590
+ });
1591
+ };
1592
+ const getListPreviewsUrl = (projectId, params) => {
1593
+ const normalizedParams = new URLSearchParams();
1594
+ Object.entries(params || {}).forEach(([key, value]) => {
1595
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1596
+ });
1597
+ const stringifiedParams = normalizedParams.toString();
1598
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/previews?${stringifiedParams}` : `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/previews`;
1599
+ };
1600
+ /**
1601
+ * Lists the project's live previews, newest first by `created_at`. An
1602
+ * expired or removed preview is not listed; what was deployed to it stays
1603
+ * in `GET /deployments`.
1604
+ * @summary List previews
1605
+ */
1606
+ const listPreviews = async (projectId, params, options) => {
1607
+ return customFetch(getListPreviewsUrl(projectId, params), {
1608
+ ...options,
1609
+ method: "GET"
1610
+ });
1611
+ };
1612
+ const getRemovePreviewUrl = (projectId) => {
1613
+ return `${getProxyPath()}/projects/${encodeURIComponent(String(projectId))}/previews/remove`;
1614
+ };
1615
+ /**
1616
+ * Ends a preview before it expires: the URL stops being served at once.
1617
+ * The deployments to it stay in the history.
1618
+ *
1619
+ * Idempotent: a URL with no live preview, including one that has already
1620
+ * expired or was removed before, answers `204` too, so a cleanup that
1621
+ * races the expiry still succeeds.
1622
+ *
1623
+ * The URL travels in the body rather than the path because an origin
1624
+ * contains `/`.
1625
+ * @summary Remove a preview
1626
+ */
1627
+ const removePreview = async (projectId, removePreviewBody, options) => {
1628
+ const getHeaders = (h) => {
1629
+ if (!h) return {};
1630
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1631
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1632
+ const headers = {};
1633
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1634
+ return headers;
1635
+ };
1636
+ return customFetch(getRemovePreviewUrl(projectId), {
1637
+ ...options,
1638
+ method: "POST",
1639
+ headers: {
1640
+ "Content-Type": "application/json",
1641
+ ...getHeaders(options?.headers)
1642
+ },
1643
+ body: JSON.stringify(removePreviewBody)
1644
+ });
1645
+ };
1646
+ const getCreateSessionUrl = () => {
1647
+ return `${getProxyPath()}/sessions`;
1648
+ };
1649
+ /**
1650
+ * Creates an anonymous session shell with no user and no factors (`state: building`).
1651
+ *
1652
+ * This is optional — an `auth_attempt` will create a session implicitly if none is provided.
1653
+ * Use this explicitly when you want to:
1654
+ * - Pre-allocate a `session_id` before the user is known, so device/telemetry signals
1655
+ * can be correlated with the eventual authenticated session from the start.
1656
+ * - Track anonymous state (bot detection, device fingerprint) that survives until authentication.
1657
+ *
1658
+ * Creating a session is an app-plane operation on the project credential
1659
+ * (`session.write`). The returned `session_token` is a session credential for the
1660
+ * end-user client, not a management scope: it is delivered as the
1661
+ * `__nextgen_session` cookie and authorises the self-service operations
1662
+ * `GET /sessions/me` and `DELETE /sessions/me` (`nextgenSession` scheme). The
1663
+ * by-id operations `GET /sessions/{session_id}` and `DELETE /sessions/{session_id}`
1664
+ * are operator endpoints and require `session.read` / `session.delete` instead.
1665
+ *
1666
+ * The `session_token` is superseded when a handoff exchange completes — clients must
1667
+ * replace it at that point.
1668
+ *
1669
+ * Anonymous sessions expire aggressively (10-minute TTL). The TTL resets to the configured
1670
+ * full session TTL when the first authentication factor is written via a completing `auth_attempt`.
1671
+ * @summary Create an anonymous session shell
1672
+ */
1673
+ const createSession = async (createSessionBody, options) => {
1674
+ const getHeaders = (h) => {
1675
+ if (!h) return {};
1676
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1677
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1678
+ const headers = {};
1679
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1680
+ return headers;
1681
+ };
1682
+ return customFetch(getCreateSessionUrl(), {
1683
+ ...options,
1684
+ method: "POST",
1685
+ headers: {
1686
+ "Content-Type": "application/json",
1687
+ ...getHeaders(options?.headers)
1688
+ },
1689
+ body: JSON.stringify(createSessionBody)
1690
+ });
1691
+ };
1692
+ const getQuerySessionsUrl = (params) => {
1693
+ const normalizedParams = new URLSearchParams();
1694
+ Object.entries(params || {}).forEach(([key, value]) => {
1695
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1696
+ });
1697
+ const stringifiedParams = normalizedParams.toString();
1698
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/sessions/query?${stringifiedParams}` : `${getProxyPath()}/sessions/query`;
1699
+ };
1700
+ /**
1701
+ * Returns the sessions of a project, paginated with a cursor.
1702
+ * Sessions of every lifecycle state are returned; each carries its `state`.
1703
+ * Requires `session.read` permission.
1704
+ * @summary Query sessions
1705
+ */
1706
+ const querySessions = async (querySessionsBody, params, options) => {
1707
+ const getHeaders = (h) => {
1708
+ if (!h) return {};
1709
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1710
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1711
+ const headers = {};
1712
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1713
+ return headers;
1714
+ };
1715
+ return customFetch(getQuerySessionsUrl(params), {
1716
+ ...options,
1717
+ method: "POST",
1718
+ headers: {
1719
+ "Content-Type": "application/json",
1720
+ ...getHeaders(options?.headers)
1721
+ },
1722
+ body: JSON.stringify(querySessionsBody)
1723
+ });
1724
+ };
1725
+ const getExchangeHandoffUrl = (params) => {
1726
+ const normalizedParams = new URLSearchParams();
1727
+ Object.entries(params || {}).forEach(([key, value]) => {
1728
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1729
+ });
1730
+ const stringifiedParams = normalizedParams.toString();
1731
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/sessions/exchange?${stringifiedParams}` : `${getProxyPath()}/sessions/exchange`;
1732
+ };
1733
+ /**
1734
+ * Consumes a one-time `handoff_token` minted by `POST /auth_attempts/{id}/handoff`
1735
+ * and returns the resulting session and a `session_token`.
1736
+ *
1737
+ * The server resolves the originating `auth_attempt` from the token and then:
1738
+ *
1739
+ * | Originating auth_attempt | Outcome |
1740
+ * |---|---|
1741
+ * | No `session_id` | A new authenticated session is **created**. |
1742
+ * | `session_id` points to an anonymous shell | Existing session is **upgraded** — user and factors written in, TTL reset to full session TTL. |
1743
+ * | `session_id` points to an active session (step-up) | Existing session is **upgraded** — new factors merged, `assurance_levels[]` expanded. |
1744
+ *
1745
+ * The response shape is identical in all three cases.
1746
+ *
1747
+ * The `session_token` supersedes any previously issued `session_token` for the same session.
1748
+ * Clients must replace their stored token at this point.
1749
+ *
1750
+ * Requires a project service key (OAuth2 client credentials).
1751
+ *
1752
+ * The project comes from the project secret. A query `project_id` that
1753
+ * disagrees answers `403` with `proj.mismatch`. The exchange resolves a
1754
+ * deployment the same way as other runtime operations; with no browser
1755
+ * `Origin` and nothing deployed to the resolved target the response is
1756
+ * `409` with `rel.not_deployed`. A revoked release answers `409` with
1757
+ * `rel.revoked`.
1758
+ * @summary Exchange handoff token for a session
1759
+ */
1760
+ const exchangeHandoff = async (exchangeHandoffBody, params, options) => {
1761
+ const getHeaders = (h) => {
1762
+ if (!h) return {};
1763
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1764
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1765
+ const headers = {};
1766
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1767
+ return headers;
1768
+ };
1769
+ return customFetch(getExchangeHandoffUrl(params), {
1770
+ ...options,
1771
+ method: "POST",
1772
+ headers: {
1773
+ "Content-Type": "application/json",
1774
+ ...getHeaders(options?.headers)
1775
+ },
1776
+ body: JSON.stringify(exchangeHandoffBody)
1777
+ });
1778
+ };
1779
+ const getGetSessionUrl = (sessionId) => {
1780
+ return `${getProxyPath()}/sessions/${encodeURIComponent(String(sessionId))}`;
1781
+ };
1782
+ /**
1783
+ * Returns the current state of a session including its factors and all currently
1784
+ * satisfied assurance levels.
1785
+ *
1786
+ * `assurance_levels[]` may shrink over time as factor freshness windows expire,
1787
+ * without the session itself expiring. Use step-up authentication (a new `auth_attempt`
1788
+ * against the same `session_id`) to restore a dropped assurance level.
1789
+ * @summary Get session state
1790
+ */
1791
+ const getSession = async (sessionId, options) => {
1792
+ return customFetch(getGetSessionUrl(sessionId), {
1793
+ ...options,
1794
+ method: "GET"
1795
+ });
1796
+ };
1797
+ const getRevokeSessionUrl = (sessionId) => {
1798
+ return `${getProxyPath()}/sessions/${encodeURIComponent(String(sessionId))}`;
1799
+ };
1800
+ /**
1801
+ * Permanently deletes the session, terminating it immediately.
1802
+ *
1803
+ * This is the operator revoke path and requires the `session.delete` scope on a
1804
+ * project-bound credential. End-user logout with the `__nextgen_session` cookie is
1805
+ * `DELETE /sessions/me` (`nextgenSession` scheme).
1806
+ *
1807
+ * Idempotent: deleting a session that does not exist (or was already deleted)
1808
+ * still returns 204. After deletion, any tokens derived from the session are
1809
+ * invalidated.
1810
+ * @summary Revoke session
1811
+ */
1812
+ const revokeSession = async (sessionId, options) => {
1813
+ return customFetch(getRevokeSessionUrl(sessionId), {
1814
+ ...options,
1815
+ method: "DELETE"
1816
+ });
1817
+ };
1818
+ const getGetMySessionUrl = (params) => {
1819
+ const normalizedParams = new URLSearchParams();
1820
+ Object.entries(params || {}).forEach(([key, value]) => {
1821
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1822
+ });
1823
+ const stringifiedParams = normalizedParams.toString();
1824
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/sessions/me?${stringifiedParams}` : `${getProxyPath()}/sessions/me`;
1825
+ };
1826
+ /**
1827
+ * Returns the current state of the current session including its factors and all currently
1828
+ * satisfied assurance levels.
1829
+ *
1830
+ * With `project_id`, the session is returned only when it belongs to that project.
1831
+ *
1832
+ * `assurance_levels[]` may shrink over time as factor freshness windows expire,
1833
+ * without the session itself expiring. Use step-up authentication (a new `auth_attempt`
1834
+ * against the same `session_id`) to restore a dropped assurance level.
1835
+ * @summary Get my session state
1836
+ */
1837
+ const getMySession = async (params, options) => {
1838
+ return customFetch(getGetMySessionUrl(params), {
1839
+ ...options,
1840
+ method: "GET"
1841
+ });
1842
+ };
1843
+ const getRevokeMySessionUrl = (params) => {
1844
+ const normalizedParams = new URLSearchParams();
1845
+ Object.entries(params || {}).forEach(([key, value]) => {
1846
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1847
+ });
1848
+ const stringifiedParams = normalizedParams.toString();
1849
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/sessions/me?${stringifiedParams}` : `${getProxyPath()}/sessions/me`;
1850
+ };
1851
+ /**
1852
+ * Logs out by permanently deleting the session.
1853
+ *
1854
+ * The `__nextgen_session` cookie issued at creation (or superseded by a handoff
1855
+ * exchange) is required, with the session's token from `GET /sessions/me/csrf`
1856
+ * in the `X-Zitadel-CSRF` header. Idempotent: if the session is already gone
1857
+ * this still returns 204. Any tokens derived from the session are invalidated,
1858
+ * and the cookie itself is cleared in the response.
1859
+ *
1860
+ * With `project_id`, only a session of that project is deleted. A session of
1861
+ * another project is left alone, and so is its cookie.
1862
+ * @summary Revoke my session
1863
+ */
1864
+ const revokeMySession = async (params, options) => {
1865
+ return customFetch(getRevokeMySessionUrl(params), {
1866
+ ...options,
1867
+ method: "DELETE"
1868
+ });
1869
+ };
1870
+ const getGetMySessionCsrfTokenUrl = (params) => {
1871
+ const normalizedParams = new URLSearchParams();
1872
+ Object.entries(params || {}).forEach(([key, value]) => {
1873
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1874
+ });
1875
+ const stringifiedParams = normalizedParams.toString();
1876
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/sessions/me/csrf?${stringifiedParams}` : `${getProxyPath()}/sessions/me/csrf`;
1877
+ };
1878
+ /**
1879
+ * Returns the session-bound token for cross-site request forgery protection
1880
+ * (ADR 053 §5). Browser code sends it in the `X-Zitadel-CSRF` header on the
1881
+ * state-changing requests the session cookie authenticates that require it
1882
+ * — see the `nextgenSession` scheme. It authorizes nothing on its own: the
1883
+ * HttpOnly cookie is still the credential, and a cross-site page cannot
1884
+ * read this response. It stays the same for the life of the session, so a
1885
+ * client fetches it once per session.
1886
+ *
1887
+ * With `project_id`, the token is returned only when the session belongs to
1888
+ * that project.
1889
+ * @summary Get my session's CSRF token
1890
+ */
1891
+ const getMySessionCsrfToken = async (params, options) => {
1892
+ return customFetch(getGetMySessionCsrfTokenUrl(params), {
1893
+ ...options,
1894
+ method: "GET"
1895
+ });
1896
+ };
1897
+ const getCreateSchemaUrl = (params) => {
1898
+ const normalizedParams = new URLSearchParams();
1899
+ Object.entries(params || {}).forEach(([key, value]) => {
1900
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1901
+ });
1902
+ const stringifiedParams = normalizedParams.toString();
1903
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/schemas?${stringifiedParams}` : `${getProxyPath()}/schemas`;
1904
+ };
1905
+ /**
1906
+ * Create a new schema. The optional `$id` field is the JSON Schema document
1907
+ * URI used to identify the schema in future requests (GitOps-stable identity,
1908
+ * not a free-form resource primary key). When `$id` is omitted, the server
1909
+ * generates a `sch_*` URL. When provided, `$id` must be unique within the
1910
+ * project and should ideally be a valid URI pointing at where the schema can
1911
+ * be accessed.
1912
+ *
1913
+ * The schema can either be a concrete schema, e.g. a user schema, or a
1914
+ * schema-url which will be resolved by the server.
1915
+ * @summary Create new schema
1916
+ */
1917
+ const createSchema = async (createSchemaBody, params, options) => {
1918
+ const getHeaders = (h) => {
1919
+ if (!h) return {};
1920
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
1921
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
1922
+ const headers = {};
1923
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
1924
+ return headers;
1925
+ };
1926
+ return customFetch(getCreateSchemaUrl(params), {
1927
+ ...options,
1928
+ method: "POST",
1929
+ headers: {
1930
+ "Content-Type": "application/json",
1931
+ ...getHeaders(options?.headers)
1932
+ },
1933
+ body: JSON.stringify(createSchemaBody)
1934
+ });
1935
+ };
1936
+ const getListSchemasUrl = (params) => {
1937
+ const normalizedParams = new URLSearchParams();
1938
+ Object.entries(params || {}).forEach(([key, value]) => {
1939
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1940
+ });
1941
+ const stringifiedParams = normalizedParams.toString();
1942
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/schemas?${stringifiedParams}` : `${getProxyPath()}/schemas`;
1943
+ };
1944
+ /**
1945
+ * Retrieve a list of all schemas available in the system. This endpoint
1946
+ * supports pagination and filtering based on schema attributes.
1947
+ * @summary List all schemas
1948
+ */
1949
+ const listSchemas = async (params, options) => {
1950
+ return customFetch(getListSchemasUrl(params), {
1951
+ ...options,
1952
+ method: "GET"
1953
+ });
1954
+ };
1955
+ const getGetSchemaByIdUrl = (id, params) => {
1956
+ const normalizedParams = new URLSearchParams();
1957
+ Object.entries(params || {}).forEach(([key, value]) => {
1958
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
1959
+ });
1960
+ const stringifiedParams = normalizedParams.toString();
1961
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/schemas/${encodeURIComponent(String(id))}?${stringifiedParams}` : `${getProxyPath()}/schemas/${encodeURIComponent(String(id))}`;
1962
+ };
1963
+ /**
1964
+ * Get a schema by its ID. A schema ID identifies one immutable revision, so
1965
+ * this returns exactly that revision. To find the current revision of an
1966
+ * object type, list with `revisions=latest`.
1967
+ *
1968
+ * Schema IDs are unique within a project, not across projects (the seeded
1969
+ * default schema carries the same `$id` in every project). A Console
1970
+ * session that manages more than one project names the project with
1971
+ * `project_id`; without it, the ID is resolved in the credential's own
1972
+ * project when it is ambiguous. A project secret always resolves in its
1973
+ * own project and ignores `project_id`.
1974
+ * @summary Get schema by ID
1975
+ */
1976
+ const getSchemaById = async (id, params, options) => {
1977
+ return customFetch(getGetSchemaByIdUrl(id, params), {
1978
+ ...options,
1979
+ method: "GET"
1980
+ });
1981
+ };
1982
+ const getCreateFlowDefinitionUrl = () => {
1983
+ return `${getProxyPath()}/flow_definitions`;
1984
+ };
1985
+ /**
1986
+ * Publishes a new flow definition revision.
1987
+ * Flow definitions are templates that define the sequence of steps (capabilities)
1988
+ * for a particular user journey (e.g., registration, login, password reset).
1989
+ *
1990
+ * Flow definitions are created based on the flow definition schema, which includes the flow's purpose, audience, and the steps involved.
1991
+ *
1992
+ * Every call allocates a new opaque id. Revisions of one flow share its
1993
+ * `name`; posting a definition under an existing `name` publishes a new
1994
+ * revision of that flow, it is not a conflict. List with `name` to see a
1995
+ * flow's revisions, newest by creation time first.
1996
+ * @summary Create a new flow definition
1997
+ */
1998
+ const createFlowDefinition = async (createFlowDefinitionBody, options) => {
1999
+ const getHeaders = (h) => {
2000
+ if (!h) return {};
2001
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
2002
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2003
+ const headers = {};
2004
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2005
+ return headers;
2006
+ };
2007
+ return customFetch(getCreateFlowDefinitionUrl(), {
2008
+ ...options,
2009
+ method: "POST",
2010
+ headers: {
2011
+ "Content-Type": "application/json",
2012
+ ...getHeaders(options?.headers)
2013
+ },
2014
+ body: JSON.stringify(createFlowDefinitionBody)
2015
+ });
2016
+ };
2017
+ const getListFlowDefinitionsUrl = (params) => {
2018
+ const normalizedParams = new URLSearchParams();
2019
+ Object.entries(params || {}).forEach(([key, value]) => {
2020
+ if (Array.isArray(value) && ["expand"].includes(key)) {
2021
+ value.forEach((v) => {
2022
+ normalizedParams.append(key, v === null ? "null" : String(v));
2023
+ });
2024
+ return;
2025
+ }
2026
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2027
+ });
2028
+ const stringifiedParams = normalizedParams.toString();
2029
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/flow_definitions?${stringifiedParams}` : `${getProxyPath()}/flow_definitions`;
2030
+ };
2031
+ /**
2032
+ * Retrieves a list of all flow definitions, newest by creation time first.
2033
+ * This endpoint can be used to view existing flow definitions and their configurations.
2034
+ * Filter by `name` to list the revisions of one flow.
2035
+ * @summary List flow definitions
2036
+ */
2037
+ const listFlowDefinitions = async (params, options) => {
2038
+ return customFetch(getListFlowDefinitionsUrl(params), {
2039
+ ...options,
2040
+ method: "GET"
2041
+ });
2042
+ };
2043
+ const getGetFlowDefinitionUrl = (id) => {
2044
+ return `${getProxyPath()}/flow_definitions/${encodeURIComponent(String(id))}`;
2045
+ };
2046
+ /**
2047
+ * Get a flow definition by id
2048
+ * @summary Get a flow definition by id
2049
+ */
2050
+ const getFlowDefinition = async (id, options) => {
2051
+ return customFetch(getGetFlowDefinitionUrl(id), {
2052
+ ...options,
2053
+ method: "GET"
2054
+ });
2055
+ };
2056
+ const getCreateTeamUrl = (params) => {
2057
+ const normalizedParams = new URLSearchParams();
2058
+ Object.entries(params || {}).forEach(([key, value]) => {
2059
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2060
+ });
2061
+ const stringifiedParams = normalizedParams.toString();
2062
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/teams?${stringifiedParams}` : `${getProxyPath()}/teams`;
2063
+ };
2064
+ /**
2065
+ * Creates a team in the project, with a name no other team in the project has.
2066
+ *
2067
+ * A taken name is refused with `409 team.already_exists`. The new team has no
2068
+ * members yet.
2069
+ * @summary Create team
2070
+ */
2071
+ const createTeam = async (createTeamBody, params, options) => {
2072
+ const getHeaders = (h) => {
2073
+ if (!h) return {};
2074
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
2075
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2076
+ const headers = {};
2077
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2078
+ return headers;
2079
+ };
2080
+ return customFetch(getCreateTeamUrl(params), {
2081
+ ...options,
2082
+ method: "POST",
2083
+ headers: {
2084
+ "Content-Type": "application/json",
2085
+ ...getHeaders(options?.headers)
2086
+ },
2087
+ body: JSON.stringify(createTeamBody)
2088
+ });
2089
+ };
2090
+ const getQueryTeamsUrl = (params) => {
2091
+ const normalizedParams = new URLSearchParams();
2092
+ Object.entries(params || {}).forEach(([key, value]) => {
2093
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2094
+ });
2095
+ const stringifiedParams = normalizedParams.toString();
2096
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/teams/query?${stringifiedParams}` : `${getProxyPath()}/teams/query`;
2097
+ };
2098
+ /**
2099
+ * Returns the teams of a project, paginated with a cursor.
2100
+ * @summary Query teams
2101
+ */
2102
+ const queryTeams = async (queryTeamsBody, params, options) => {
2103
+ const getHeaders = (h) => {
2104
+ if (!h) return {};
2105
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
2106
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2107
+ const headers = {};
2108
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2109
+ return headers;
2110
+ };
2111
+ return customFetch(getQueryTeamsUrl(params), {
2112
+ ...options,
2113
+ method: "POST",
2114
+ headers: {
2115
+ "Content-Type": "application/json",
2116
+ ...getHeaders(options?.headers)
2117
+ },
2118
+ body: JSON.stringify(queryTeamsBody)
2119
+ });
2120
+ };
2121
+ const getGetTeamUrl = (teamId) => {
2122
+ return `${getProxyPath()}/teams/${encodeURIComponent(String(teamId))}`;
2123
+ };
2124
+ /**
2125
+ * Returns a Team by its id.
2126
+ * @summary Get team
2127
+ */
2128
+ const getTeam = async (teamId, options) => {
2129
+ return customFetch(getGetTeamUrl(teamId), {
2130
+ ...options,
2131
+ method: "GET"
2132
+ });
2133
+ };
2134
+ const getDeleteTeamUrl = (teamId) => {
2135
+ return `${getProxyPath()}/teams/${encodeURIComponent(String(teamId))}`;
2136
+ };
2137
+ /**
2138
+ * Deactivates the team.
2139
+ *
2140
+ * The team is tombstoned rather than erased: it stays readable through
2141
+ * getTeam with status `deactivated`. Its memberships are removed and the
2142
+ * users whose lifecycle it owns are deactivated with it.
2143
+ *
2144
+ * The request is idempotent. Deleting a team that is already deactivated
2145
+ * or doesn't exist succeeds without changing anything.
2146
+ *
2147
+ * A team that still owns a project is refused with `409
2148
+ * team.owns_project`: deactivating it would leave the project owned by a
2149
+ * dead team and so unmanageable. No endpoint releases that ownership yet,
2150
+ * so such a team cannot currently be deactivated through the API.
2151
+ * @summary Delete team
2152
+ */
2153
+ const deleteTeam = async (teamId, options) => {
2154
+ return customFetch(getDeleteTeamUrl(teamId), {
2155
+ ...options,
2156
+ method: "DELETE"
2157
+ });
2158
+ };
2159
+ const getUpdateTeamUrl = (teamId) => {
2160
+ return `${getProxyPath()}/teams/${encodeURIComponent(String(teamId))}`;
2161
+ };
2162
+ /**
2163
+ * Update team. Only active teams can be updated.
2164
+ * @summary Update team
2165
+ */
2166
+ const updateTeam = async (teamId, updateTeamBody, options) => {
2167
+ const getHeaders = (h) => {
2168
+ if (!h) return {};
2169
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
2170
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2171
+ const headers = {};
2172
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2173
+ return headers;
2174
+ };
2175
+ return customFetch(getUpdateTeamUrl(teamId), {
2176
+ ...options,
2177
+ method: "PATCH",
2178
+ headers: {
2179
+ "Content-Type": "application/json",
2180
+ ...getHeaders(options?.headers)
2181
+ },
2182
+ body: JSON.stringify(updateTeamBody)
2183
+ });
2184
+ };
2185
+ const getCreateBrandingUrl = (params) => {
2186
+ const normalizedParams = new URLSearchParams();
2187
+ Object.entries(params || {}).forEach(([key, value]) => {
2188
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2189
+ });
2190
+ const stringifiedParams = normalizedParams.toString();
2191
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/branding?${stringifiedParams}` : `${getProxyPath()}/branding`;
2192
+ };
2193
+ /**
2194
+ * Publishes a new immutable branding revision for the project. Branding
2195
+ * revisions cannot be updated or deleted; every edit publishes a new
2196
+ * revision, and flow responses resolve the latest revision per project.
2197
+ *
2198
+ * The `liquid_template` is validated lexically on save (size, encoding,
2199
+ * banned patterns such as `<script>` tags, inline event handlers, and the
2200
+ * `| raw` filter). Authoritative LiquidJS validation runs at authoring
2201
+ * time via `zitadel plan` / `zitadel apply`.
2202
+ * @summary Publish a new branding revision
2203
+ */
2204
+ const createBranding = async (createBrandingBody, params, options) => {
2205
+ const getHeaders = (h) => {
2206
+ if (!h) return {};
2207
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
2208
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2209
+ const headers = {};
2210
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2211
+ return headers;
2212
+ };
2213
+ return customFetch(getCreateBrandingUrl(params), {
2214
+ ...options,
2215
+ method: "POST",
2216
+ headers: {
2217
+ "Content-Type": "application/json",
2218
+ ...getHeaders(options?.headers)
2219
+ },
2220
+ body: JSON.stringify(createBrandingBody)
2221
+ });
2222
+ };
2223
+ const getListBrandingUrl = (params) => {
2224
+ const normalizedParams = new URLSearchParams();
2225
+ Object.entries(params || {}).forEach(([key, value]) => {
2226
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2227
+ });
2228
+ const stringifiedParams = normalizedParams.toString();
2229
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/branding?${stringifiedParams}` : `${getProxyPath()}/branding`;
2230
+ };
2231
+ /**
2232
+ * Lists branding revisions for the project, newest first, capped at the
2233
+ * 100 most recent. The first entry is the revision flow responses
2234
+ * currently resolve. Deliberately unpaginated in v1 — list endpoints gain a
2235
+ * real query mechanism together; advertising pagination parameters the
2236
+ * server ignores would be worse than none.
2237
+ * @summary List branding revisions
2238
+ */
2239
+ const listBranding = async (params, options) => {
2240
+ return customFetch(getListBrandingUrl(params), {
2241
+ ...options,
2242
+ method: "GET"
2243
+ });
2244
+ };
2245
+ const getGetBrandingByIdUrl = (id) => {
2246
+ return `${getProxyPath()}/branding/${encodeURIComponent(String(id))}`;
2247
+ };
2248
+ /**
2249
+ * Retrieves a single branding revision, including its stored configuration.
2250
+ * @summary Get a branding revision by ID
2251
+ */
2252
+ const getBrandingById = async (id, options) => {
2253
+ return customFetch(getGetBrandingByIdUrl(id), {
2254
+ ...options,
2255
+ method: "GET"
2256
+ });
2257
+ };
2258
+ const getCreateIdpUrl = (params) => {
2259
+ const normalizedParams = new URLSearchParams();
2260
+ Object.entries(params || {}).forEach(([key, value]) => {
2261
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2262
+ });
2263
+ const stringifiedParams = normalizedParams.toString();
2264
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/idps?${stringifiedParams}` : `${getProxyPath()}/idps`;
2265
+ };
2266
+ /**
2267
+ * Creates or revises a connection document. If the slug does not already
2268
+ * exist, a new connection is created. If a connection with that slug already
2269
+ * exists, a revision is created.
2270
+ *
2271
+ * A revision gets a new `revision_id` and does not modify the connection
2272
+ * `id`, so identity links that reference the connection keep resolving while
2273
+ * releases and auth attempts stay pinned to the revision they captured.
2274
+ *
2275
+ * Identity fields are fixed for the life of the connection and a revision
2276
+ * that changes one is rejected: `protocol`, `subject_claim`, and `issuer`,
2277
+ * the field that names the authority. Their values decide which provider
2278
+ * account a stored subject belongs to, so changing one would silently
2279
+ * repoint existing identities at a different provider.
2280
+ *
2281
+ * `subject_claim` is optional, and `sub` is used as the default value. If a
2282
+ * revision updates `subject_claim` to a different value than the one set
2283
+ * during creation, the request is rejected.
2284
+ *
2285
+ * OIDC is the only protocol.
2286
+ *
2287
+ * The document is validated against the `idp-connection.json` schema before
2288
+ * anything is stored. The rules the engine applies when it starts a sign-in
2289
+ * then run on the document, so a connection that could never start one is
2290
+ * refused here instead with `idp.endpoints_partial`: the OIDC block sets an
2291
+ * endpoint without the others. It either sets no endpoint, and discovery
2292
+ * fills them, or sets `authorization_endpoint`, `token_endpoint`, `jwks_uri`,
2293
+ * and `userinfo_endpoint`. `userinfo_endpoint` may be left out when
2294
+ * `id_token_mapping` is on, but setting it alone still counts as setting an
2295
+ * endpoint. The details list the missing endpoints.
2296
+ *
2297
+ * A refused document stores nothing, and on a revise the current revision
2298
+ * stays unchanged.
2299
+ * @summary Create or revise an identity provider connection
2300
+ */
2301
+ const createIdp = async (createIdpBody, params, options) => {
2302
+ const getHeaders = (h) => {
2303
+ if (!h) return {};
2304
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
2305
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2306
+ const headers = {};
2307
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2308
+ return headers;
2309
+ };
2310
+ return customFetch(getCreateIdpUrl(params), {
2311
+ ...options,
2312
+ method: "POST",
2313
+ headers: {
2314
+ "Content-Type": "application/json",
2315
+ ...getHeaders(options?.headers)
2316
+ },
2317
+ body: JSON.stringify(createIdpBody)
2318
+ });
2319
+ };
2320
+ const getQueryIdpsUrl = (params) => {
2321
+ const normalizedParams = new URLSearchParams();
2322
+ Object.entries(params || {}).forEach(([key, value]) => {
2323
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2324
+ });
2325
+ const stringifiedParams = normalizedParams.toString();
2326
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/idps/query?${stringifiedParams}` : `${getProxyPath()}/idps/query`;
2327
+ };
2328
+ /**
2329
+ * Returns the identity provider connections of a project, paginated with a
2330
+ * cursor. One row per connection, carrying its newest revision.
2331
+ * @summary Query identity provider connections
2332
+ */
2333
+ const queryIdps = async (queryIdpsBody, params, options) => {
2334
+ const getHeaders = (h) => {
2335
+ if (!h) return {};
2336
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
2337
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2338
+ const headers = {};
2339
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2340
+ return headers;
2341
+ };
2342
+ return customFetch(getQueryIdpsUrl(params), {
2343
+ ...options,
2344
+ method: "POST",
2345
+ headers: {
2346
+ "Content-Type": "application/json",
2347
+ ...getHeaders(options?.headers)
2348
+ },
2349
+ body: JSON.stringify(queryIdpsBody)
2350
+ });
2351
+ };
2352
+ const getGetIdpByIdUrl = (id, params) => {
2353
+ const normalizedParams = new URLSearchParams();
2354
+ Object.entries(params || {}).forEach(([key, value]) => {
2355
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2356
+ });
2357
+ const stringifiedParams = normalizedParams.toString();
2358
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/idps/${encodeURIComponent(String(id))}?${stringifiedParams}` : `${getProxyPath()}/idps/${encodeURIComponent(String(id))}`;
2359
+ };
2360
+ /**
2361
+ * Reads a connection by its id, at its newest revision.
2362
+ * `GET /idps/{id}/revisions` lists every revision of the connection.
2363
+ *
2364
+ * The lookup is scoped to the project in `project_id`.
2365
+ * @summary Get an identity provider connection by id
2366
+ */
2367
+ const getIdpById = async (id, params, options) => {
2368
+ return customFetch(getGetIdpByIdUrl(id, params), {
2369
+ ...options,
2370
+ method: "GET"
2371
+ });
2372
+ };
2373
+ const getListIdpRevisionsUrl = (id, params) => {
2374
+ const normalizedParams = new URLSearchParams();
2375
+ Object.entries(params || {}).forEach(([key, value]) => {
2376
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2377
+ });
2378
+ const stringifiedParams = normalizedParams.toString();
2379
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/idps/${encodeURIComponent(String(id))}/revisions?${stringifiedParams}` : `${getProxyPath()}/idps/${encodeURIComponent(String(id))}/revisions`;
2380
+ };
2381
+ /**
2382
+ * Returns every revision of one connection, newest first, paginated with a
2383
+ * cursor. The order is fixed, so there is no `sorting`.
2384
+ *
2385
+ * The lookup is scoped to the project in `project_id`.
2386
+ * @summary List the revisions of an identity provider connection
2387
+ */
2388
+ const listIdpRevisions = async (id, params, options) => {
2389
+ return customFetch(getListIdpRevisionsUrl(id, params), {
2390
+ ...options,
2391
+ method: "GET"
2392
+ });
2393
+ };
2394
+ const getGetIdpRevisionByIdUrl = (revisionId, params) => {
2395
+ const normalizedParams = new URLSearchParams();
2396
+ Object.entries(params || {}).forEach(([key, value]) => {
2397
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2398
+ });
2399
+ const stringifiedParams = normalizedParams.toString();
2400
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/idps/revisions/${encodeURIComponent(String(revisionId))}?${stringifiedParams}` : `${getProxyPath()}/idps/revisions/${encodeURIComponent(String(revisionId))}`;
2401
+ };
2402
+ /**
2403
+ * Reads one revision of a connection by its `revision_id`, the value an auth
2404
+ * attempt or a release pins.
2405
+ *
2406
+ * The lookup is scoped to the project in `project_id`.
2407
+ * @summary Get one revision of an identity provider connection
2408
+ */
2409
+ const getIdpRevisionById = async (revisionId, params, options) => {
2410
+ return customFetch(getGetIdpRevisionByIdUrl(revisionId, params), {
2411
+ ...options,
2412
+ method: "GET"
2413
+ });
2414
+ };
2415
+ const getCreateReleaseUrl = (params) => {
2416
+ const normalizedParams = new URLSearchParams();
2417
+ Object.entries(params || {}).forEach(([key, value]) => {
2418
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2419
+ });
2420
+ const stringifiedParams = normalizedParams.toString();
2421
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/releases?${stringifiedParams}` : `${getProxyPath()}/releases`;
2422
+ };
2423
+ /**
2424
+ * Assembles a release from existing revisions, given as
2425
+ * `(kind, revision_id)` pairs. To build one from files on disk, use
2426
+ * `POST /releases/build`.
2427
+ *
2428
+ * Each revision must exist in the project and is recorded under the handle
2429
+ * it declares. The release must be complete and consistent:
2430
+ *
2431
+ * - Every handle its revisions name must be in the release: a flow's
2432
+ * `user_schema`, and the IDP connections named by a flow step's
2433
+ * `sso_providers` or a schema's `x-auth-methods.sso.providers`. A missing
2434
+ * one answers `rel.unresolved_reference`, naming the resource and the
2435
+ * handle, e.g. `flow_definition default-login: user_schema human-user not found`.
2436
+ * - Every flow is validated as on save, against the user schema revision
2437
+ * in the release. A flow that fails answers `rel.invalid`, with the
2438
+ * reason in `details`.
2439
+ *
2440
+ * Idempotent on the set of revisions: the same revisions with a different
2441
+ * `message` answer `200` with the existing release. A new release answers
2442
+ * `201`. Creating a release does not deploy it.
2443
+ * @summary Create a release
2444
+ */
2445
+ const createRelease = async (createReleaseBody, params, options) => {
2446
+ const getHeaders = (h) => {
2447
+ if (!h) return {};
2448
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
2449
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2450
+ const headers = {};
2451
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2452
+ return headers;
2453
+ };
2454
+ return customFetch(getCreateReleaseUrl(params), {
2455
+ ...options,
2456
+ method: "POST",
2457
+ headers: {
2458
+ "Content-Type": "application/json",
2459
+ ...getHeaders(options?.headers)
2460
+ },
2461
+ body: JSON.stringify(createReleaseBody)
2462
+ });
2463
+ };
2464
+ const getListReleasesUrl = (params) => {
2465
+ const normalizedParams = new URLSearchParams();
2466
+ Object.entries(params || {}).forEach(([key, value]) => {
2467
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2468
+ });
2469
+ const stringifiedParams = normalizedParams.toString();
2470
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/releases?${stringifiedParams}` : `${getProxyPath()}/releases`;
2471
+ };
2472
+ /**
2473
+ * Lists the project's releases, newest first.
2474
+ *
2475
+ * Entries carry the digest, the metadata and `revoked_at` — the pinned set
2476
+ * is omitted.
2477
+ * Read one release with `GET /releases/{release_id}` to get its pointers.
2478
+ *
2479
+ * `content_hash` looks a release up by its content, as the CLI does when a
2480
+ * person types the digest a transcript printed. The project holds at most
2481
+ * one release per digest, so the filtered list has one entry or none, and
2482
+ * an unknown digest is an empty list rather than an error. Paths take the
2483
+ * `rel_` id only; the matched entry's `id` is what to use there.
2484
+ * @summary List releases
2485
+ */
2486
+ const listReleases = async (params, options) => {
2487
+ return customFetch(getListReleasesUrl(params), {
2488
+ ...options,
2489
+ method: "GET"
2490
+ });
2491
+ };
2492
+ const getBuildReleaseUrl = (params) => {
2493
+ const normalizedParams = new URLSearchParams();
2494
+ Object.entries(params || {}).forEach(([key, value]) => {
2495
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2496
+ });
2497
+ const stringifiedParams = normalizedParams.toString();
2498
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/releases/build?${stringifiedParams}` : `${getProxyPath()}/releases/build`;
2499
+ };
2500
+ /**
2501
+ * Builds a release from the resources of `.zitadel/` as authored on disk,
2502
+ * grouped by kind, in one transaction: a failure anywhere leaves no
2503
+ * revision and no release. The caller records nothing.
2504
+ *
2505
+ * If the project already holds a release with the same content, the same
2506
+ * `content_hash`, the request answers `200` with that release and
2507
+ * allocates nothing, however long ago it was built. Otherwise every resource is compared against the
2508
+ * project's newest revision of the same handle: unchanged content reuses
2509
+ * that revision, changed content allocates a new one, and the request
2510
+ * answers `201` with the new release. Metadata is excluded from the
2511
+ * comparison, so the same content under a different `message` is the same
2512
+ * release.
2513
+ *
2514
+ * A structurally malformed request is refused while decoding with
2515
+ * `req.invalid`, naming the offending fields. A well-formed bundle is then
2516
+ * checked resource by resource, as each kind's create endpoint checks it,
2517
+ * and every failure is reported at once: the request answers `400` with
2518
+ * `rel.invalid`, and `details.resources` lists each resource that failed.
2519
+ * A handle that resolves neither in the bundle nor in the project answers
2520
+ * `rel.unresolved_reference`, naming the pointer and the handle.
2521
+ *
2522
+ * Building writes revisions, so besides `release.write` it needs the write
2523
+ * scope of every kind the bundle carries a resource of: `schema.write`,
2524
+ * `flow_definition.write`, `branding.write` and `idp.write`, as the
2525
+ * per-kind create endpoints do. A missing scope answers `403` with `rel.permission_denied`,
2526
+ * naming the kind. An empty kind needs no scope.
2527
+ *
2528
+ * Building a release does not deploy it. A release is not tied to an
2529
+ * origin, and the same release can later be deployed to any number of
2530
+ * origins unchanged.
2531
+ * @summary Build a release from files
2532
+ */
2533
+ const buildRelease = async (buildReleaseBody, params, options) => {
2534
+ const getHeaders = (h) => {
2535
+ if (!h) return {};
2536
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
2537
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2538
+ const headers = {};
2539
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2540
+ return headers;
2541
+ };
2542
+ return customFetch(getBuildReleaseUrl(params), {
2543
+ ...options,
2544
+ method: "POST",
2545
+ headers: {
2546
+ "Content-Type": "application/json",
2547
+ ...getHeaders(options?.headers)
2548
+ },
2549
+ body: JSON.stringify(buildReleaseBody)
2550
+ });
2551
+ };
2552
+ const getGetReleaseByIdUrl = (releaseId, params) => {
2553
+ const normalizedParams = new URLSearchParams();
2554
+ Object.entries(params || {}).forEach(([key, value]) => {
2555
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2556
+ });
2557
+ const stringifiedParams = normalizedParams.toString();
2558
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/releases/${encodeURIComponent(String(releaseId))}?${stringifiedParams}` : `${getProxyPath()}/releases/${encodeURIComponent(String(releaseId))}`;
2559
+ };
2560
+ /**
2561
+ * Reads one release: its digest, its metadata, whether it was revoked, and
2562
+ * the `(kind, handle, revision_id)` tuples it pins.
2563
+ *
2564
+ * The path takes the `rel_` id only. To find a release from its digest,
2565
+ * list with the `content_hash` filter and read the matched entry's `id`.
2566
+ *
2567
+ * Does not embed resource content. Resolve each `revision_id` through the
2568
+ * per-kind read endpoints when the bytes are needed.
2569
+ *
2570
+ * The lookup is scoped to the project in `project_id`: a release id belonging
2571
+ * to another project answers not found exactly as an unknown id does, so the
2572
+ * endpoint cannot be used to probe for releases in projects the caller cannot
2573
+ * read.
2574
+ * @summary Get a release by id
2575
+ */
2576
+ const getReleaseById = async (releaseId, params, options) => {
2577
+ return customFetch(getGetReleaseByIdUrl(releaseId, params), {
2578
+ ...options,
2579
+ method: "GET"
2580
+ });
2581
+ };
2582
+ const getRevokeReleaseUrl = (releaseId, params) => {
2583
+ const normalizedParams = new URLSearchParams();
2584
+ Object.entries(params || {}).forEach(([key, value]) => {
2585
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2586
+ });
2587
+ const stringifiedParams = normalizedParams.toString();
2588
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/releases/${encodeURIComponent(String(releaseId))}/revoke?${stringifiedParams}` : `${getProxyPath()}/releases/${encodeURIComponent(String(releaseId))}/revoke`;
2589
+ };
2590
+ /**
2591
+ * Marks the release revoked, so that its content is never served again.
2592
+ * From then on the release cannot be deployed and is refused on every path
2593
+ * that would serve it, including to a build that pins its digest, with
2594
+ * `rel.revoked`.
2595
+ *
2596
+ * A release that any origin still serves cannot be revoked. An origin
2597
+ * serves the release of the newest deployment to it, so the call answers
2598
+ * `409` with `rel.in_use`, naming each such origin and that deployment.
2599
+ * Deploy another release there or roll back first, then revoke. Revoking
2600
+ * therefore never takes an origin down. Deployments that named the release
2601
+ * earlier stay in the history.
2602
+ *
2603
+ * Idempotent: revoking a release that is already revoked answers `200`
2604
+ * with the release unchanged, `revoked_at` still naming the first
2605
+ * revocation. There is no un-revoke; build a new release instead.
2606
+ *
2607
+ * Takes no body. The lookup is scoped to the project in `project_id`, so a
2608
+ * release id of another project answers not found exactly as an unknown id
2609
+ * does.
2610
+ * @summary Revoke a release
2611
+ */
2612
+ const revokeRelease = async (releaseId, params, options) => {
2613
+ return customFetch(getRevokeReleaseUrl(releaseId, params), {
2614
+ ...options,
2615
+ method: "POST"
2616
+ });
2617
+ };
2618
+ const getCreateGrantUrl = (params) => {
2619
+ const normalizedParams = new URLSearchParams();
2620
+ Object.entries(params || {}).forEach(([key, value]) => {
2621
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2622
+ });
2623
+ const stringifiedParams = normalizedParams.toString();
2624
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/grants?${stringifiedParams}` : `${getProxyPath()}/grants`;
2625
+ };
2626
+ /**
2627
+ * Bind a user or team to `project.viewer`, `project.editor`, or
2628
+ * `project.admin` on the project identified by the `project-id` header.
2629
+ * Name the principal with `user` (`user_id` or `identifier`) or `team`
2630
+ * (`team_id` or `name`). IDs are `asgn_<opaque>`. Owning-team
2631
+ * (`project.team`) grants are not created here — claim owns that path. An
2632
+ * unrevoked grant with the same principal and relation occupies the unique
2633
+ * key even after `expires_at`; DELETE it before re-creating.
2634
+ * Create does not accept `expand`. The `user_id` and team locators
2635
+ * return 201, whose `user` / `team` carry only `user_id` / `team_id`,
2636
+ * and still 404 / 409 when the principal is missing or the tuple
2637
+ * already exists. Creating by `user.identifier` answers 202 with no
2638
+ * body on every outcome. Granting the session caller's own user is
2639
+ * `grant.invalid` on either user locator. Read the grant back for
2640
+ * identifier and display.
2641
+ *
2642
+ * Accepts either a project secret (`oauth2`) or a user-bound Console
2643
+ * session cookie (`nextgenSession`). Session callers are authorized as
2644
+ * the human against the target project (home may differ). Cookie-authenticated
2645
+ * requests follow the scheme's CSRF rules (`nextgenSession`).
2646
+ * @summary Create grant
2647
+ */
2648
+ const createGrant = async (createGrantBody, params, options) => {
2649
+ const getHeaders = (h) => {
2650
+ if (!h) return {};
2651
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
2652
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2653
+ const headers = {};
2654
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2655
+ return headers;
2656
+ };
2657
+ return customFetch(getCreateGrantUrl(params), {
2658
+ ...options,
2659
+ method: "POST",
2660
+ headers: {
2661
+ "Content-Type": "application/json",
2662
+ ...getHeaders(options?.headers)
2663
+ },
2664
+ body: JSON.stringify(createGrantBody)
2665
+ });
2666
+ };
2667
+ const getQueryGrantsUrl = (params) => {
2668
+ const normalizedParams = new URLSearchParams();
2669
+ Object.entries(params || {}).forEach(([key, value]) => {
2670
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2671
+ });
2672
+ const stringifiedParams = normalizedParams.toString();
2673
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/grants/query?${stringifiedParams}` : `${getProxyPath()}/grants/query`;
2674
+ };
2675
+ /**
2676
+ * Returns the collaboration grants of a project, paginated with a cursor.
2677
+ * Only unrevoked grants this API manages are listed (user or team bound to
2678
+ * viewer, editor, or admin), including expired grants so a client can
2679
+ * DELETE before re-granting. Project-secret setup (`sk_proj`) and
2680
+ * owning-team (`relation=team`) rows are not returned. Grants are not in
2681
+ * `resource_scope_index`; project scope is required on the query (same as
2682
+ * get). Requires `project.read`. `expand: ["principal"]` adds envelope
2683
+ * fields on `user` / `team` and additionally requires `user.read` and
2684
+ * `team.read` for project secrets (documented on the expand enum; those
2685
+ * scopes cannot be ANDed onto this security block because they are
2686
+ * body-conditional). A user-bound Console session that already passed
2687
+ * the project Check may expand without those scopes.
2688
+ *
2689
+ * Accepts either a project secret (`oauth2`) or a user-bound Console
2690
+ * session cookie (`nextgenSession`). Cookie-authenticated requests
2691
+ * follow the scheme's CSRF rules (`nextgenSession`).
2692
+ * @summary Query grants
2693
+ */
2694
+ const queryGrants = async (queryGrantsBody, params, options) => {
2695
+ const getHeaders = (h) => {
2696
+ if (!h) return {};
2697
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
2698
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2699
+ const headers = {};
2700
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2701
+ return headers;
2702
+ };
2703
+ return customFetch(getQueryGrantsUrl(params), {
2704
+ ...options,
2705
+ method: "POST",
2706
+ headers: {
2707
+ "Content-Type": "application/json",
2708
+ ...getHeaders(options?.headers)
2709
+ },
2710
+ body: JSON.stringify(queryGrantsBody)
2711
+ });
2712
+ };
2713
+ const getGetGrantUrl = (id, params) => {
2714
+ const normalizedParams = new URLSearchParams();
2715
+ Object.entries(params || {}).forEach(([key, value]) => {
2716
+ if (Array.isArray(value) && ["expand"].includes(key)) {
2717
+ value.forEach((v) => {
2718
+ normalizedParams.append(key, v === null ? "null" : String(v));
2719
+ });
2720
+ return;
2721
+ }
2722
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2723
+ });
2724
+ const stringifiedParams = normalizedParams.toString();
2725
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/grants/${encodeURIComponent(String(id))}?${stringifiedParams}` : `${getProxyPath()}/grants/${encodeURIComponent(String(id))}`;
2726
+ };
2727
+ /**
2728
+ * Loads a grant by `(project_id, id)` that this API manages (user or team
2729
+ * bound to viewer, editor, or admin) and that has not been revoked.
2730
+ * "Active" here means not revoked: expired grants stay visible so the
2731
+ * client can DELETE before re-granting the same binding. Authorization
2732
+ * still ignores expired grants. Grants are not registered in
2733
+ * `resource_scope_index`; project scope is required on the query (same as
2734
+ * events). Misses, revoked rows, project-secret setup (`sk_proj`),
2735
+ * owning-team (`relation=team`) rows, and cross-project ids return 404.
2736
+ * `expand=principal` adds envelope fields on `user` or `team` and requires
2737
+ * `user.read` and `team.read` in addition to `project.read` for project
2738
+ * secrets. A user-bound Console session that already passed the project
2739
+ * Check may expand without those scopes.
2740
+ *
2741
+ * Accepts either a project secret (`oauth2`) or a user-bound Console
2742
+ * session cookie (`nextgenSession`). Cookie-authenticated requests
2743
+ * follow the scheme's CSRF rules (`nextgenSession`).
2744
+ * @summary Get grant
2745
+ */
2746
+ const getGrant = async (id, params, options) => {
2747
+ return customFetch(getGetGrantUrl(id, params), {
2748
+ ...options,
2749
+ method: "GET"
2750
+ });
2751
+ };
2752
+ const getDeleteGrantUrl = (id, params) => {
2753
+ const normalizedParams = new URLSearchParams();
2754
+ Object.entries(params || {}).forEach(([key, value]) => {
2755
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2756
+ });
2757
+ const stringifiedParams = normalizedParams.toString();
2758
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/grants/${encodeURIComponent(String(id))}?${stringifiedParams}` : `${getProxyPath()}/grants/${encodeURIComponent(String(id))}`;
2759
+ };
2760
+ /**
2761
+ * Soft-revokes a grant this API manages and emits `authz.revoked`.
2762
+ * Already-revoked, missing, project-secret setup, and owning-team grants
2763
+ * return 404. The row is not un-revoked. Expired grants can still be
2764
+ * revoked so the unique binding can be reused.
2765
+ *
2766
+ * Accepts either a project secret (`oauth2`) or a user-bound Console
2767
+ * session cookie (`nextgenSession`). Cookie-authenticated requests
2768
+ * follow the scheme's CSRF rules (`nextgenSession`).
2769
+ * @summary Revoke grant
2770
+ */
2771
+ const deleteGrant = async (id, params, options) => {
2772
+ return customFetch(getDeleteGrantUrl(id, params), {
2773
+ ...options,
2774
+ method: "DELETE"
2775
+ });
2776
+ };
2777
+ const getListEventsUrl = (params) => {
2778
+ const normalizedParams = new URLSearchParams();
2779
+ Object.entries(params || {}).forEach(([key, value]) => {
2780
+ if (Array.isArray(value) && ["category", "event_type"].includes(key)) {
2781
+ value.forEach((v) => {
2782
+ normalizedParams.append(key, v === null ? "null" : String(v));
2783
+ });
2784
+ return;
2785
+ }
2786
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2787
+ });
2788
+ const stringifiedParams = normalizedParams.toString();
2789
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/events?${stringifiedParams}` : `${getProxyPath()}/events`;
2790
+ };
2791
+ /**
2792
+ * Returns project-scoped audit events, newest-first by keyset on
2793
+ * `(created_at, id)` (ADR 027 / ADR 049). Pass `order=asc` for oldest-first.
2794
+ * Requires `events.read`.
2795
+ *
2796
+ * Pre-claim projects return an empty list (events are stored but not
2797
+ * visible until claim succeeds). Team-scoped credentials see only events
2798
+ * whose emit-time `team_id` matches the credential team (enforced when
2799
+ * team-scoped tokens exist).
2800
+ *
2801
+ * Clients discriminate each item via `event_type` (OpenAPI Event oneOf) —
2802
+ * see docs/design/api/events-catalog.md.
2803
+ * @summary List events
2804
+ */
2805
+ const listEvents = async (params, options) => {
2806
+ return customFetch(getListEventsUrl(params), {
2807
+ ...options,
2808
+ method: "GET"
2809
+ });
2810
+ };
2811
+ const getGetEventUrl = (id, params) => {
2812
+ const normalizedParams = new URLSearchParams();
2813
+ Object.entries(params || {}).forEach(([key, value]) => {
2814
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2815
+ });
2816
+ const stringifiedParams = normalizedParams.toString();
2817
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/events/${encodeURIComponent(String(id))}?${stringifiedParams}` : `${getProxyPath()}/events/${encodeURIComponent(String(id))}`;
2818
+ };
2819
+ /**
2820
+ * Loads a single event by `(project_id, id)`. Requires `events.read`.
2821
+ * Events are not registered in `resource_scope_index`; project scope is
2822
+ * required on the query (ADR 049). Misses and cross-project ids return 404.
2823
+ *
2824
+ * Pre-claim projects return 404 (stored events stay invisible until claim).
2825
+ * @summary Get event by ID
2826
+ */
2827
+ const getEvent = async (id, params, options) => {
2828
+ return customFetch(getGetEventUrl(id, params), {
2829
+ ...options,
2830
+ method: "GET"
2831
+ });
2832
+ };
2833
+ const getGetVariablesUrl = (params) => {
2834
+ const normalizedParams = new URLSearchParams();
2835
+ Object.entries(params || {}).forEach(([key, value]) => {
2836
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2837
+ });
2838
+ const stringifiedParams = normalizedParams.toString();
2839
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/variables?${stringifiedParams}` : `${getProxyPath()}/variables`;
2840
+ };
2841
+ /**
2842
+ * Returns the project's variables, keyed by name, each with its value per
2843
+ * kind. With `kind`, only that kind's values are returned.
2844
+ *
2845
+ * Secret values are not returned. A secret appears as `{"secret": true}`,
2846
+ * which says a value is held without disclosing it.
2847
+ * @summary Get variables
2848
+ */
2849
+ const getVariables = async (params, options) => {
2850
+ return customFetch(getGetVariablesUrl(params), {
2851
+ ...options,
2852
+ method: "GET"
2853
+ });
2854
+ };
2855
+ const getUpdateVariablesUrl = (params) => {
2856
+ const normalizedParams = new URLSearchParams();
2857
+ Object.entries(params || {}).forEach(([key, value]) => {
2858
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2859
+ });
2860
+ const stringifiedParams = normalizedParams.toString();
2861
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/variables?${stringifiedParams}` : `${getProxyPath()}/variables`;
2862
+ };
2863
+ /**
2864
+ * Enters, replaces and removes the project's variables for the requested
2865
+ * kind. Names not in the body are untouched. Existing deployments keep the
2866
+ * values they froze.
2867
+ *
2868
+ * Without `kind`, a plain value is written for both kinds. A secret is
2869
+ * written for `primary` only and removes the name's `preview` value, so a
2870
+ * preview never keeps a plaintext copy; set a preview secret with
2871
+ * `kind=preview`. `null` removes the name from both.
2872
+ *
2873
+ * A bare scalar enters a non-secret value. `{"value": …, "secret": true}`
2874
+ * stores the value encrypted under the project's active `secret` key, after
2875
+ * which it can be referenced but not read back. `null` removes the name
2876
+ * (RFC 7386), which is how several variables are removed in one request;
2877
+ * removing a name the project does not hold is a no-op rather than an error.
2878
+ *
2879
+ * The body is applied whole or not at all, so a rejected request leaves the
2880
+ * project's variables exactly as they were. Writing the same name twice
2881
+ * replaces the value rather than duplicating it, which makes a retry safe.
2882
+ * @summary Update variables
2883
+ */
2884
+ const updateVariables = async (updateVariablesBody, params, options) => {
2885
+ const getHeaders = (h) => {
2886
+ if (!h) return {};
2887
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
2888
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2889
+ const headers = {};
2890
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2891
+ return headers;
2892
+ };
2893
+ return customFetch(getUpdateVariablesUrl(params), {
2894
+ ...options,
2895
+ method: "PATCH",
2896
+ headers: {
2897
+ "Content-Type": "application/json",
2898
+ ...getHeaders(options?.headers)
2899
+ },
2900
+ body: JSON.stringify(updateVariablesBody)
2901
+ });
2902
+ };
2903
+ const getGetVariableUrl = (variableName, params) => {
2904
+ const normalizedParams = new URLSearchParams();
2905
+ Object.entries(params || {}).forEach(([key, value]) => {
2906
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2907
+ });
2908
+ const stringifiedParams = normalizedParams.toString();
2909
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/variables/${encodeURIComponent(String(variableName))}?${stringifiedParams}` : `${getProxyPath()}/variables/${encodeURIComponent(String(variableName))}`;
2910
+ };
2911
+ /**
2912
+ * Reads one variable by name, with its value per kind. A name with no
2913
+ * value for the requested kind answers `var.not_found`. A secret reads
2914
+ * back as `{"secret": true}`.
2915
+ * @summary Get a variable
2916
+ */
2917
+ const getVariable = async (variableName, params, options) => {
2918
+ return customFetch(getGetVariableUrl(variableName, params), {
2919
+ ...options,
2920
+ method: "GET"
2921
+ });
2922
+ };
2923
+ const getDeleteVariableUrl = (variableName, params) => {
2924
+ const normalizedParams = new URLSearchParams();
2925
+ Object.entries(params || {}).forEach(([key, value]) => {
2926
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2927
+ });
2928
+ const stringifiedParams = normalizedParams.toString();
2929
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/variables/${encodeURIComponent(String(variableName))}?${stringifiedParams}` : `${getProxyPath()}/variables/${encodeURIComponent(String(variableName))}`;
2930
+ };
2931
+ /**
2932
+ * Removes a variable for the requested kind, or for both kinds without
2933
+ * `kind`. A name with no value for that kind answers `var.not_found`.
2934
+ * Existing deployments keep the values they froze.
2935
+ * @summary Delete a variable
2936
+ */
2937
+ const deleteVariable = async (variableName, params, options) => {
2938
+ return customFetch(getDeleteVariableUrl(variableName, params), {
2939
+ ...options,
2940
+ method: "DELETE"
2941
+ });
2942
+ };
2943
+ const getCreateDeploymentUrl = (params) => {
2944
+ const normalizedParams = new URLSearchParams();
2945
+ Object.entries(params || {}).forEach(([key, value]) => {
2946
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
2947
+ });
2948
+ const stringifiedParams = normalizedParams.toString();
2949
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/deployments?${stringifiedParams}` : `${getProxyPath()}/deployments`;
2950
+ };
2951
+ /**
2952
+ * Makes a release live on its targets by recording a deployment,
2953
+ * atomically: on success every target serves the release and the record
2954
+ * exists; on failure nothing changes and no record is written.
2955
+ *
2956
+ * Name the release by exactly one of `release_id` or `content_hash`; it
2957
+ * must already exist in the project. `targets` is `primary` or preview
2958
+ * URLs. The deployment freezes the project's variable values for its kind,
2959
+ * with no fallback between primary and preview values.
2960
+ *
2961
+ * A deployment to `primary` changes nothing when the project's newest
2962
+ * primary deployment has the same release and frozen values and covers
2963
+ * exactly the current primary origins: the call answers `200` with that
2964
+ * deployment. Any other request writes a new deployment and answers `201`;
2965
+ * for preview URLs that record renews their previews.
2966
+ *
2967
+ * Failures:
2968
+ * - `400 dep.invalid`: both or neither of `release_id` and `content_hash`;
2969
+ * a primary origin named exactly; `primary` mixed with preview URLs;
2970
+ * `primary` on a project with no primary origin; `ttl` with `primary`;
2971
+ * `ttl` above the project's maximum.
2972
+ * - `400 dep.variables_missing`: a referenced variable has no value for
2973
+ * the kind; `details` names the kind and every missing variable.
2974
+ * - `403 proj.origin_not_allowed`: a preview URL matches no preview
2975
+ * pattern.
2976
+ * - `404 rel.not_found`: the release id or digest names no release here.
2977
+ * - `409 dep.conflict`: `expected_deployment_id` is not the deployment
2978
+ * this write replaces; `details.deployment` is that deployment.
2979
+ * - `409 rel.revoked`: the release is revoked.
2980
+ * @summary Create a deployment
2981
+ */
2982
+ const createDeployment = async (createDeploymentBody, params, options) => {
2983
+ const getHeaders = (h) => {
2984
+ if (!h) return {};
2985
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
2986
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
2987
+ const headers = {};
2988
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
2989
+ return headers;
2990
+ };
2991
+ return customFetch(getCreateDeploymentUrl(params), {
2992
+ ...options,
2993
+ method: "POST",
2994
+ headers: {
2995
+ "Content-Type": "application/json",
2996
+ ...getHeaders(options?.headers)
2997
+ },
2998
+ body: JSON.stringify(createDeploymentBody)
2999
+ });
3000
+ };
3001
+ const getListDeploymentsUrl = (params) => {
3002
+ const normalizedParams = new URLSearchParams();
3003
+ Object.entries(params || {}).forEach(([key, value]) => {
3004
+ if (Array.isArray(value) && ["expand"].includes(key)) {
3005
+ value.forEach((v) => {
3006
+ normalizedParams.append(key, v === null ? "null" : String(v));
3007
+ });
3008
+ return;
3009
+ }
3010
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3011
+ });
3012
+ const stringifiedParams = normalizedParams.toString();
3013
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/deployments?${stringifiedParams}` : `${getProxyPath()}/deployments`;
3014
+ };
3015
+ /**
3016
+ * Lists what ran where, and when.
3017
+ *
3018
+ * By default the list is the history, newest first: every deployment of
3019
+ * the project with every target it made the release live on. With
3020
+ * `origin`, the history of that origin alone.
3021
+ *
3022
+ * With `live=true`, the list is what is served now, newest first: the
3023
+ * project's newest primary deployment, narrowed to origins that are still
3024
+ * primary, and the newest deployment to each live preview URL, narrowed to
3025
+ * the URLs it still serves. Combined with `origin`, it is the one
3026
+ * deployment that origin serves, or empty.
3027
+ *
3028
+ * `expand: ["release"]` embeds the release each deployment made live; it
3029
+ * requires `release.read` and does not change the ordering or the page
3030
+ * tokens.
3031
+ * @summary List deployments
3032
+ */
3033
+ const listDeployments = async (params, options) => {
3034
+ return customFetch(getListDeploymentsUrl(params), {
3035
+ ...options,
3036
+ method: "GET"
3037
+ });
3038
+ };
3039
+ const getGetDeploymentByIdUrl = (deploymentId, params) => {
3040
+ const normalizedParams = new URLSearchParams();
3041
+ Object.entries(params || {}).forEach(([key, value]) => {
3042
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3043
+ });
3044
+ const stringifiedParams = normalizedParams.toString();
3045
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/deployments/${encodeURIComponent(String(deploymentId))}?${stringifiedParams}` : `${getProxyPath()}/deployments/${encodeURIComponent(String(deploymentId))}`;
3046
+ };
3047
+ /**
3048
+ * Reads one deployment record.
3049
+ *
3050
+ * The lookup is scoped to the project in `project_id`: a deployment id
3051
+ * belonging to another project answers not found exactly as an unknown id
3052
+ * does, so the endpoint cannot be used to probe for deployments in projects
3053
+ * the caller cannot read.
3054
+ * @summary Get a deployment by id
3055
+ */
3056
+ const getDeploymentById = async (deploymentId, params, options) => {
3057
+ return customFetch(getGetDeploymentByIdUrl(deploymentId, params), {
3058
+ ...options,
3059
+ method: "GET"
3060
+ });
3061
+ };
3062
+ const getRollbackDeploymentUrl = (deploymentId, params) => {
3063
+ const normalizedParams = new URLSearchParams();
3064
+ Object.entries(params || {}).forEach(([key, value]) => {
3065
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3066
+ });
3067
+ const stringifiedParams = normalizedParams.toString();
3068
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/deployments/${encodeURIComponent(String(deploymentId))}/rollback?${stringifiedParams}` : `${getProxyPath()}/deployments/${encodeURIComponent(String(deploymentId))}/rollback`;
3069
+ };
3070
+ /**
3071
+ * Re-deploys the release of the deployment named in the path to `primary`,
3072
+ * with the variable values it froze: a new deployment with `reason:
3073
+ * rollback` and `rollback_to` naming it. Like any deployment to `primary`,
3074
+ * it covers every current primary origin. Idempotent like a deployment to
3075
+ * `primary`: when nothing would change it answers `200` with the newest
3076
+ * primary deployment.
3077
+ *
3078
+ * Failures:
3079
+ * - `400 dep.invalid`: the deployment went to preview URLs (deploy to the
3080
+ * preview again instead), or the project has no primary origin.
3081
+ * - `404 dep.not_found`: no deployment of the project has that id.
3082
+ * - `409 dep.conflict`: `expected_deployment_id` is not the project's
3083
+ * newest primary deployment; `details.deployment` is that deployment.
3084
+ * - `409 rel.revoked`: the release is revoked.
3085
+ * @summary Roll back to a deployment
3086
+ */
3087
+ const rollbackDeployment = async (deploymentId, params, rollbackDeploymentBody, options) => {
3088
+ const getHeaders = (h) => {
3089
+ if (!h) return {};
3090
+ if (h instanceof Headers) return Object.fromEntries(h.entries());
3091
+ if (Symbol.iterator in h) return Object.fromEntries(Array.from(h, (entry) => Array.from(entry)));
3092
+ const headers = {};
3093
+ for (const [name, value] of Object.entries(h)) if (value !== void 0) headers[name] = value;
3094
+ return headers;
3095
+ };
3096
+ return customFetch(getRollbackDeploymentUrl(deploymentId, params), {
3097
+ ...options,
3098
+ method: "POST",
3099
+ headers: {
3100
+ "Content-Type": "application/json",
3101
+ ...getHeaders(options?.headers)
3102
+ },
3103
+ body: JSON.stringify(rollbackDeploymentBody)
3104
+ });
3105
+ };
3106
+ const getGetDeploymentVariablesUrl = (deploymentId, params) => {
3107
+ const normalizedParams = new URLSearchParams();
3108
+ Object.entries(params || {}).forEach(([key, value]) => {
3109
+ if (value !== void 0) normalizedParams.append(key, value === null ? "null" : String(value));
3110
+ });
3111
+ const stringifiedParams = normalizedParams.toString();
3112
+ return stringifiedParams.length > 0 ? `${getProxyPath()}/deployments/${encodeURIComponent(String(deploymentId))}/variables?${stringifiedParams}` : `${getProxyPath()}/deployments/${encodeURIComponent(String(deploymentId))}/variables`;
3113
+ };
3114
+ /**
3115
+ * Returns the variable values the deployment froze when it was made. Later
3116
+ * changes to the project's variables do not affect them. A secret reads
3117
+ * back as `{"secret": true}`.
3118
+ * @summary Get a deployment's variables
3119
+ */
3120
+ const getDeploymentVariables = async (deploymentId, params, options) => {
3121
+ return customFetch(getGetDeploymentVariablesUrl(deploymentId, params), {
3122
+ ...options,
3123
+ method: "GET"
3124
+ });
3125
+ };
3126
+ //#endregion
3127
+ //#region ../api/dist/runtime/api-factory.mjs
3128
+ /**
3129
+ * Factory for the typed Zitadel client every consumer reaches for.
3130
+ *
3131
+ * Wraps the orval-generated endpoints in a {@link Proxy} so each
3132
+ * generated function sees the right base URL and (optionally) the
3133
+ * right bearer token at call time — without the caller having to
3134
+ * thread either through every operation, and without exposing the
3135
+ * module-globals (`setProxyPath` / `setApiAuthToken`) as part of the
3136
+ * public API.
3137
+ *
3138
+ * Per-instance isolation: multiple clients can coexist in one process
3139
+ * (different servers, different tokens). Their Proxy `get` traps set
3140
+ * the globals synchronously before invoking the underlying generated
3141
+ * function, which reads them at the top of `customFetch` before any
3142
+ * `await`. Two clients running interleaved within a single JS turn
3143
+ * are safe; two clients running in parallel across awaits could
3144
+ * clobber each other — not a pattern any current consumer uses.
3145
+ */
3146
+ /**
3147
+ * Build a typed Zitadel client pre-bound to a base URL and (optionally)
3148
+ * a bearer token. Every method on the returned object mirrors a
3149
+ * generated orval function:
3150
+ *
3151
+ * const client = createZitadelClient({ baseUrl, token });
3152
+ * await client.createProject({ origins: [] });
3153
+ * await client.createSchema(body, { project_id });
3154
+ */
3155
+ function createZitadelClient(opts) {
3156
+ let baseUrl = opts.baseUrl;
3157
+ while (baseUrl.endsWith("/")) baseUrl = baseUrl.slice(0, -1);
3158
+ return new Proxy(zitadelNextGen_exports, { get(target, prop, receiver) {
3159
+ const value = Reflect.get(target, prop, receiver);
3160
+ if (typeof value !== "function") return value;
3161
+ return (...args) => {
3162
+ setProxyPath(baseUrl);
3163
+ setApiAuthToken(opts.token);
3164
+ setRequestPolicy({
3165
+ signal: opts.signal,
3166
+ timeoutMs: opts.timeoutMs
3167
+ });
3168
+ return value(...args);
3169
+ };
3170
+ } });
3171
+ }
3172
+ //#endregion
3173
+ //#region ../config/dist/defaults-B3SfaQPb.mjs
3174
+ var default_human_user_default = {
3175
+ title: "DefaultHumanUserSchema",
3176
+ $schema: "https://json-schema.org/draft/2020-12/schema",
3177
+ metaSchema: "${SERVER_URL}/user-schema.json",
3178
+ $id: "${USER_SCHEMA_URL}",
3179
+ objectType: "human-user",
3180
+ kind: "user-schema",
3181
+ type: "object",
3182
+ "x-identifier": "email",
3183
+ description: "The default editable schema for human users.",
3184
+ "x-auth-methods": {
3185
+ "password": { "enabled": true },
3186
+ "passkey": { "enabled": true }
3187
+ },
3188
+ required: ["email"],
3189
+ properties: { "email": {
3190
+ "type": "string",
3191
+ "format": "email",
3192
+ "x-unique": "project",
3193
+ "description": "The user's email address."
3194
+ } }
3195
+ };
3196
+ var default_login_default = {
3197
+ $schema: "../meta/flow-definition.json",
3198
+ name: "default-login",
3199
+ status: "active",
3200
+ user_schema: "human-user",
3201
+ purposes: {
3202
+ "login": "identifier",
3203
+ "register": "register"
3204
+ },
3205
+ steps: [
3206
+ {
3207
+ "name": "identifier",
3208
+ "fields": ["email"],
3209
+ "actions": [{
3210
+ "name": "submit",
3211
+ "kind": "submit",
3212
+ "primary": true,
3213
+ "text_key": "identifier.action.continue"
3214
+ }, {
3215
+ "name": "register",
3216
+ "kind": "navigate",
3217
+ "primary": false,
3218
+ "text_key": "identifier.action.register.link"
3219
+ }],
3220
+ "transitions": {
3221
+ "submit": { "target": "password" },
3222
+ "user_not_found": { "target": "register" },
3223
+ "register": {
3224
+ "target": "register",
3225
+ "purpose": "register"
3226
+ }
3227
+ }
3228
+ },
3229
+ {
3230
+ "name": "password",
3231
+ "fields": ["x-auth-methods#password"],
3232
+ "actions": [{
3233
+ "name": "submit",
3234
+ "kind": "submit",
3235
+ "primary": true,
3236
+ "text_key": "password.action.signin"
3237
+ }],
3238
+ "transitions": { "submit": { "target": "done" } }
3239
+ },
3240
+ {
3241
+ "name": "register",
3242
+ "fields": ["email"],
3243
+ "actions": [{
3244
+ "name": "submit",
3245
+ "kind": "submit",
3246
+ "primary": true,
3247
+ "text_key": "register.action.password"
3248
+ }, {
3249
+ "name": "sign_in",
3250
+ "kind": "navigate",
3251
+ "primary": false,
3252
+ "text_key": "register.action.sign_in.link"
3253
+ }],
3254
+ "transitions": {
3255
+ "submit": { "target": "register-password" },
3256
+ "user_already_exists": { "target": "password" },
3257
+ "sign_in": {
3258
+ "target": "identifier",
3259
+ "purpose": "login"
3260
+ }
3261
+ }
3262
+ },
3263
+ {
3264
+ "name": "register-password",
3265
+ "fields": ["x-auth-methods#password"],
3266
+ "actions": [{
3267
+ "name": "submit",
3268
+ "kind": "submit",
3269
+ "primary": true,
3270
+ "text_key": "register-password.action.submit"
3271
+ }],
3272
+ "on_success": "create_user",
3273
+ "transitions": {
3274
+ "submit": { "target": "done" },
3275
+ "user_already_exists": { "target": "password" }
3276
+ }
3277
+ },
3278
+ {
3279
+ "name": "done",
3280
+ "complete": "show"
3281
+ }
3282
+ ]
3283
+ };
3284
+ var human_user_default = {
3285
+ title: "DefaultHumanUserSchema",
3286
+ $schema: "https://json-schema.org/draft/2020-12/schema",
3287
+ metaSchema: "${SERVER_URL}/user-schema.json",
3288
+ $id: "${USER_SCHEMA_URL}",
3289
+ objectType: "human-user",
3290
+ kind: "user-schema",
3291
+ type: "object",
3292
+ "x-identifier": "email",
3293
+ description: "The default editable schema for human users (passkey-first sign-in).",
3294
+ "x-auth-methods": {
3295
+ "passkey": { "enabled": true },
3296
+ "password": { "enabled": true }
3297
+ },
3298
+ required: ["email"],
3299
+ properties: { "email": {
3300
+ "type": "string",
3301
+ "format": "email",
3302
+ "x-unique": "project",
3303
+ "description": "The user's email address."
3304
+ } }
3305
+ };
3306
+ var login_default = {
3307
+ $schema: "../meta/flow-definition.json",
3308
+ name: "default-login",
3309
+ status: "active",
3310
+ user_schema: "human-user",
3311
+ purposes: {
3312
+ "login": "passkey-first",
3313
+ "register": "register"
3314
+ },
3315
+ steps: [
3316
+ {
3317
+ "name": "passkey-first",
3318
+ "fields": [],
3319
+ "actions": [
3320
+ {
3321
+ "name": "passkey",
3322
+ "kind": "passkey",
3323
+ "primary": true,
3324
+ "text_key": "passkey-first.action.passkey"
3325
+ },
3326
+ {
3327
+ "name": "email_fallback",
3328
+ "kind": "navigate",
3329
+ "primary": false,
3330
+ "text_key": "passkey-first.action.email_fallback"
3331
+ },
3332
+ {
3333
+ "name": "register",
3334
+ "kind": "navigate",
3335
+ "primary": false,
3336
+ "text_key": "identifier.action.register.link"
3337
+ }
3338
+ ],
3339
+ "transitions": {
3340
+ "passkey": { "target": "done" },
3341
+ "email_fallback": { "target": "identifier" },
3342
+ "user_not_found": { "target": "register" },
3343
+ "register": {
3344
+ "target": "register",
3345
+ "purpose": "register"
3346
+ }
3347
+ }
3348
+ },
3349
+ {
3350
+ "name": "identifier",
3351
+ "fields": ["email"],
3352
+ "actions": [
3353
+ {
3354
+ "name": "submit",
3355
+ "kind": "submit",
3356
+ "primary": true,
3357
+ "text_key": "identifier.action.continue"
3358
+ },
3359
+ {
3360
+ "name": "passkey",
3361
+ "kind": "passkey",
3362
+ "primary": false,
3363
+ "text_key": "identifier.action.passkey"
3364
+ },
3365
+ {
3366
+ "name": "register",
3367
+ "kind": "navigate",
3368
+ "primary": false,
3369
+ "text_key": "identifier.action.register.link"
3370
+ }
3371
+ ],
3372
+ "transitions": {
3373
+ "submit": { "target": "password" },
3374
+ "passkey": { "target": "done" },
3375
+ "user_not_found": { "target": "register" },
3376
+ "register": {
3377
+ "target": "register",
3378
+ "purpose": "register"
3379
+ }
3380
+ }
3381
+ },
3382
+ {
3383
+ "name": "password",
3384
+ "fields": ["x-auth-methods#password"],
3385
+ "actions": [{
3386
+ "name": "submit",
3387
+ "kind": "submit",
3388
+ "primary": true,
3389
+ "text_key": "password.action.signin"
3390
+ }, {
3391
+ "name": "passkey",
3392
+ "kind": "passkey",
3393
+ "primary": false,
3394
+ "text_key": "password.action.passkey"
3395
+ }],
3396
+ "transitions": {
3397
+ "submit": { "target": "done" },
3398
+ "passkey": { "target": "done" }
3399
+ }
3400
+ },
3401
+ {
3402
+ "name": "register",
3403
+ "fields": ["email"],
3404
+ "actions": [
3405
+ {
3406
+ "name": "passkey_register",
3407
+ "kind": "passkey_register",
3408
+ "primary": true,
3409
+ "text_key": "register.action.passkey"
3410
+ },
3411
+ {
3412
+ "name": "submit",
3413
+ "kind": "submit",
3414
+ "primary": false,
3415
+ "text_key": "register.action.password"
3416
+ },
3417
+ {
3418
+ "name": "sign_in",
3419
+ "kind": "navigate",
3420
+ "primary": false,
3421
+ "text_key": "register.action.sign_in.link"
3422
+ }
3423
+ ],
3424
+ "transitions": {
3425
+ "passkey_register": { "target": "done" },
3426
+ "submit": { "target": "register-password" },
3427
+ "user_already_exists": { "target": "password" },
3428
+ "sign_in": {
3429
+ "target": "passkey-first",
3430
+ "purpose": "login"
3431
+ }
3432
+ }
3433
+ },
3434
+ {
3435
+ "name": "register-password",
3436
+ "fields": ["x-auth-methods#password"],
3437
+ "actions": [{
3438
+ "name": "submit",
3439
+ "kind": "submit",
3440
+ "primary": true,
3441
+ "text_key": "register-password.action.submit"
3442
+ }],
3443
+ "on_success": "create_user",
3444
+ "transitions": {
3445
+ "submit": { "target": "done" },
3446
+ "user_already_exists": { "target": "password" }
3447
+ }
3448
+ },
3449
+ {
3450
+ "name": "done",
3451
+ "complete": "show"
3452
+ }
3453
+ ]
3454
+ };
3455
+ const DEFAULT_BUILTIN_SCHEMA_BASE = "https://zitadel.com/schemas/v1";
3456
+ const DEFAULT_FLOW_SCHEMA_URI = `${DEFAULT_BUILTIN_SCHEMA_BASE}/flow-definition.json`;
3457
+ /**
3458
+ * Named schema+flow bundles `zitadel setup` can scaffold (#448: the prompt
3459
+ * fires before any `.zitadel/` file is written; each preset maps to a
3460
+ * pre-defined bundle the CLI copies on first setup). `password-first` is
3461
+ * today's default; `passkey-first` puts a passkey ceremony on the login
3462
+ * entry step with an email→password fallback path.
3463
+ */
3464
+ const SETUP_PRESETS = ["password-first", "passkey-first"];
3465
+ const PRESET_TEMPLATES = {
3466
+ "password-first": {
3467
+ schema: default_human_user_default,
3468
+ flow: default_login_default
3469
+ },
3470
+ "passkey-first": {
3471
+ schema: human_user_default,
3472
+ flow: login_default
3473
+ }
3474
+ };
3475
+ function presetTemplates(preset) {
3476
+ if (!Object.hasOwn(PRESET_TEMPLATES, preset)) throw new Error(`unknown setup preset ${JSON.stringify(preset)} (known presets: ${SETUP_PRESETS.join(", ")})`);
3477
+ return PRESET_TEMPLATES[preset];
3478
+ }
3479
+ /**
3480
+ * The second setup axis (#448): *who* signs in, orthogonal to the sign-in
3481
+ * preset (*how* they sign in). The sign-in preset owns the flow shape and
3482
+ * auth methods; the use case owns which profile fields the schema collects.
3483
+ * Composing the two keeps us at one field catalog + one flow-per-preset
3484
+ * instead of a bundle per (use case × preset) pair. `minimal` is the
3485
+ * default and never blocks non-interactive runs.
3486
+ */
3487
+ const SETUP_USE_CASES = [
3488
+ "minimal",
3489
+ "consumer",
3490
+ "business"
3491
+ ];
3492
+ /**
3493
+ * Fields each use case collects, in register/display order. `email` is
3494
+ * always first and stays the only required property; the rest are optional
3495
+ * profile attributes gathered on the flow's register step. `givenName`/
3496
+ * `familyName` are the attributes the backend reads for a user's identity
3497
+ * (`internal/domain/user.go`); `companyName` is stored as a plain user
3498
+ * attribute today — there is no org/team model behind it yet.
3499
+ */
3500
+ const USE_CASE_FIELDS = {
3501
+ minimal: ["email"],
3502
+ consumer: [
3503
+ "email",
3504
+ "givenName",
3505
+ "familyName"
3506
+ ],
3507
+ business: [
3508
+ "email",
3509
+ "givenName",
3510
+ "familyName",
3511
+ "companyName"
3512
+ ]
3513
+ };
3514
+ /**
3515
+ * JSON-Schema bodies for the optional profile fields the CLI composes in per
3516
+ * use case. The shipped templates are an email-only baseline (shared verbatim
3517
+ * with the Go server fallback), so this catalog owns every field beyond
3518
+ * `email`. Authored in the templates' style — no `x-claim`, since the backend
3519
+ * maps identity by attribute name and the user-property meta-schema defines no
3520
+ * claim keyword. `givenName`/`familyName` are the attributes the backend reads
3521
+ * for a user's identity (`internal/domain/user.go`).
3522
+ */
3523
+ const EXTRA_FIELD_BODIES = {
3524
+ givenName: {
3525
+ type: "string",
3526
+ maxLength: 50,
3527
+ description: "The user's given (first) name."
3528
+ },
3529
+ familyName: {
3530
+ type: "string",
3531
+ maxLength: 50,
3532
+ description: "The user's family (last) name."
3533
+ },
3534
+ companyName: {
3535
+ type: "string",
3536
+ maxLength: 200,
3537
+ description: "The user's company name."
3538
+ }
3539
+ };
3540
+ function useCaseFields(useCase) {
3541
+ if (!Object.hasOwn(USE_CASE_FIELDS, useCase)) throw new Error(`unknown setup use case ${JSON.stringify(useCase)} (known use cases: ${SETUP_USE_CASES.join(", ")})`);
3542
+ return USE_CASE_FIELDS[useCase];
3543
+ }
3544
+ /**
3545
+ * The body for one use-case field: reuse the template's authored body when it
3546
+ * has one (so composed schemas match the shipped defaults for shared fields),
3547
+ * else the extra catalog, else a generic editable string so composition stays
3548
+ * total for any field a future use case introduces.
3549
+ */
3550
+ function fieldBody(field, templateProps) {
3551
+ if (Object.hasOwn(templateProps, field)) return { ...templateProps[field] };
3552
+ if (Object.hasOwn(EXTRA_FIELD_BODIES, field)) return { ...EXTRA_FIELD_BODIES[field] };
3553
+ return {
3554
+ type: "string",
3555
+ description: `The user's ${field}.`
3556
+ };
3557
+ }
3558
+ /**
3559
+ * Narrow a rendered schema to the chosen use case: keep the preset-owned
3560
+ * header and `x-auth-methods`, but replace `properties`/`required` with the
3561
+ * use case's field set. `email` is the sole required property.
3562
+ */
3563
+ function applyUseCaseToSchema(schema, useCase) {
3564
+ const templateProps = schema.properties ?? {};
3565
+ const properties = {};
3566
+ for (const field of useCaseFields(useCase)) properties[field] = fieldBody(field, templateProps);
3567
+ return {
3568
+ ...schema,
3569
+ required: ["email"],
3570
+ properties
3571
+ };
3572
+ }
3573
+ /**
3574
+ * Derive the flow's register-step fields from the use case rather than
3575
+ * copying a hard-coded list into every bundle (#448): the register step
3576
+ * collects exactly what the schema defines. Other steps are untouched.
3577
+ */
3578
+ function applyUseCaseToFlow(flow, useCase) {
3579
+ const fields = [...useCaseFields(useCase)];
3580
+ const steps = flow.steps.map((step) => step.name === "register" ? {
3581
+ ...step,
3582
+ fields
3583
+ } : step);
3584
+ return {
3585
+ ...flow,
3586
+ steps
3587
+ };
3588
+ }
3589
+ function defaultHumanUserSchemaUrl(builtinSchemaBase = DEFAULT_BUILTIN_SCHEMA_BASE) {
3590
+ return `${trimTrailingSlash(builtinSchemaBase)}/default-human-user.json`;
3591
+ }
3592
+ function getDefaultHumanUserSchema(options = {}) {
3593
+ const builtinSchemaBase = trimTrailingSlash(options.builtinSchemaBase ?? "https://zitadel.com/schemas/v1");
3594
+ return applyUseCaseToSchema(renderTemplate(presetTemplates(options.preset ?? "password-first").schema, {
3595
+ SERVER_URL: builtinSchemaBase,
3596
+ USER_SCHEMA_URL: options.userSchemaUrl ?? defaultHumanUserSchemaUrl(builtinSchemaBase)
3597
+ }), options.useCase ?? "minimal");
3598
+ }
3599
+ function getDefaultLoginFlow(options = {}) {
3600
+ const builtinSchemaBase = trimTrailingSlash(options.builtinSchemaBase ?? "https://zitadel.com/schemas/v1");
3601
+ return applyUseCaseToFlow(renderTemplate(presetTemplates(options.preset ?? "password-first").flow, { SERVER_URL: builtinSchemaBase }), options.useCase ?? "minimal");
3602
+ }
3603
+ function renderTemplate(value, replacements) {
3604
+ if (Array.isArray(value)) return value.map((item) => renderTemplate(item, replacements));
3605
+ if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, renderTemplate(item, replacements)]));
3606
+ if (typeof value === "string") return value.replaceAll(/\$\{([A-Z_]+)\}/g, (match, name) => {
3607
+ return replacements[name] ?? match;
3608
+ });
3609
+ return value;
3610
+ }
3611
+ function trimTrailingSlash(value) {
3612
+ let trimmed = value;
3613
+ while (trimmed.endsWith("/")) trimmed = trimmed.slice(0, -1);
3614
+ return trimmed;
3615
+ }
3616
+ //#endregion
3617
+ //#region src/bootstrap.ts
3618
+ const DEFAULT_PROJECT_NAME = "zitadel-testing";
3619
+ /**
3620
+ * Server-side half of `zitadel setup`, without any file scaffolding:
3621
+ * `POST /projects` is unauthenticated and mints the projectSecret used as the
3622
+ * bearer for everything else; the schema is uploaded without `$id` so the
3623
+ * server assigns an opaque id, which the flow must then reference.
3624
+ */
3625
+ async function bootstrapProject(options) {
3626
+ const { baseUrl } = options;
3627
+ const project = await createZitadelClient({ baseUrl }).createProject({
3628
+ name: options.projectName ?? DEFAULT_PROJECT_NAME,
3629
+ origins: (options.appOrigins ?? []).map((pattern) => ({
3630
+ pattern,
3631
+ kind: "preview"
3632
+ })),
3633
+ seed_defaults: false
3634
+ });
3635
+ const projectId = requireString(project.id, "project id");
3636
+ const projectSecret = requireString(project.project_secret, "project secret");
3637
+ const previewSecret = typeof project.preview_secret === "string" ? project.preview_secret : void 0;
3638
+ const client = createZitadelClient({
3639
+ baseUrl,
3640
+ token: projectSecret
3641
+ });
3642
+ const { $id: _templateId, ...schemaBody } = getDefaultHumanUserSchema({
3643
+ preset: options.preset,
3644
+ useCase: options.useCase
3645
+ });
3646
+ const schemaId = requireString((await client.createSchema(schemaBody, { project_id: projectId })).id, "schema id");
3647
+ const flowBody = getDefaultLoginFlow({
3648
+ preset: options.preset,
3649
+ useCase: options.useCase
3650
+ });
3651
+ return {
3652
+ projectId,
3653
+ projectSecret,
3654
+ previewSecret,
3655
+ schemaId,
3656
+ flowId: requireString((await client.createFlowDefinition({
3657
+ project_id: projectId,
3658
+ schema_uri: DEFAULT_FLOW_SCHEMA_URI,
3659
+ flow_definition: flowBody
3660
+ })).id, "flow definition id")
3661
+ };
3662
+ }
3663
+ function requireString(value, label) {
3664
+ if (typeof value === "string" && value.length > 0) return value;
3665
+ throw new Error(`Missing ${label} in server response.`);
3666
+ }
3667
+ //#endregion
3668
+ //#region src/cli.ts
3669
+ const DEFAULT_TIMEOUT_MS = 12e4;
3670
+ function resolveCliBin() {
3671
+ const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
3672
+ const pkgPath = require$1.resolve("@zitadel/cli/package.json");
3673
+ const rel = require$1(pkgPath).bin?.zitadel;
3674
+ if (!rel) throw new Error("@zitadel/cli does not declare a `zitadel` bin entry");
3675
+ return (0, node_path.join)((0, node_path.dirname)(pkgPath), rel);
3676
+ }
3677
+ function runCli(options) {
3678
+ const bin = options.bin ?? resolveCliBin();
3679
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
3680
+ return new Promise((resolve, reject) => {
3681
+ const child = (0, node_child_process.spawn)(process.execPath, [bin, ...options.args], {
3682
+ env: {
3683
+ ...process.env,
3684
+ ...options.env
3685
+ },
3686
+ stdio: [
3687
+ "ignore",
3688
+ "pipe",
3689
+ "pipe"
3690
+ ]
3691
+ });
3692
+ let stdout = "";
3693
+ let stderr = "";
3694
+ child.stdout.setEncoding("utf8");
3695
+ child.stdout.on("data", (chunk) => {
3696
+ stdout += chunk;
3697
+ });
3698
+ child.stderr.setEncoding("utf8");
3699
+ child.stderr.on("data", (chunk) => {
3700
+ stderr += chunk;
3701
+ });
3702
+ const timer = setTimeout(() => {
3703
+ child.kill("SIGKILL");
3704
+ reject(/* @__PURE__ */ new Error(`zitadel ${options.args[0] ?? ""} timed out after ${timeoutMs}ms\n${tail(stderr)}`));
3705
+ }, timeoutMs);
3706
+ timer.unref();
3707
+ child.on("error", (error) => {
3708
+ clearTimeout(timer);
3709
+ reject(error);
3710
+ });
3711
+ child.on("close", (code) => {
3712
+ clearTimeout(timer);
3713
+ resolve({
3714
+ exitCode: code ?? -1,
3715
+ stdout,
3716
+ stderr
3717
+ });
3718
+ });
3719
+ });
3720
+ }
3721
+ function tail(text, lines = 20) {
3722
+ return text.split("\n").slice(-lines).join("\n").trim();
3723
+ }
3724
+ //#endregion
3725
+ //#region src/envelope.ts
3726
+ /**
3727
+ * Render an error envelope's remediation fields for humans — the CLI's
3728
+ * `hint`/`next_commands` are the actionable part of a failure (e.g. "Reinstall
3729
+ * @zitadel/cli so npm can install @zitadel/server"), so surface them instead
3730
+ * of a raw stdout dump. Returns undefined when the envelope has no message.
3731
+ */
3732
+ function describeEnvelopeError(envelope) {
3733
+ if (typeof envelope.message !== "string" || envelope.message.length === 0) return;
3734
+ const lines = [envelope.code ? `${envelope.code}: ${envelope.message}` : envelope.message];
3735
+ if (envelope.hint) lines.push(`hint: ${envelope.hint}`);
3736
+ if (envelope.next_commands && envelope.next_commands.length > 0) lines.push(`next: ${envelope.next_commands.join(" | ")}`);
3737
+ return lines.join("\n");
3738
+ }
3739
+ function parseCliEnvelope(stdout, context) {
3740
+ const start = stdout.indexOf("{");
3741
+ const end = stdout.lastIndexOf("}");
3742
+ if (start === -1 || end <= start) throw new Error(`${context}: expected a JSON envelope on stdout, got:\n${stdout.trim() || "(empty)"}`);
3743
+ let parsed;
3744
+ try {
3745
+ parsed = JSON.parse(stdout.slice(start, end + 1));
3746
+ } catch (error) {
3747
+ throw new Error(`${context}: failed to parse JSON envelope: ${error.message}\n${stdout.trim()}`, { cause: error });
3748
+ }
3749
+ if (typeof parsed !== "object" || parsed === null || typeof parsed.status !== "string") throw new Error(`${context}: stdout JSON is not a CLI envelope:\n${stdout.trim()}`);
3750
+ return parsed;
3751
+ }
3752
+ //#endregion
3753
+ //#region src/ports.ts
3754
+ /**
3755
+ * Ask the OS for a free TCP port. The port is released before returning, so a
3756
+ * racing process could grab it; the CLI's own preflight surfaces that as
3757
+ * E_PORT_IN_USE, which is loud rather than corrupting.
3758
+ */
3759
+ function getFreePort() {
3760
+ return new Promise((resolve, reject) => {
3761
+ const server = (0, node_net.createServer)();
3762
+ server.unref();
3763
+ server.on("error", reject);
3764
+ server.listen(0, "127.0.0.1", () => {
3765
+ const address = server.address();
3766
+ if (address === null || typeof address === "string") {
3767
+ server.close();
3768
+ reject(/* @__PURE__ */ new Error("could not determine a free port"));
3769
+ return;
3770
+ }
3771
+ const { port } = address;
3772
+ server.close((err) => {
3773
+ if (err) {
3774
+ reject(err);
3775
+ return;
3776
+ }
3777
+ resolve(port);
3778
+ });
3779
+ });
3780
+ });
3781
+ }
3782
+ //#endregion
3783
+ //#region src/lifecycle.ts
3784
+ /**
3785
+ * Boot an ephemeral local server by shelling out to `zitadel start` and parse
3786
+ * its JSON envelope. The CLI owns the subtle parts (port preflight, health
3787
+ * wait, process-group stop), so this module stays a thin adapter; swapping it
3788
+ * for direct library calls later must not change the shape returned here.
3789
+ */
3790
+ async function bootLocalServer(options = {}) {
3791
+ const ownsDir = options.dir === void 0;
3792
+ const dir = options.dir ?? await (0, node_fs_promises.mkdtemp)((0, node_path.join)((0, node_os.tmpdir)(), "zitadel-testing-"));
3793
+ const port = options.port ?? await getFreePort();
3794
+ const env = {};
3795
+ if (options.serverBinary) env.ZITADEL_SERVER_BINARY = options.serverBinary;
3796
+ const result = await runCli({
3797
+ args: [
3798
+ "start",
3799
+ "--port",
3800
+ String(port),
3801
+ "--non-interactive",
3802
+ "--json",
3803
+ "-c",
3804
+ dir
3805
+ ],
3806
+ bin: options.cliBin,
3807
+ env,
3808
+ timeoutMs: options.timeoutMs
3809
+ });
3810
+ if (result.exitCode !== 0) throw new Error(`zitadel start exited with code ${result.exitCode}.\n${failureDetail(result)}\nstate dir kept for inspection: ${dir}`);
3811
+ const stopViaCli = async () => {
3812
+ const stopResult = await runCli({
3813
+ args: [
3814
+ "stop",
3815
+ "--non-interactive",
3816
+ "--json",
3817
+ "-c",
3818
+ dir
3819
+ ],
3820
+ bin: options.cliBin,
3821
+ env,
3822
+ timeoutMs: options.timeoutMs
3823
+ });
3824
+ if (stopResult.exitCode !== 0) throw new Error(`zitadel stop exited with code ${stopResult.exitCode}.\n${failureDetail(stopResult)}\nstate dir kept for inspection: ${dir}`);
3825
+ };
3826
+ let envelope;
3827
+ try {
3828
+ envelope = parseCliEnvelope(result.stdout, "zitadel start");
3829
+ if (envelope.status !== "ok") throw new Error(`zitadel start reported status "${envelope.status}":\n${describeEnvelopeError(envelope) ?? tail(result.stdout)}`);
3830
+ } catch (error) {
3831
+ const startError = new Error(`zitadel start produced unusable output.\nreason: ${error instanceof Error ? error.message : String(error)}\nstdout: ${tail(result.stdout) || "(empty)"}\nstderr: ${tail(result.stderr) || "(empty)"}\nstate dir kept for inspection: ${dir}`, { cause: error });
3832
+ try {
3833
+ await stopViaCli();
3834
+ } catch (stopError) {
3835
+ throw new AggregateError([startError, stopError], `${startError.message}\nStopping the possibly-running instance also failed: ${stopError instanceof Error ? stopError.message : String(stopError)}`);
3836
+ }
3837
+ throw startError;
3838
+ }
3839
+ const { runtime, urls } = envelope.data;
3840
+ const runStop = async () => {
3841
+ await stopViaCli();
3842
+ if (ownsDir && !options.keep) await (0, node_fs_promises.rm)(dir, {
3843
+ recursive: true,
3844
+ force: true
3845
+ });
3846
+ };
3847
+ let stopPromise;
3848
+ const stop = () => {
3849
+ stopPromise ??= runStop().catch((error) => {
3850
+ stopPromise = void 0;
3851
+ throw error;
3852
+ });
3853
+ return stopPromise;
3854
+ };
3855
+ return {
3856
+ baseUrl: urls.api,
3857
+ runtime: {
3858
+ port: runtime.port,
3859
+ pid: runtime.pid,
3860
+ dir,
3861
+ logPath: runtime.log_path
3862
+ },
3863
+ stop
3864
+ };
3865
+ }
3866
+ /**
3867
+ * A failed CLI run usually still prints an error envelope; its
3868
+ * message/hint/next_commands beat raw output tails (e.g. a fresh install
3869
+ * missing @zitadel/server gets "Reinstall @zitadel/cli" instead of a stack).
3870
+ */
3871
+ function failureDetail(result) {
3872
+ try {
3873
+ const described = describeEnvelopeError(parseCliEnvelope(result.stdout, "zitadel"));
3874
+ if (described) return described;
3875
+ } catch {}
3876
+ return `stdout: ${tail(result.stdout) || "(empty)"}\nstderr: ${tail(result.stderr) || "(empty)"}`;
3877
+ }
3878
+ //#endregion
3879
+ //#region src/seed.ts
3880
+ /**
3881
+ * A unique unused email + password. Nothing is created on the instance —
3882
+ * this is the input for registration-flow specs, which must prove the flow
3883
+ * creates the user. It needs no instance either, so both entry points export
3884
+ * it for specs that run without `withZitadel()`; `seed.identity()` and
3885
+ * `zitadel.identity()` call this function.
3886
+ */
3887
+ function identity() {
3888
+ return {
3889
+ email: `e2e-${(0, node_crypto.randomUUID)().slice(0, 8)}@example.com`,
3890
+ password: `Pw!${(0, node_crypto.randomUUID)()}`
3891
+ };
3892
+ }
3893
+ /**
3894
+ * Create a user that can immediately complete the password login flow:
3895
+ * `POST /users` (the body carries `schema: <schema id>` and the schema-defined
3896
+ * content under `attributes`) followed by `PUT /users/{id}/password`.
3897
+ *
3898
+ * Defaults mint a unique email per call (email is x-unique per project), which
3899
+ * is what makes per-test seeding parallel-safe on a shared instance.
3900
+ */
3901
+ async function seedUser(client, context, input = {}) {
3902
+ const fresh = identity();
3903
+ const email = input.email ?? fresh.email;
3904
+ const password = input.password ?? fresh.password;
3905
+ const id = requireString((await client.createUser({
3906
+ schema: context.schemaId,
3907
+ attributes: {
3908
+ ...input.attributes,
3909
+ email
3910
+ }
3911
+ }, { project_id: context.projectId })).id, "user id");
3912
+ await client.setUserPassword(id, { password });
3913
+ return {
3914
+ id,
3915
+ email,
3916
+ password
3917
+ };
3918
+ }
3919
+ /**
3920
+ * Seed `count` users sequentially. The template makes fixture data
3921
+ * deterministic per index (stable emails/names keep screenshot diffs about
3922
+ * code, not reshuffled data — the `console:dev-real` pattern); untemplated
3923
+ * fields fall back to the unique defaults. Name-like attributes need a
3924
+ * schema that declares them (`useCase: "consumer"` or wider).
3925
+ */
3926
+ async function seedUsers(client, context, count, template = {}) {
3927
+ const users = [];
3928
+ for (let index = 0; index < count; index += 1) users.push(await seedUser(client, context, {
3929
+ email: template.email?.(index),
3930
+ password: template.password?.(index),
3931
+ attributes: template.attributes?.(index)
3932
+ }));
3933
+ return users;
3934
+ }
3935
+ //#endregion
3936
+ //#region src/session.ts
3937
+ /**
3938
+ * Mirrors the server's session cookie (internal/api/session.go): the name a
3939
+ * direct call to the server sends, and the one an app keeps behind a proxy that
3940
+ * passes the server's cookie through, such as an SPA's in production.
3941
+ */
3942
+ const SESSION_COOKIE_NAME = "__nextgen_session";
3943
+ /**
3944
+ * The cookie an app keeps its session in on its own origin behind a server SDK
3945
+ * (Next.js, Nuxt, SvelteKit, SolidStart, TanStack Start, Qwik Router) or the dev
3946
+ * proxy `zitadel setup` writes for an SPA: `__nextgen_session_<projectId>`. The
3947
+ * proxy renames the server's cookie, so the apps and the Console on one host
3948
+ * keep a session each (ADR 073).
3949
+ *
3950
+ * Mirrors `sessionCookieName` in `@zitadel/sdk-core`, including the
3951
+ * percent-encoding of every byte outside `[A-Za-z0-9_-]`.
3952
+ */
3953
+ function sessionCookieName(projectId) {
3954
+ let name = `${SESSION_COOKIE_NAME}_`;
3955
+ for (const byte of new TextEncoder().encode(projectId)) {
3956
+ const char = String.fromCharCode(byte);
3957
+ name += /[A-Za-z0-9_-]/.test(char) ? char : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
3958
+ }
3959
+ return name;
3960
+ }
3961
+ const MAX_FLOW_STEPS = 6;
3962
+ /**
3963
+ * Drive the real login flow headlessly for a seeded password user and
3964
+ * exchange the terminal handoff for a session: exactly what `<zitadel-login>`
3965
+ * does, minus the rendering. Supports flows whose steps only ask for the
3966
+ * user's email and password (the shipped `password-first` presets); any step
3967
+ * demanding more — a challenge, an unknown field — fails loudly by design.
3968
+ *
3969
+ * Flow calls use raw fetch instead of the typed client because the flow is
3970
+ * stateless through the sealed `_zflow` cookie (internal/api/flow.go): every
3971
+ * response re-seals the flow state into Set-Cookie, and submits are rejected
3972
+ * without it. Browsers round-trip it implicitly; here a one-cookie jar does.
3973
+ */
3974
+ async function mintSession(client, handle, context, user, options = {}) {
3975
+ const values = {
3976
+ email: user.email,
3977
+ password: user.password
3978
+ };
3979
+ const jar = new FlowCookieJar();
3980
+ const origin = options.origin;
3981
+ let response = await flowFetch(handle, jar, origin, "/flow", {
3982
+ project_id: context.projectId,
3983
+ purpose: "login",
3984
+ ...options.flowDefinitionName ? { flow_definition_name: options.flowDefinitionName } : {}
3985
+ });
3986
+ for (let hop = 0; hop < MAX_FLOW_STEPS; hop += 1) {
3987
+ if (response.handoff_token) {
3988
+ const exchanged = await client.exchangeHandoff({ handoff_token: response.handoff_token }, { project_id: context.projectId });
3989
+ return {
3990
+ user,
3991
+ sessionToken: exchanged.session_token,
3992
+ expiresAt: exchanged.session.expires_at,
3993
+ cookie: {
3994
+ name: SESSION_COOKIE_NAME,
3995
+ value: exchanged.session_token,
3996
+ httpOnly: true,
3997
+ secure: true,
3998
+ sameSite: "Lax",
3999
+ path: "/"
4000
+ }
4001
+ };
4002
+ }
4003
+ response = await flowFetch(handle, jar, origin, `/flow/${encodeURIComponent(response.id)}/submit`, {
4004
+ session_token: response.session_token,
4005
+ action: "submit",
4006
+ fields: collectFields(response, values)
4007
+ });
4008
+ }
4009
+ throw new Error(`seed.session: flow did not complete within ${MAX_FLOW_STEPS} steps (last step: ${describeStep(response)}).`);
4010
+ }
4011
+ /** One-cookie jar for the sealed `_zflow` flow-state cookie. */
4012
+ var FlowCookieJar = class {
4013
+ cookie;
4014
+ absorb(response) {
4015
+ for (const raw of response.headers.getSetCookie()) {
4016
+ const [pair] = raw.split(";", 1);
4017
+ if (pair?.startsWith("_zflow=")) this.cookie = pair;
4018
+ }
4019
+ }
4020
+ header() {
4021
+ return this.cookie ? { cookie: this.cookie } : {};
4022
+ }
4023
+ };
4024
+ async function flowFetch(handle, jar, origin, path, body) {
4025
+ const response = await fetch(`${handle.baseUrl}${path}`, {
4026
+ method: "POST",
4027
+ headers: {
4028
+ "content-type": "application/json",
4029
+ authorization: `Bearer ${handle.projectSecret}`,
4030
+ ...origin ? { origin } : {},
4031
+ ...jar.header()
4032
+ },
4033
+ body: JSON.stringify(body)
4034
+ });
4035
+ jar.absorb(response);
4036
+ const parsed = await response.json().catch(() => void 0);
4037
+ if (!response.ok || !parsed) {
4038
+ const detail = parsed && typeof parsed === "object" ? ` — ${JSON.stringify(parsed)}` : "";
4039
+ const hint = !origin && /origin/i.test(detail) ? "\nNo Origin header was sent: pass `origin` to seedSession() (the Playwright fixtures pass the suite's baseURL) or `appOrigins` to startLocalZitadel()." : "";
4040
+ throw new Error(`seed.session: POST ${path} returned ${response.status}${detail}${hint}`);
4041
+ }
4042
+ return parsed;
4043
+ }
4044
+ /**
4045
+ * Fill exactly the fields the current step declares — the orchestrator's
4046
+ * convention — from the known email/password values. An unknown required
4047
+ * field means this flow needs more than a password login can provide.
4048
+ */
4049
+ function collectFields(response, values) {
4050
+ const fields = {};
4051
+ for (const field of response.step.fields ?? []) {
4052
+ const value = values[fieldKey(field)];
4053
+ if (value === void 0) throw new Error(`seed.session supports password flows only; step ${describeStep(response)} declares field "${field.name}", which the kit cannot fill. Log in through the UI for flows with additional factors.`);
4054
+ fields[field.name] = value;
4055
+ }
4056
+ return fields;
4057
+ }
4058
+ /**
4059
+ * Steps name credential fields with schema pointers (e.g.
4060
+ * `x-auth-methods#password`); match on the trailing segment so the value map
4061
+ * stays the plain `{ email, password }` a caller thinks in.
4062
+ */
4063
+ function fieldKey(field) {
4064
+ const name = field.name;
4065
+ return (name.split(/[#/.]/).at(-1) ?? name).toLowerCase();
4066
+ }
4067
+ function describeStep(response) {
4068
+ const name = response.step.name ?? "(unnamed)";
4069
+ const declared = (response.step.fields ?? []).map((field) => field.name).join(", ");
4070
+ return `"${name}"${declared ? ` [fields: ${declared}]` : ""}`;
4071
+ }
4072
+ //#endregion
4073
+ //#region src/index.ts
4074
+ /**
4075
+ * Attach to an already-bootstrapped instance/project. Lifecycle-free on
4076
+ * purpose: this is the entry point for Playwright workers (via the handshake
4077
+ * file) and, later, for seeding remote instances.
4078
+ */
4079
+ function connectZitadel(handle) {
4080
+ const api = createZitadelClient({
4081
+ baseUrl: handle.baseUrl,
4082
+ token: handle.projectSecret
4083
+ });
4084
+ const context = {
4085
+ projectId: handle.projectId,
4086
+ schemaId: handle.schemaId
4087
+ };
4088
+ return {
4089
+ handle,
4090
+ api,
4091
+ appEnv: require_handshake.applyAppEnvTemplate(require_handshake.nextAppEnv, handle),
4092
+ seedUser: (input) => seedUser(api, context, input),
4093
+ seedUsers: (count, template) => seedUsers(api, context, count, template),
4094
+ identity,
4095
+ seedSession: async (input = {}) => {
4096
+ const { user: existing, flowDefinitionName, origin, ...userInput } = input;
4097
+ const user = existing ?? await seedUser(api, context, userInput);
4098
+ return mintSession(api, handle, context, user, {
4099
+ flowDefinitionName,
4100
+ origin: origin ?? handle.appOrigin
4101
+ });
4102
+ }
4103
+ };
4104
+ }
4105
+ /**
4106
+ * Boot an ephemeral local instance (binary runtime + SQLite by default, no
4107
+ * Docker) and bootstrap a project + default schema + login flow on it. The
4108
+ * result can seed loginable password users immediately.
4109
+ */
4110
+ async function startLocalZitadel(options = {}) {
4111
+ const server = await bootLocalServer(options);
4112
+ let bootstrapped;
4113
+ try {
4114
+ bootstrapped = await bootstrapProject({
4115
+ baseUrl: server.baseUrl,
4116
+ projectName: options.projectName,
4117
+ appOrigins: options.appOrigins,
4118
+ preset: options.preset,
4119
+ useCase: options.useCase
4120
+ });
4121
+ } catch (error) {
4122
+ try {
4123
+ await server.stop();
4124
+ } catch (stopError) {
4125
+ throw new AggregateError([error, stopError], "bootstrap failed, and stopping the booted instance also failed");
4126
+ }
4127
+ throw error;
4128
+ }
4129
+ return {
4130
+ ...connectZitadel({
4131
+ baseUrl: server.baseUrl,
4132
+ projectId: bootstrapped.projectId,
4133
+ projectSecret: bootstrapped.projectSecret,
4134
+ schemaId: bootstrapped.schemaId,
4135
+ previewSecret: bootstrapped.previewSecret,
4136
+ appOrigin: options.appOrigins?.[0]
4137
+ }),
4138
+ runtime: server.runtime,
4139
+ stop: server.stop,
4140
+ [Symbol.asyncDispose]: server.stop
4141
+ };
4142
+ }
4143
+ //#endregion
4144
+ Object.defineProperty(exports, "SESSION_COOKIE_NAME", {
4145
+ enumerable: true,
4146
+ get: function() {
4147
+ return SESSION_COOKIE_NAME;
4148
+ }
4149
+ });
4150
+ Object.defineProperty(exports, "bootLocalServer", {
4151
+ enumerable: true,
4152
+ get: function() {
4153
+ return bootLocalServer;
4154
+ }
4155
+ });
4156
+ Object.defineProperty(exports, "bootstrapProject", {
4157
+ enumerable: true,
4158
+ get: function() {
4159
+ return bootstrapProject;
4160
+ }
4161
+ });
4162
+ Object.defineProperty(exports, "connectZitadel", {
4163
+ enumerable: true,
4164
+ get: function() {
4165
+ return connectZitadel;
4166
+ }
4167
+ });
4168
+ Object.defineProperty(exports, "identity", {
4169
+ enumerable: true,
4170
+ get: function() {
4171
+ return identity;
4172
+ }
4173
+ });
4174
+ Object.defineProperty(exports, "sessionCookieName", {
4175
+ enumerable: true,
4176
+ get: function() {
4177
+ return sessionCookieName;
4178
+ }
4179
+ });
4180
+ Object.defineProperty(exports, "startLocalZitadel", {
4181
+ enumerable: true,
4182
+ get: function() {
4183
+ return startLocalZitadel;
4184
+ }
4185
+ });
4186
+
4187
+ //# sourceMappingURL=src-CUvV1OWp.cjs.map