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