@zitadel/api 0.2.0 → 0.4.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 (89) hide show
  1. package/README.md +17 -3
  2. package/dist/api-factory-C5b1Gqwv.mjs +357 -0
  3. package/dist/api-factory-C5b1Gqwv.mjs.map +1 -0
  4. package/dist/api-factory-Dt5lUjyu.d.mts +212 -0
  5. package/dist/api-factory-Dt5lUjyu.d.mts.map +1 -0
  6. package/dist/{fetch-CtYe0OvX.d.mts → fetch-B-lgjlrf.d.mts} +22 -12
  7. package/dist/fetch-B-lgjlrf.d.mts.map +1 -0
  8. package/dist/generated/endpoints/zitadelNextGen.d.mts +2 -2
  9. package/dist/generated/endpoints/zitadelNextGen.mjs +192 -124
  10. package/dist/generated/endpoints/zitadelNextGen.mjs.map +1 -1
  11. package/dist/generated/endpoints/zitadelNextGen.msw.d.mts +3 -1
  12. package/dist/generated/endpoints/zitadelNextGen.msw.d.mts.map +1 -1
  13. package/dist/generated/endpoints/zitadelNextGen.msw.mjs +40 -7
  14. package/dist/generated/endpoints/zitadelNextGen.msw.mjs.map +1 -1
  15. package/dist/generated/endpoints/zitadelNextGen.zod.d.mts +104 -28
  16. package/dist/generated/endpoints/zitadelNextGen.zod.d.mts.map +1 -1
  17. package/dist/generated/endpoints/zitadelNextGen.zod.mjs +117 -37
  18. package/dist/generated/endpoints/zitadelNextGen.zod.mjs.map +1 -1
  19. package/dist/generated/model/index.d.mts +2 -2
  20. package/dist/generated/model/index.mjs +5 -1
  21. package/dist/generated/model/index.mjs.map +1 -1
  22. package/dist/generated/operations.mjs +22 -1
  23. package/dist/generated/operations.mjs.map +1 -1
  24. package/dist/{index-D7-l5LV6.d.mts → index-DGQY1rfH.d.mts} +398 -10
  25. package/dist/index-DGQY1rfH.d.mts.map +1 -0
  26. package/dist/runtime/api-factory.d.mts +2 -51
  27. package/dist/runtime/api-factory.mjs +3 -62
  28. package/dist/runtime/auth.mjs +1 -1
  29. package/dist/runtime/auth.mjs.map +1 -1
  30. package/dist/runtime/base-url.d.mts +14 -0
  31. package/dist/runtime/base-url.d.mts.map +1 -1
  32. package/dist/runtime/base-url.mjs +22 -1
  33. package/dist/runtime/base-url.mjs.map +1 -1
  34. package/dist/runtime/config.d.mts +1 -1
  35. package/dist/runtime/config.mjs +1 -1
  36. package/dist/runtime/fetch.d.mts +2 -2
  37. package/dist/runtime/fetch.mjs +41 -17
  38. package/dist/runtime/fetch.mjs.map +1 -1
  39. package/dist/runtime/paging.d.mts +35 -0
  40. package/dist/runtime/paging.d.mts.map +1 -0
  41. package/dist/runtime/paging.mjs +38 -0
  42. package/dist/runtime/paging.mjs.map +1 -0
  43. package/dist/{zitadelNextGen-Cw3DrCn1.d.mts → zitadelNextGen-BVO4sdKD.d.mts} +69 -34
  44. package/dist/zitadelNextGen-BVO4sdKD.d.mts.map +1 -0
  45. package/package.json +7 -1
  46. package/src/generated/endpoints/zitadelNextGen.faker.ts +9 -6
  47. package/src/generated/endpoints/zitadelNextGen.msw.ts +16 -1
  48. package/src/generated/endpoints/zitadelNextGen.ts +212 -125
  49. package/src/generated/endpoints/zitadelNextGen.zod.ts +120 -36
  50. package/src/generated/model/createFlowDefinition201UserSchemaMetadata.ts +5 -0
  51. package/src/generated/model/deleteUserByID409.ts +20 -0
  52. package/src/generated/model/deleteUserByID409Details.ts +12 -0
  53. package/src/generated/model/deleteUserByIDDefault.ts +9 -0
  54. package/src/generated/model/evaluatePolicy200.ts +30 -0
  55. package/src/generated/model/evaluatePolicy200Violations.ts +14 -0
  56. package/src/generated/model/evaluatePolicyBody.ts +82 -0
  57. package/src/generated/model/evaluatePolicyDefault.ts +90 -0
  58. package/src/generated/model/evaluatePolicyParams.ts +15 -0
  59. package/src/generated/model/getFlowDefinition200UserSchemaMetadata.ts +5 -0
  60. package/src/generated/model/getFlowStepDefault.ts +9 -0
  61. package/src/generated/model/getMyUserSchema200Metadata.ts +5 -0
  62. package/src/generated/model/getSchemaById200Metadata.ts +5 -0
  63. package/src/generated/model/index.ts +8 -0
  64. package/src/generated/model/listFlowDefinitions200FlowDefinitionsItemUserSchemaMetadata.ts +5 -0
  65. package/src/generated/model/listSchemas200SchemasItemMetadata.ts +5 -0
  66. package/src/generated/model/listSchemasExpandItem.ts +28 -0
  67. package/src/generated/model/listSchemasParams.ts +5 -0
  68. package/src/generated/model/queryTeamsParams.ts +3 -2
  69. package/src/generated/model/queryUsersBodyFilterItem.ts +11 -3
  70. package/src/generated/model/queryUsersBodyFilterItemField.ts +12 -3
  71. package/src/generated/model/submitFlowStepDefault.ts +9 -0
  72. package/src/generated/operations.ts +24 -1
  73. package/src/generated/paging.ts +128 -0
  74. package/src/runtime/api-factory.spec.ts +278 -0
  75. package/src/runtime/api-factory.ts +93 -12
  76. package/src/runtime/auth.ts +1 -1
  77. package/src/runtime/base-url.spec.ts +40 -4
  78. package/src/runtime/base-url.ts +28 -0
  79. package/src/runtime/fetch.spec.ts +51 -0
  80. package/src/runtime/fetch.ts +69 -30
  81. package/src/runtime/paged.spec.ts +104 -0
  82. package/src/runtime/paged.ts +61 -0
  83. package/src/runtime/paging.spec.ts +94 -0
  84. package/src/runtime/paging.ts +58 -0
  85. package/dist/fetch-CtYe0OvX.d.mts.map +0 -1
  86. package/dist/index-D7-l5LV6.d.mts.map +0 -1
  87. package/dist/runtime/api-factory.d.mts.map +0 -1
  88. package/dist/runtime/api-factory.mjs.map +0 -1
  89. package/dist/zitadelNextGen-Cw3DrCn1.d.mts.map +0 -1
@@ -1,4 +1,5 @@
1
1
  import { apiCsrfRejectionHandlerFor, apiCsrfTokenFor, getApiAuthToken } from "./auth";
2
+ import { API_PREFIX } from "./base-url";
2
3
 
3
4
  /** The header the session-bound CSRF token travels in (ADR 053 §5). */
4
5
  export const CSRF_HEADER = "X-Zitadel-CSRF";
@@ -9,6 +10,9 @@ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
9
10
  /** The code the server answers a refused CSRF check with. */
10
11
  const CSRF_INVALID = "auth.csrf_invalid";
11
12
 
13
+ /** The code the server answers a path no operation of its version has with (ADR 076). */
14
+ const ROUTE_NOT_FOUND = "req.not_found";
15
+
12
16
  /**
13
17
  * Framework-neutral failure type the orval-generated client throws on
14
18
  * any non-2xx response. Carries the HTTP status, the parsed error body
@@ -42,26 +46,27 @@ export class ApiError extends Error {
42
46
  }
43
47
 
44
48
  /**
45
- * Thrown when a request got no response at all: the connection was refused or
46
- * reset, the host did not resolve, or the server accepted the connection but
47
- * did not answer in time. The counterpart to {@link ApiError}, which is a
48
- * response that came back with a failing status.
49
+ * Thrown when a request got no usable response: the connection was refused or
50
+ * reset, the host did not resolve, the server accepted the connection but did
51
+ * not answer in time, or it answered with a body that could not be read. The
52
+ * counterpart to {@link ApiError}, which is a response that came back with a
53
+ * failing status.
49
54
  *
50
- * `fetch` only rejects when no response arrived, so this is decided by the
51
- * fact that it rejected, never by how a runtime words the failure. The
52
- * runtime's own error stays on `cause` for debugging.
55
+ * `fetch` only rejects when no response arrived, and reading the body only
56
+ * when the body broke off or could not be decoded, so this is decided by which
57
+ * of the two rejected, never by how a runtime words the failure. The runtime's
58
+ * own error stays on `cause` for debugging.
53
59
  */
54
60
  export class NetworkError extends Error {
55
61
  readonly url: string;
56
- /** `timeout` when a deadline cut the request off, `unreachable` otherwise. */
57
- readonly reason: "unreachable" | "timeout";
62
+ /**
63
+ * `timeout` when a deadline cut the request off, `unreadable` when a response
64
+ * arrived but its body could not be read (a proxy that labels a decoded body
65
+ * as compressed, say), `unreachable` otherwise.
66
+ */
67
+ readonly reason: NetworkErrorReason;
58
68
 
59
- constructor(
60
- url: string,
61
- reason: "unreachable" | "timeout",
62
- message: string,
63
- options?: ErrorOptions,
64
- ) {
69
+ constructor(url: string, reason: NetworkErrorReason, message: string, options?: ErrorOptions) {
65
70
  super(message, options);
66
71
  this.name = "NetworkError";
67
72
  this.url = url;
@@ -69,6 +74,9 @@ export class NetworkError extends Error {
69
74
  }
70
75
  }
71
76
 
77
+ /** Why a {@link NetworkError} got no usable response. */
78
+ export type NetworkErrorReason = "unreachable" | "unreadable" | "timeout";
79
+
72
80
  /**
73
81
  * What every request a client makes is bound by. Set per call by
74
82
  * `createZitadelClient`, the same way as the base URL and token, and read at
@@ -150,7 +158,13 @@ export async function customFetch<T>(url: string, options: RequestInit): Promise
150
158
  }
151
159
 
152
160
  if (!res.ok) {
153
- const message = `${options.method ?? "GET"} ${url} returned ${res.status}`;
161
+ // Every operation this client calls is one the spec has, so a server that
162
+ // knows no such path is another version, most likely one from before the
163
+ // API moved under its prefix.
164
+ const message =
165
+ res.status === 404 && apiErrorCode(parsed) === ROUTE_NOT_FOUND
166
+ ? `${options.method ?? "GET"} ${url} returned 404 (${ROUTE_NOT_FOUND}): the server has no such operation; a server older than this client does not serve the API under ${API_PREFIX}`
167
+ : `${options.method ?? "GET"} ${url} returned ${res.status}`;
154
168
  throw new ApiError(
155
169
  res.status,
156
170
  url,
@@ -160,6 +174,10 @@ export async function customFetch<T>(url: string, options: RequestInit): Promise
160
174
  );
161
175
  }
162
176
 
177
+ // The body is trusted to have the shape the generated types promise; no
178
+ // response is checked here or by the paged functions. Should that change,
179
+ // check it here, against the generated Zod response schemas, so every call
180
+ // is covered.
163
181
  return parsed as T;
164
182
  }
165
183
 
@@ -193,6 +211,8 @@ function isStream(body: RequestInit["body"]): boolean {
193
211
  * - a deadline fired → {@link NetworkError} with reason `timeout`;
194
212
  * - any other abort → the signal's own reason, rethrown untouched, because a
195
213
  * cancellation is the caller's decision and the caller knows what it means;
214
+ * - a response arrived but `read` failed → {@link NetworkError} with reason
215
+ * `unreadable`, naming the status that did come back;
196
216
  * - anything else → {@link NetworkError} with reason `unreachable`.
197
217
  *
198
218
  * Exported for the few callers that need the raw {@link Response} (a
@@ -210,25 +230,44 @@ export async function request<R = undefined>(
210
230
  }
211
231
  const signal = signals.length > 0 ? AbortSignal.any(signals) : undefined;
212
232
  const method = init.method ?? "GET";
233
+ let res: Response;
234
+ try {
235
+ res = await fetch(url, { ...init, signal });
236
+ } catch (error) {
237
+ throw failure(error, signal, method, url, "unreachable", "got no response");
238
+ }
213
239
  try {
214
- const res = await fetch(url, { ...init, signal });
215
240
  return { res, rawBody: (read ? await read(res) : undefined) as R };
216
241
  } catch (error) {
217
- if (signal?.aborted) {
218
- const reason: unknown = signal.reason;
219
- if (reason instanceof DOMException && reason.name === "TimeoutError") {
220
- throw new NetworkError(url, "timeout", `${method} ${url} timed out`, { cause: reason });
221
- }
222
- throw reason;
242
+ const what = `answered ${res.status}, but its body could not be read`;
243
+ throw failure(error, signal, method, url, "unreadable", what);
244
+ }
245
+ }
246
+
247
+ /**
248
+ * What {@link request} rejects with when `fetch` or `read` failed: the abort
249
+ * as {@link request} describes it, or else a {@link NetworkError} of `reason`
250
+ * saying `what` happened to the request.
251
+ */
252
+ function failure(
253
+ error: unknown,
254
+ signal: AbortSignal | undefined,
255
+ method: string,
256
+ url: string,
257
+ reason: "unreachable" | "unreadable",
258
+ what: string,
259
+ ): unknown {
260
+ if (signal?.aborted) {
261
+ const abort: unknown = signal.reason;
262
+ if (abort instanceof DOMException && abort.name === "TimeoutError") {
263
+ return new NetworkError(url, "timeout", `${method} ${url} timed out`, { cause: abort });
223
264
  }
224
- const code = errnoOf(error);
225
- throw new NetworkError(
226
- url,
227
- "unreachable",
228
- `${method} ${url} got no response${code ? ` (${code})` : ""}`,
229
- { cause: error },
230
- );
265
+ return abort;
231
266
  }
267
+ const code = errnoOf(error);
268
+ return new NetworkError(url, reason, `${method} ${url} ${what}${code ? ` (${code})` : ""}`, {
269
+ cause: error,
270
+ });
232
271
  }
233
272
 
234
273
  /**
@@ -0,0 +1,104 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+
3
+ import { paged } from "./paged";
4
+
5
+ /** Reads a page's `rows` and its cursor, as a generated table entry does. */
6
+ const rows = {
7
+ items: (page: { rows: string[] }) => page.rows,
8
+ next: (page: { next_page_token?: string }) => page.next_page_token,
9
+ withToken: ([id, params]: unknown[], page_token: string) => [
10
+ id,
11
+ Object.assign({}, params, { page_token }),
12
+ ],
13
+ };
14
+
15
+ /** Hooks that leave every page and failure as they are. */
16
+ const asIs = {
17
+ respond: (body: unknown) => body,
18
+ fail: (error: unknown): never => {
19
+ throw error;
20
+ },
21
+ };
22
+
23
+ describe("paged", () => {
24
+ /** A generated function taking `(id, params)`, answering two pages. */
25
+ function endpoint() {
26
+ return vi.fn(async (...args: unknown[]) => {
27
+ const params = args[1] as { page_token?: string; limit?: number } | undefined;
28
+ return params?.page_token === undefined
29
+ ? { rows: ["a"], next_page_token: "t1" }
30
+ : { rows: ["b"] };
31
+ });
32
+ }
33
+
34
+ it("fetches the next page with the arguments its shape builds from the cursor", async () => {
35
+ const call = endpoint();
36
+
37
+ await paged(call, rows, asIs).all("user_1", { limit: 1 });
38
+
39
+ expect(call.mock.calls).toEqual([
40
+ ["user_1", { limit: 1 }],
41
+ ["user_1", { limit: 1, page_token: "t1" }],
42
+ ]);
43
+ });
44
+
45
+ it("follows the cursor its shape reads, whatever the field is called", async () => {
46
+ const call = vi.fn(async (...args: unknown[]) =>
47
+ (args[0] as { page_token?: string } | undefined)?.page_token === undefined
48
+ ? { rows: ["a"], cursor: "t1" }
49
+ : { rows: ["b"] },
50
+ );
51
+ const shape = {
52
+ items: (page: { rows: string[] }) => page.rows,
53
+ next: (page: { cursor?: string }) => page.cursor,
54
+ withToken: ([params]: unknown[], page_token: string) => [
55
+ Object.assign({}, params, { page_token }),
56
+ ],
57
+ };
58
+
59
+ expect(await paged(call, shape, asIs).all()).toEqual(["a", "b"]);
60
+ });
61
+
62
+ it("collects every page's items in order", async () => {
63
+ expect(await paged(endpoint(), rows, asIs).all("user_1")).toEqual(["a", "b"]);
64
+ });
65
+
66
+ it("reads the cursor before its response hook sees the page", async () => {
67
+ const reshape = {
68
+ ...asIs,
69
+ respond: (body: unknown) => ({ rows: (body as { rows: string[] }).rows, renamed: true }),
70
+ };
71
+
72
+ expect(await paged(endpoint(), rows, reshape).all("user_1")).toEqual(["a", "b"]);
73
+ });
74
+
75
+ it("waits for a response hook that answers later", async () => {
76
+ const later = { ...asIs, respond: async (body: unknown) => body };
77
+
78
+ expect(await paged(endpoint(), rows, later).all("user_1")).toEqual(["a", "b"]);
79
+ });
80
+
81
+ it("starts at the page_token among its arguments", async () => {
82
+ const call = vi.fn(async () => ({ rows: ["c"], next_page_token: "" }));
83
+
84
+ expect(await paged(call, rows, asIs).all("user_1", { page_token: "c3" })).toEqual(["c"]);
85
+ expect(call.mock.calls).toEqual([["user_1", { page_token: "c3" }]]);
86
+ });
87
+
88
+ it("hands every failure of the walk to its error hook once", async () => {
89
+ const seen: unknown[] = [];
90
+ const call = vi.fn(async () => {
91
+ throw new Error("down");
92
+ });
93
+ const record = {
94
+ ...asIs,
95
+ fail: (error: unknown): never => {
96
+ seen.push(error);
97
+ throw new Error("handled");
98
+ },
99
+ };
100
+
101
+ await expect(paged(call, rows, record).all()).rejects.toThrow("handled");
102
+ expect(seen).toHaveLength(1);
103
+ });
104
+ });
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The client's own use of the cursor walk: `pages`, `items` and `all` on one
3
+ * generated function. Internal to the package; `./paging` is what it exports.
4
+ */
5
+ import { pages } from "./paging";
6
+
7
+ /**
8
+ * How a generated function pages: its page's items and cursor, read off a page
9
+ * as the generated table types them, and the arguments that fetch the next one.
10
+ * Method syntax, so a table entry typed by its page assigns here.
11
+ */
12
+ type PagingShape = Readonly<{
13
+ items(page: unknown): readonly unknown[];
14
+ next(page: unknown): string | null | undefined;
15
+ withToken(args: unknown[], token: string): readonly unknown[];
16
+ }>;
17
+
18
+ /** What the client does to every response and every failure. */
19
+ type Hooks = Readonly<{
20
+ respond: (body: unknown) => unknown;
21
+ fail: (error: unknown) => never;
22
+ }>;
23
+
24
+ /**
25
+ * `pages`, `items` and `all` for one generated function. Each takes the
26
+ * function's own arguments; the first page is fetched with them as given, so a
27
+ * `page_token` among them is where it starts. `send` fetches a page as the
28
+ * server answers it, so the cursor is read before `hooks.respond` sees the
29
+ * page, and every failure of the walk reaches `hooks.fail` once.
30
+ */
31
+ export function paged(send: (...args: unknown[]) => unknown, shape: PagingShape, hooks: Hooks) {
32
+ async function* walk<T>(args: unknown[], take: (page: unknown) => readonly T[]) {
33
+ const raw = pages(
34
+ async (token) => {
35
+ return token === undefined ? send(...args) : send(...shape.withToken(args, token));
36
+ },
37
+ { next: (page) => shape.next(page) ?? undefined },
38
+ );
39
+ try {
40
+ for await (const page of raw) {
41
+ for (const value of take(await hooks.respond(page))) {
42
+ yield value;
43
+ }
44
+ }
45
+ } catch (error) {
46
+ hooks.fail(error);
47
+ }
48
+ }
49
+
50
+ return {
51
+ pages: (...args: unknown[]) => walk(args, (page) => [page]),
52
+ items: (...args: unknown[]) => walk(args, (page) => shape.items(page)),
53
+ all: async (...args: unknown[]) => {
54
+ const collected: unknown[] = [];
55
+ for await (const list of walk(args, (page) => [shape.items(page)])) {
56
+ collected.push(...list);
57
+ }
58
+ return collected;
59
+ },
60
+ };
61
+ }
@@ -0,0 +1,94 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+
3
+ import { itemsOf, nextToken, pages } from "./paging";
4
+
5
+ /** Answers each cursor with the page `chain` holds for it; `""` is the first page. */
6
+ function fetchPage(chain: Record<string, { rows: string[]; next?: string }>) {
7
+ return vi.fn(async (token: string | undefined) => {
8
+ const page = chain[token ?? ""] ?? { rows: [] };
9
+ return { rows: page.rows, next_page_token: page.next };
10
+ });
11
+ }
12
+
13
+ describe("nextToken", () => {
14
+ it.each([
15
+ ["a cursor", { next_page_token: "t1" }, "t1"],
16
+ ["an empty cursor", { next_page_token: "" }, undefined],
17
+ ["a null cursor", { next_page_token: null }, undefined],
18
+ ["no cursor", {}, undefined],
19
+ ])("reads %s", (_, page, expected) => {
20
+ expect(nextToken(page)).toBe(expected);
21
+ });
22
+
23
+ it("reads the field it is told to", () => {
24
+ expect(nextToken({ next_cursor: "c2", next_page_token: "t2" }, "next_cursor")).toBe("c2");
25
+ });
26
+ });
27
+
28
+ describe("itemsOf", () => {
29
+ it("reads the list the field names", () => {
30
+ expect(itemsOf({ users: ["a", "b"], next_page_token: "t1" }, "users")).toEqual(["a", "b"]);
31
+ });
32
+
33
+ it.each([
34
+ ["a page without the field", { next_page_token: "" }],
35
+ ["a field that is not a list", { users: "a" }],
36
+ ["no page at all", null],
37
+ ])("refuses %s, naming the field", (_, page) => {
38
+ expect(() => itemsOf(page, "users")).toThrow(
39
+ new TypeError('Unexpected list response: missing "users" array'),
40
+ );
41
+ });
42
+ });
43
+
44
+ describe("pages", () => {
45
+ it("follows the cursor until the server gives none", async () => {
46
+ const fetch = fetchPage({ "": { rows: ["a"], next: "t1" }, t1: { rows: ["b"] } });
47
+
48
+ const rows = [];
49
+ for await (const page of pages(fetch)) rows.push(...page.rows);
50
+
51
+ expect(rows).toEqual(["a", "b"]);
52
+ expect(fetch.mock.calls).toEqual([[undefined], ["t1"]]);
53
+ });
54
+
55
+ it("fetches the next page only when the loop reaches it", async () => {
56
+ const fetch = fetchPage({ "": { rows: ["a"], next: "t1" }, t1: { rows: ["b"] } });
57
+
58
+ for await (const _ of pages(fetch)) break;
59
+
60
+ expect(fetch).toHaveBeenCalledTimes(1);
61
+ });
62
+
63
+ it("follows the cursor the reader it is given names", async () => {
64
+ const fetch = vi.fn(async (token: string | undefined) =>
65
+ token === undefined ? { next_cursor: "c2" } : {},
66
+ );
67
+
68
+ for await (const _ of pages(fetch, { next: (page) => nextToken(page, "next_cursor") }));
69
+
70
+ expect(fetch.mock.calls).toEqual([[undefined], ["c2"]]);
71
+ });
72
+
73
+ it("ends at an empty cursor the reader it is given returns", async () => {
74
+ const fetch = vi.fn(async (token: string | undefined) =>
75
+ token === undefined ? { next_cursor: "c2" } : { next_cursor: "" },
76
+ );
77
+
78
+ for await (const _ of pages(fetch, { next: (page) => page.next_cursor }));
79
+
80
+ expect(fetch.mock.calls).toEqual([[undefined], ["c2"]]);
81
+ });
82
+
83
+ it("follows the cursor a page arrived with, whatever the loop does to it", async () => {
84
+ const fetch = fetchPage({ "": { rows: ["a"], next: "t1" }, t1: { rows: ["b"] } });
85
+
86
+ const rows = [];
87
+ for await (const page of pages(fetch)) {
88
+ rows.push(...page.rows);
89
+ delete (page as { next_page_token?: string }).next_page_token;
90
+ }
91
+
92
+ expect(rows).toEqual(["a", "b"]);
93
+ });
94
+ });
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Cursor paging (ADR 027): a page carries `next_page_token` while more remain,
3
+ * and the next request sends it back as `page_token`.
4
+ *
5
+ * The walk trusts that contract. A server that repeats a cursor, skips one or
6
+ * answers a page in a different shape is an upstream bug to fix in the server,
7
+ * not something the client detects or works around; do not add guards for it.
8
+ * Typed callers read a page's list straight off it; only {@link itemsOf}, for
9
+ * a caller that knows the list by name alone, checks it is there.
10
+ */
11
+
12
+ /** Fetches the page a cursor names; `undefined` asks for the first page. */
13
+ export type FetchPage<P> = (token: string | undefined) => Promise<P>;
14
+
15
+ /**
16
+ * The cursor to the page after `page`, or `undefined` on the last one. `field`
17
+ * names it, for an API that calls it other than `next_page_token`.
18
+ */
19
+ export function nextToken(page: unknown, field = "next_page_token"): string | undefined {
20
+ const token = (page as Record<string, unknown> | null)?.[field];
21
+ return typeof token === "string" && token !== "" ? token : undefined;
22
+ }
23
+
24
+ /**
25
+ * The array `field` names on a page, for a caller that learns the field only
26
+ * at runtime (an operation picked from a table); a page without one is not a
27
+ * page of that list.
28
+ */
29
+ export function itemsOf(page: unknown, field: string): readonly unknown[] {
30
+ const list = (page as Record<string, unknown> | null)?.[field];
31
+ if (!Array.isArray(list)) {
32
+ throw new TypeError(`Unexpected list response: missing "${field}" array`);
33
+ }
34
+ return list;
35
+ }
36
+
37
+ /**
38
+ * Every page, fetched only when the loop asks for the next one, so a caller
39
+ * that stops early never reads the rest. The first page is the one
40
+ * `fetchPage(undefined)` answers; `next` reads a page's cursor, and an empty
41
+ * one ends the walk like none.
42
+ */
43
+ export async function* pages<P>(
44
+ fetchPage: FetchPage<P>,
45
+ { next = nextToken }: { next?: (page: P) => string | undefined } = {},
46
+ ): AsyncGenerator<P, void, undefined> {
47
+ let token: string | undefined;
48
+ for (;;) {
49
+ const page = await fetchPage(token);
50
+ // Read before the page is handed out, so a loop that changes the page
51
+ // cannot change where the walk goes.
52
+ token = next(page) || undefined;
53
+ yield page;
54
+ if (token === undefined) {
55
+ return;
56
+ }
57
+ }
58
+ }
@@ -1 +0,0 @@
1
- {"version":3,"file":"fetch-CtYe0OvX.d.mts","names":[],"sources":["../src/runtime/fetch.ts"],"mappings":";;cAGa;;;;;;;;;;;;cAmBA,iBAAiB;WACnB;WACA;WACA;;;;;;WAMA;EAEG,YAAA,gBAAgB,aAAa,eAAe,iBAAiB;;;;;;;;;;;;cAoB9D,qBAAqB;WACvB;;WAEA;EAGP,YAAA,aACA,mCACA,iBACA,UAAU;;;;;;;KAcF;;EAEV,SAAS;;EAET;;iBAKc,iBAAiB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;iBA0BnB,YAAY,GAAG,aAAa,SAAS,cAAc,QAAQ;;;;;;;;;;;;;;;;iBAyF3D,QAAQ,eAC5B,aACA,MAAM,aACN,SAAQ,eACR,QAAQ,KAAK,aAAa,QAAQ,KACjC;EAAU,KAAK;EAAU,SAAS;;;;;;;iBAiErB,aAAa;;;;;;;;iBAYb,gBAAgB,OAAO"}