calmlens 0.25.0 → 0.27.1

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 (95) hide show
  1. package/README.md +15 -15
  2. package/bin/calmlens.js +2383 -677
  3. package/cjs/{BrowserUpload-AO2-2U5Z.js → BrowserUpload-CTqIjCV5.js} +1 -1
  4. package/{esm/BrowserUpload-D2lemMIU.d.ts → cjs/BrowserUpload-D4sEmd0X.d.ts} +2 -2
  5. package/{esm/CalmLensAppClient-Dt0t9Bk6.d.ts → cjs/CalmLensAppClient-CCeFnKX8.d.ts} +5 -11
  6. package/cjs/{CalmLensAppClient-nv6qwja0.js → CalmLensAppClient-CZm-9g22.js} +23 -16
  7. package/cjs/{CalmLensOptionKeys-BvCac9NO.js → CalmLensOptionKeys-C1w3SqmL.js} +165 -95
  8. package/cjs/CalmLensServerClient-B7PfocET.d.ts +346 -0
  9. package/cjs/{CalmLensServerClient-B60kCBCR.js → CalmLensServerClient-ucq3ITjd.js} +281 -315
  10. package/cjs/{CalmLensTypes-BhR7LFDu.d.ts → CalmLensTypes-HUERg5hI.d.ts} +142 -155
  11. package/cjs/{Classification-CxRedzgH-C9qlYW_J.d.ts → Classification-CMM2tZpJ-IdIh63n0.d.ts} +6 -7
  12. package/cjs/{Core-Cw4IxFUq.js → Core-D-1KCqT7.js} +39 -16
  13. package/cjs/{Core-DSMxC2GL.d.ts → Core-DXAs8mcx.d.ts} +10 -3
  14. package/{esm/ModerationContextLimits-Bqr0duav.js → cjs/ModerationContextLimits-BcYKgU2X.js} +859 -44
  15. package/cjs/ReactUpload-BTciTpwB.d.ts +27 -0
  16. package/cjs/{ReactUpload--oDFltw2.js → ReactUpload-BymgWiC8.js} +38 -2
  17. package/cjs/{TestTriggers-CiFcTHX3-BmfH4J3f.js → TestTriggers-Cvi7e2KA-DcT1pc_W.js} +91 -22
  18. package/{esm/TestTriggers-BJ4B-MXR-D1tGifPU.d.ts → cjs/TestTriggers-Dnukm-jm-DoEB7jJc.d.ts} +1 -1
  19. package/cjs/{UploadController-ObdgTaBl.js → UploadController-C8GPbDKI.js} +16 -3
  20. package/{esm/WebhookPayload-DLGGOGW6.d.ts → cjs/WebhookPayload-mUmOFH55.d.ts} +152 -9
  21. package/cjs/app.d.ts +6 -6
  22. package/cjs/app.js +20 -2
  23. package/cjs/elements.d.ts +5 -5
  24. package/cjs/elements.js +105 -68
  25. package/cjs/{index-AAWuerkU.d.ts → index-Ck7x1YjM.d.ts} +3 -3
  26. package/cjs/index.d.ts +5 -5
  27. package/cjs/index.js +19 -1
  28. package/cjs/react-native.d.ts +3 -3
  29. package/cjs/react-native.js +7 -5
  30. package/cjs/react.d.ts +5 -4
  31. package/cjs/react.js +11 -15
  32. package/cjs/server.d.ts +6 -6
  33. package/cjs/server.js +20 -2
  34. package/cjs/test-inputs.d.ts +1 -1
  35. package/cjs/test-inputs.js +13 -13
  36. package/cjs/testing.d.ts +18 -21
  37. package/cjs/testing.js +99 -147
  38. package/cjs/{ui-CcuGKTcL.d.ts → ui-BfJNO3c6.d.ts} +2 -2
  39. package/cjs/{ui-CA16jyfZ.js → ui-CW8BqtZk.js} +7 -5
  40. package/cjs/ui.d.ts +3 -3
  41. package/cjs/ui.js +4 -3
  42. package/cjs/vue.d.ts +15 -8
  43. package/cjs/vue.js +30 -17
  44. package/esm/{BrowserUpload-Co4T6uGk.js → BrowserUpload-C01iLeOs.js} +1 -1
  45. package/{cjs/BrowserUpload-D2lemMIU.d.ts → esm/BrowserUpload-D4sEmd0X.d.ts} +2 -2
  46. package/{cjs/CalmLensAppClient-Dt0t9Bk6.d.ts → esm/CalmLensAppClient-CCeFnKX8.d.ts} +5 -11
  47. package/esm/{CalmLensAppClient-BRzy4dwn.js → CalmLensAppClient-CgDogQQC.js} +23 -16
  48. package/esm/{CalmLensOptionKeys-bE3rb5PN.js → CalmLensOptionKeys-CEwNbpEz.js} +160 -96
  49. package/esm/CalmLensServerClient-B7PfocET.d.ts +346 -0
  50. package/esm/{CalmLensServerClient-_PRi90wI.js → CalmLensServerClient-TT6zrAG5.js} +281 -315
  51. package/esm/{CalmLensTypes-BhR7LFDu.d.ts → CalmLensTypes-HUERg5hI.d.ts} +142 -155
  52. package/esm/{Classification-CxRedzgH-C9qlYW_J.d.ts → Classification-CMM2tZpJ-IdIh63n0.d.ts} +6 -7
  53. package/esm/{Core-CtbYmeXG.js → Core-CP6NaqJz.js} +39 -16
  54. package/esm/{Core-DSMxC2GL.d.ts → Core-DXAs8mcx.d.ts} +10 -3
  55. package/{cjs/ModerationContextLimits-Cn9RvnZH.js → esm/ModerationContextLimits-BmV8QD32.js} +476 -301
  56. package/esm/{ReactUpload-B5itHBSF.js → ReactUpload-B72Oq3qE.js} +34 -4
  57. package/esm/ReactUpload-BTciTpwB.d.ts +27 -0
  58. package/esm/{TestTriggers-CiFcTHX3-BK2-sgOC.js → TestTriggers-Cvi7e2KA-BA83CRJb.js} +87 -23
  59. package/{cjs/TestTriggers-BJ4B-MXR-D1tGifPU.d.ts → esm/TestTriggers-Dnukm-jm-DoEB7jJc.d.ts} +1 -1
  60. package/esm/{UploadController-C7fL3Iz9.js → UploadController-Q7xTqh5w.js} +11 -4
  61. package/{cjs/WebhookPayload-DLGGOGW6.d.ts → esm/WebhookPayload-mUmOFH55.d.ts} +152 -9
  62. package/esm/app.d.ts +6 -6
  63. package/esm/app.js +3 -3
  64. package/esm/elements.d.ts +5 -5
  65. package/esm/elements.js +105 -69
  66. package/esm/{index-AAWuerkU.d.ts → index-Ck7x1YjM.d.ts} +3 -3
  67. package/esm/index.d.ts +5 -5
  68. package/esm/index.js +1 -1
  69. package/esm/react-native.d.ts +3 -3
  70. package/esm/react-native.js +6 -6
  71. package/esm/react.d.ts +5 -4
  72. package/esm/react.js +10 -16
  73. package/esm/server.d.ts +6 -6
  74. package/esm/server.js +3 -3
  75. package/esm/styles.css +37 -14
  76. package/esm/svelte/CalmLensAsset.svelte +1 -1
  77. package/esm/svelte/CalmLensUploader.svelte +17 -17
  78. package/esm/svelte/context.js +21 -0
  79. package/esm/svelte/index.d.ts +12 -0
  80. package/esm/svelte/index.js +1 -0
  81. package/esm/test-inputs.d.ts +1 -1
  82. package/esm/test-inputs.js +1 -1
  83. package/esm/testing.d.ts +18 -21
  84. package/esm/testing.js +93 -141
  85. package/esm/{ui-B98AucZA.js → ui-BBDJJkFL.js} +7 -5
  86. package/esm/{ui-CcuGKTcL.d.ts → ui-BfJNO3c6.d.ts} +2 -2
  87. package/esm/ui.d.ts +3 -3
  88. package/esm/ui.js +4 -4
  89. package/esm/vue.d.ts +15 -8
  90. package/esm/vue.js +30 -19
  91. package/package.json +16 -6
  92. package/cjs/CalmLensServerClient-7XjQaeKu.d.ts +0 -353
  93. package/cjs/ReactUpload-CW4NzAsh.d.ts +0 -17
  94. package/esm/CalmLensServerClient-7XjQaeKu.d.ts +0 -353
  95. package/esm/ReactUpload-CW4NzAsh.d.ts +0 -17
@@ -1,5 +1,5 @@
1
- import { B as invalidArgument, C as validateBatchAssetsOptions, F as isBrowserRuntime, I as isReactNativeRuntime, R as CalmLensError, T as validateServerClientOptions, V as invalidConfig, a as appendAssetLocation, b as toTextAssetOptions, d as checkOptionKeys, g as pollForDecision, l as validateSignAssetUrlOptions, o as buildAssetUrl, p as encodePathSegment, s as getAssetInfo, u as DEFAULT_CDN_BASE_URL, w as validateRequestOptions, z as SDK_ERROR_CODES } from "./ModerationContextLimits-Bqr0duav.js";
2
- import { c as getMockHooks, d as prepareSubmitAssetOptions, f as resolveConnectionOptions, i as CalmLensConnection, l as invalidPayload, n as NULLABLE_OPTION_KEYS, o as expectAsset, p as splitsIntoParts, r as SERVER_OPTION_KEYS, u as newIdempotencyKey } from "./CalmLensOptionKeys-bE3rb5PN.js";
1
+ import { C as validateBatchAssetsOptions, F as isReactNativeRuntime, L as copyLastResponse, P as isBrowserRuntime, R as listPages, Y as CalmLensError, a as appendAssetLocation, b as toTextAssetOptions, ct as invalidConfig, d as checkOptionKeys, g as pollForDecision, l as validateSignAssetUrlOptions, o as buildAssetUrl, ot as SDK_ERROR_CODES, p as encodePathSegment, s as getAssetInfo, st as invalidArgument, u as DEFAULT_CDN_BASE_URL, w as validateServerClientOptions, y as stringifyQuery, z as readEnv } from "./ModerationContextLimits-BmV8QD32.js";
2
+ import { c as getMockHooks, d as prepareSubmitAssetOptions, f as resolveConnectionOptions, i as CalmLensConnection, l as invalidPayload, m as validateCallOptions, n as NULLABLE_OPTION_KEYS, o as expectAsset, p as splitsIntoParts, r as SERVER_OPTION_KEYS, u as newIdempotencyKey } from "./CalmLensOptionKeys-CEwNbpEz.js";
3
3
  import { n as sha256Hex, r as timingSafeEqual, t as hmacSha256Hex } from "./CryptoUtils-B_x8lMIx-DhuWGzqn.js";
4
4
  // src/contract/JsonUtils.js
5
5
  const stringifyJsonCanonical = (value) => JSON.stringify(value, (_key, nestedValue) => {
@@ -184,6 +184,28 @@ const isTestWebhookEvent = (event) => Array.isArray(event?.facts) && event.facts
184
184
  * new. Store the event's `assetSequence` per `assetId` once you have applied it.
185
185
  */
186
186
  const isNewerAssetEvent = (event, lastSequence) => event.assetSequence === null || event.assetSequence === void 0 || lastSequence === null || lastSequence === void 0 || event.assetSequence > lastSequence;
187
+ // src/client/ServedAssetInfo.ts
188
+ function parseServedAssetInfo(header) {
189
+ if (!header) return void 0;
190
+ const dimensions = {};
191
+ let start = 0;
192
+ for (const delimiter of `${header},`.matchAll(/"(?:[^"\\]|\\.)*"|[",]/g)) {
193
+ if (delimiter[0] === "\"") return void 0;
194
+ if (delimiter[0] !== ",") continue;
195
+ const member = header.slice(start, delimiter.index).trim();
196
+ start = delimiter.index + 1;
197
+ const [key] = member.split(/[=; \t]/, 1);
198
+ if (key !== "width" && key !== "height") continue;
199
+ const match = /^(?:width|height)=([0-9]{1,15})$/.exec(member);
200
+ if (!match || dimensions[key] !== void 0 || Number(match[1]) === 0) return void 0;
201
+ dimensions[key] = Number(match[1]);
202
+ }
203
+ const { width, height } = dimensions;
204
+ return width === void 0 || height === void 0 ? void 0 : {
205
+ width,
206
+ height
207
+ };
208
+ }
187
209
  const getEnsureLensCacheKey = (options) => stringifyJsonCanonical({
188
210
  identifier: options.identifier,
189
211
  name: options.name,
@@ -193,6 +215,35 @@ const getEnsureLensCacheKey = (options) => stringifyJsonCanonical({
193
215
  transform: options.transform ?? null
194
216
  });
195
217
  const requireId = (value, name) => encodePathSegment(value, name);
218
+ /** `options`, after checking that text it classifies isn't empty. */
219
+ const checkedTextContent = (options) => {
220
+ if (options && "content" in options && "plainText" in options.content && (typeof options.content.plainText !== "string" || !options.content.plainText.trim())) throw invalidPayload("Text to classify must be a non-empty string");
221
+ return options;
222
+ };
223
+ /** A signal that aborts when any of `signals` does. */
224
+ const anySignal = (signals) => {
225
+ if (typeof AbortSignal.any === "function") return AbortSignal.any(signals);
226
+ const controller = new AbortController();
227
+ for (const signal of signals) if (signal.aborted) controller.abort(signal.reason);
228
+ else signal.addEventListener("abort", () => controller.abort(signal.reason), { once: true });
229
+ return controller.signal;
230
+ };
231
+ /**
232
+ * Fills in what the options leave out from the environment: `CALMLENS_API_KEY`,
233
+ * `CALMLENS_PROJECT_ID` and `CALMLENS_BASE_URL`, in runtimes that have one.
234
+ */
235
+ const withEnvironmentDefaults = (options) => {
236
+ if (!options || typeof options !== "object" || getMockHooks(options)) return options;
237
+ const apiKey = options.apiKey ?? readEnv("CALMLENS_API_KEY");
238
+ const projectId = options.projectId ?? readEnv("CALMLENS_PROJECT_ID");
239
+ const baseUrl = options.baseUrl ?? readEnv("CALMLENS_BASE_URL");
240
+ return {
241
+ ...options,
242
+ ...apiKey !== void 0 && { apiKey },
243
+ ...projectId !== void 0 && { projectId },
244
+ ...baseUrl !== void 0 && { baseUrl }
245
+ };
246
+ };
196
247
  /**
197
248
  * `options`, once `checkOptionKeys` finds only keys `operation` takes, without the options given as
198
249
  * `null` that the API refuses as `null`: those are left out, as if omitted.
@@ -203,26 +254,17 @@ const checked = (operation, options) => {
203
254
  const nullable = NULLABLE_OPTION_KEYS[operation] ?? [];
204
255
  return Object.fromEntries(Object.entries(options).filter(([key, value]) => value !== null || nullable.includes(key)));
205
256
  };
206
- /**
207
- * Iterators stop rather than loop: a page that says more follow must not hand back a cursor this
208
- * iteration has already sent, which would repeat the same pages forever.
209
- */
210
- const assertNewCursor = (sent, cursor) => {
211
- if (sent.has(cursor)) throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
212
- message: "The API returned a cursor it had already returned, with more pages to follow",
213
- details: { cursor }
214
- });
215
- sent.add(cursor);
216
- };
217
257
  const inspectSymbol = Symbol.for("nodejs.util.inspect.custom");
218
258
  const writableCdnResponse = (response, metadata = response) => {
219
- if (response.status < 200) return response;
220
- const writable = new Response(response.body, response);
259
+ const writable = response.status < 200 ? response : new Response(response.body, response);
221
260
  const { url, redirected, type } = metadata;
222
261
  return Object.defineProperties(writable, {
223
262
  url: { value: url },
224
263
  redirected: { value: redirected },
225
264
  type: { value: type },
265
+ getAssetInfo: { value() {
266
+ return parseServedAssetInfo(this.headers.get("X-CalmLens-Asset-Info"));
267
+ } },
226
268
  clone: { value() {
227
269
  return writableCdnResponse(Response.prototype.clone.call(this), {
228
270
  url,
@@ -234,13 +276,13 @@ const writableCdnResponse = (response, metadata = response) => {
234
276
  };
235
277
  /**
236
278
  * The CalmLens API client for your server, authenticated with a project API key. Create one per
237
- * project and reuse it; it holds no connections. Every method takes one options object and
238
- * throws `CalmLensError` on failure. Browsers and apps upload with `CalmLensAppClient` instead.
279
+ * project and reuse it; it holds no connections. Every method takes one options object, then
280
+ * optional `RequestOptions` for that call, and throws `CalmLensError` on failure. Options left
281
+ * out of the constructor come from `CALMLENS_API_KEY`, `CALMLENS_PROJECT_ID`, `CALMLENS_BASE_URL`
282
+ * and `CALMLENS_LOG`. Browsers and apps upload with `CalmLensAppClient` instead.
239
283
  */
240
- var CalmLensServerClient = class CalmLensServerClient {
284
+ var CalmLensServerClient = class {
241
285
  #apiKey;
242
- /** The options this client was created with, without the API key, for `withRequestOptions`. */
243
- #options;
244
286
  #settings;
245
287
  #lenses;
246
288
  #connection;
@@ -263,13 +305,14 @@ var CalmLensServerClient = class CalmLensServerClient {
263
305
  static async verifyWebhookSignature(options) {
264
306
  return verifyWebhookSignature(options);
265
307
  }
266
- constructor(options, lenses) {
308
+ constructor(clientOptions = {}, lenses) {
309
+ const options = withEnvironmentDefaults(clientOptions);
267
310
  validateServerClientOptions(options);
268
311
  if ((isBrowserRuntime() || isReactNativeRuntime()) && !options.dangerouslyAllowBrowser) throw invalidConfig("CalmLensServerClient is running in a browser or app, where anyone could read the API key. Call CalmLens from your server, upload from the browser or app with CalmLensAppClient, or set dangerouslyAllowBrowser: true for trusted internal tools.");
269
- const { apiKey, ...rest } = options;
312
+ const { apiKey, projectId, ...rest } = options;
270
313
  this.#apiKey = apiKey;
271
- this.#options = rest;
272
314
  this.#settings = {
315
+ projectId,
273
316
  ...resolveConnectionOptions(rest),
274
317
  cdnBaseUrl: (rest.cdnBaseUrl ?? getMockHooks(rest)?.defaultCdnBaseUrl ?? DEFAULT_CDN_BASE_URL).replace(/\/+$/, "")
275
318
  };
@@ -277,19 +320,7 @@ var CalmLensServerClient = class CalmLensServerClient {
277
320
  ensuredLenses: /* @__PURE__ */ new Map(),
278
321
  pendingEnsureLenses: /* @__PURE__ */ new Map()
279
322
  };
280
- this.#connection = new CalmLensConnection(this.#settings, apiKey);
281
- }
282
- /**
283
- * A client with different cancellation, deadlines or retries for the calls made through it,
284
- * sharing this client's credentials and lens cache. This client is unchanged.
285
- */
286
- withRequestOptions(options) {
287
- validateRequestOptions(options);
288
- return new CalmLensServerClient({
289
- ...this.#options,
290
- ...options,
291
- apiKey: this.#apiKey
292
- }, this.#lenses);
323
+ this.#connection = new CalmLensConnection(this.#settings, apiKey, { readEnvironment: !getMockHooks(options) });
293
324
  }
294
325
  /** Keeps the API key out of `console.log`, `util.inspect` and `JSON.stringify`. */
295
326
  [inspectSymbol]() {
@@ -304,28 +335,80 @@ var CalmLensServerClient = class CalmLensServerClient {
304
335
  cdnBaseUrl
305
336
  };
306
337
  }
307
- get projectPath() {
338
+ get #projectPath() {
308
339
  return `/projects/${encodeURIComponent(this.#settings.projectId)}`;
309
340
  }
310
- request(method, path, options = {}) {
311
- return this.#connection.json(method, path, options);
341
+ /** Sends one of `operation`'s requests with its request options. */
342
+ async #send(operation, requestOptions, method, path, options = {}) {
343
+ return this.#connection.forCall(operation, requestOptions).json(method, path, options);
344
+ }
345
+ /**
346
+ * Sends any API request with the client's API key, retries, deadlines and error handling, for
347
+ * endpoints or fields this SDK version doesn't cover yet. `path` is relative to the base URL,
348
+ * such as `/assets/asset_123`; `query` and `body` are sent as they are, without the option
349
+ * check the other methods make. GET, HEAD and requests with an `idempotencyKey` are retried.
350
+ * Resolves with the parsed JSON body and its `lastResponse` (`undefined` for an empty body).
351
+ */
352
+ async request(method, path, { query, body, headers } = {}, requestOptions) {
353
+ const methods = [
354
+ "GET",
355
+ "HEAD",
356
+ "POST",
357
+ "PUT",
358
+ "PATCH",
359
+ "DELETE"
360
+ ];
361
+ if (typeof method !== "string" || !methods.includes(method)) throw invalidArgument(`method must be one of ${methods.join(", ")}`);
362
+ if (typeof path !== "string" || !path.startsWith("/") || path.startsWith("//")) throw invalidArgument("path must start with \"/\", such as \"/assets/asset_123\"");
363
+ const { headers: callHeaders, ...rest } = requestOptions ?? {};
364
+ return this.#send(void 0, {
365
+ ...rest,
366
+ ...(callHeaders || headers) && { headers: {
367
+ ...callHeaders,
368
+ ...headers
369
+ } }
370
+ }, method, path, {
371
+ query,
372
+ body
373
+ });
312
374
  }
313
- async submitAsset(options, wait) {
375
+ /**
376
+ * A list call: each page sends `options`, checked as `operation` takes them, with the cursor of
377
+ * the page it fetches.
378
+ */
379
+ #paginate(operation, options, requestOptions, send) {
380
+ const first = options?.cursor;
381
+ return listPages(async (cursor) => {
382
+ const valid = checked(operation, options);
383
+ return send(cursor === first ? valid : {
384
+ ...valid,
385
+ cursor
386
+ });
387
+ }, {
388
+ cursor: typeof first === "string" ? first : void 0,
389
+ feed: operation === "events.list"
390
+ });
391
+ }
392
+ async #submitAsset(operation, options, wait, requestOptions) {
393
+ const connection = this.#connection.forCall(operation, requestOptions);
314
394
  const body = prepareSubmitAssetOptions(options, {
315
- deferUploadChecks: this.#connection.deferUploadChecks,
316
- partSizeBytes: this.#connection.partSizeBytes
395
+ deferUploadChecks: connection.deferUploadChecks,
396
+ partSizeBytes: connection.partSizeBytes
317
397
  });
318
- const uploadsPath = `${this.projectPath}/assets`;
319
- if ("content" in body && splitsIntoParts(body.content, this.#connection.partSizeBytes)) return expectAsset(await this.#connection.submitInParts(uploadsPath, body, wait, {
320
- partPath: (assetId) => `/assets/${encodeURIComponent(assetId)}/part`,
321
- retrieve: (assetId) => this.buildAssets().retrieve({ assetId })
322
- }));
323
- if ("content" in body || "part" in body) return expectAsset(await this.#connection.submitUpload(uploadsPath, body, wait));
398
+ const uploadsPath = `${this.#projectPath}/assets`;
399
+ if ("content" in body && splitsIntoParts(body.content, connection.partSizeBytes)) {
400
+ const { idempotencyKey: _key, extraBody: _body, ...readOptions } = requestOptions ?? {};
401
+ return expectAsset(await connection.submitInParts(uploadsPath, body, wait, {
402
+ partPath: (assetId) => `/assets/${encodeURIComponent(assetId)}/part`,
403
+ retrieve: (assetId) => this.#buildAssets().retrieve({ assetId }, readOptions)
404
+ }));
405
+ }
406
+ if ("content" in body || "part" in body) return expectAsset(await connection.submitUpload(uploadsPath, body, wait));
324
407
  const { idempotencyKey, ...fields } = body;
325
- const data = await this.#connection.json("POST", uploadsPath, {
408
+ const data = await connection.json("POST", uploadsPath, {
326
409
  query: { wait },
327
410
  body: fields,
328
- idempotencyKey: idempotencyKey ?? newIdempotencyKey()
411
+ idempotencyKey: idempotencyKey ?? requestOptions?.idempotencyKey ?? newIdempotencyKey()
329
412
  });
330
413
  return expectAsset(data);
331
414
  }
@@ -348,21 +431,21 @@ var CalmLensServerClient = class CalmLensServerClient {
348
431
  * URL beneath the grant; lenses, transforms and viewer claims are appended as `getAssetUrl`
349
432
  * appends them and aren't part of the signature.
350
433
  */
351
- signAssetUrl: async (signOptions) => {
434
+ signAssetUrl: async (signOptions, requestOptions) => {
352
435
  const options = checked("cdn.signAssetUrl", signOptions);
353
436
  validateSignAssetUrlOptions(options);
354
437
  const { projectId, assetId, externalId, expiresIn, original, ...location } = options;
355
438
  const project = requireId(projectId ?? this.#settings.projectId, "Project ID");
356
- const signed = await this.request("POST", `/projects/${project}/signed-asset-urls`, { body: {
439
+ const signed = await this.#send("cdn.signAssetUrl", requestOptions, "POST", `/projects/${project}/signed-asset-urls`, { body: {
357
440
  ...assetId !== void 0 ? { assetId } : { externalId },
358
441
  expiresIn: expiresIn ?? 900,
359
442
  original: original ?? false
360
443
  } });
361
444
  if (!signed || typeof signed.url !== "string" || !signed.url || typeof signed.expiresAt !== "number") throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, { message: "The API returned no signed asset URL" });
362
- return {
445
+ return copyLastResponse({
363
446
  url: appendAssetLocation(signed.url, location),
364
447
  expiresAt: signed.expiresAt
365
- };
448
+ }, signed);
366
449
  },
367
450
  /**
368
451
  * The display info of an asset URL, public or signed (`{url}/info`): its type, size,
@@ -379,18 +462,23 @@ var CalmLensServerClient = class CalmLensServerClient {
379
462
  * a `Response` with writable headers as soon as headers arrive, so the body streams.
380
463
  * Non-2xx responses are returned, not thrown; `timeoutMs` covers only the wait for headers.
381
464
  */
382
- serve: async (options) => {
465
+ serve: async (options, requestOptions) => {
383
466
  const { init, resource = "rendered", ...urlOptions } = checked("cdn.serve", options);
467
+ const connection = this.#connection.forCall("cdn.serve", requestOptions);
468
+ if (requestOptions?.extraBody) throw invalidArgument("cdn.serve sends no body: extraBody can't apply");
384
469
  const url = this.cdn.getAssetUrl({
385
470
  ...urlOptions,
386
471
  resource
387
472
  });
473
+ const extraQuery = requestOptions?.extraQuery && stringifyQuery(requestOptions.extraQuery);
388
474
  const method = init?.method?.toUpperCase() ?? "GET";
389
- const { response } = await this.#connection.transport.send({
475
+ const { response } = await connection.transport.send({
476
+ ...connection.callRequest(),
390
477
  method,
391
- url,
478
+ url: extraQuery ? `${url}${url.includes("?") ? "&" : "?"}${extraQuery}` : url,
479
+ headers: requestOptions?.headers,
392
480
  init,
393
- timeoutMs: this.#connection.timeoutMs,
481
+ timeoutMs: connection.timeoutMs,
394
482
  deadline: "headers",
395
483
  fetch: this.#settings.cdnFetch
396
484
  }, { allowHttpErrors: true });
@@ -404,11 +492,11 @@ var CalmLensServerClient = class CalmLensServerClient {
404
492
  * Moderates text and waits for the decision. Sends `text` as `text/plain` content named
405
493
  * `text` unless you pass `name`.
406
494
  */
407
- classify: async (options) => this.buildAssets().classify(toTextAssetOptions(checked("text.classify", options))) };
495
+ classify: async (options, requestOptions) => this.#submitAsset("text.classify", checkedTextContent(toTextAssetOptions(checked("text.classify", options))), true, requestOptions) };
408
496
  }
409
497
  /** Assets: uploads, moderation and management. */
410
498
  get assets() {
411
- return this.buildAssets();
499
+ return this.#buildAssets();
412
500
  }
413
501
  /**
414
502
  * Signs upload tokens on your server, so a browser or app can upload through an upload preset
@@ -424,102 +512,73 @@ sign: async (options) => {
424
512
  return signUploadTokenWithApiKey(this.#apiKey, checked("uploadTokens.sign", options), this.#connection.hooks?.uploadTokenTime());
425
513
  } };
426
514
  }
427
- buildAssets() {
515
+ #buildAssets() {
428
516
  return {
429
517
  /** Searches accessible assets by keyword or a natural-language description. */
430
- search: async (options) => this.request("GET", `${this.projectPath}/assets/search`, { query: checked("assets.search", options) }),
431
- /** Lists one page of the project's assets, with an optional filter and sort. */
432
- list: async (options = {}) => this.request("GET", `${this.projectPath}/assets`, { query: checked("assets.list", options) }),
518
+ search: async (options, requestOptions) => this.#send("assets.search", requestOptions, "GET", `${this.#projectPath}/assets/search`, { query: checked("assets.search", options) }),
433
519
  /**
434
- * Yields every asset matching `options`, fetching pages as needed. The cursor keeps the position
435
- * stable when other assets are inserted or deleted.
520
+ * Lists the project's assets, with an optional filter and sort. Await it for one page, or
521
+ * `for await` over it for every matching asset, fetching pages as needed.
436
522
  */
437
- iterate: (options = {}) => {
438
- checked("assets.iterate", options);
439
- return this.iteratePages((cursor) => this.buildAssets().list({
440
- ...options,
441
- cursor
442
- }));
443
- },
523
+ list: (options = {}, requestOptions) => this.#paginate("assets.list", options, requestOptions, (query) => this.#send("assets.list", requestOptions, "GET", `${this.#projectPath}/assets`, { query })),
444
524
  /** Retrieves an asset with its status and classification results. */
445
- retrieve: async (options) => {
525
+ retrieve: async (options, requestOptions) => {
446
526
  const { assetId } = checked("assets.retrieve", options);
447
- return this.request("GET", `/assets/${requireId(assetId, "Asset ID")}`);
527
+ return this.#send("assets.retrieve", requestOptions, "GET", `/assets/${requireId(assetId, "Asset ID")}`);
448
528
  },
449
529
  /** Updates an asset's editable fields. */
450
- update: async (options) => {
530
+ update: async (options, requestOptions) => {
451
531
  const { assetId, ...body } = checked("assets.update", options);
452
- return this.request("PATCH", `/assets/${requireId(assetId, "Asset ID")}`, { body });
453
- },
454
- /** Lists one page of the assets extracted from a website or multimedia document. */
455
- listChildren: async (options = {}) => {
456
- const { assetId, ...query } = checked("assets.listChildren", options);
457
- return this.request("GET", `/assets/${requireId(assetId, "Asset ID")}/children`, { query });
532
+ return this.#send("assets.update", requestOptions, "PATCH", `/assets/${requireId(assetId, "Asset ID")}`, { body });
458
533
  },
459
534
  /**
460
- * Lists one page of an audio or video asset's findings timeline, in time order.
535
+ * Lists the assets extracted from a website or multimedia document. Await it for one page,
536
+ * or `for await` over it for every child.
537
+ */
538
+ listChildren: (options, requestOptions) => this.#paginate("assets.listChildren", options ?? {}, requestOptions, ({ assetId, ...query }) => this.#send("assets.listChildren", requestOptions, "GET", `/assets/${requireId(assetId, "Asset ID")}/children`, { query })),
539
+ /**
540
+ * Lists an audio or video asset's findings timeline, in time order. Await it for one page,
541
+ * or `for await` over it for every segment.
461
542
  * `classification.moderation.timeline.segmentCount` says how many segments there are.
462
543
  */
463
- listTimeline: async (options) => {
464
- const { assetId, ...query } = checked("assets.listTimeline", options);
465
- const assetPath = `${this.projectPath}/assets/${requireId(assetId, "Asset ID")}`;
466
- return this.request("GET", `${assetPath}/timeline`, { query });
467
- },
468
- /** Yields every segment of an audio or video asset's findings timeline, in time order. */
469
- iterateTimeline: (options) => {
470
- checked("assets.iterateTimeline", options);
471
- requireId(options?.assetId, "Asset ID");
472
- return this.iteratePages((cursor) => this.buildAssets().listTimeline({
473
- ...options,
474
- cursor
475
- }));
476
- },
477
- /** Yields every child of an asset, fetching pages as needed. */
478
- iterateChildren: (options) => {
479
- checked("assets.iterateChildren", options);
480
- requireId(options?.assetId, "Asset ID");
481
- return this.iteratePages((cursor) => this.buildAssets().listChildren({
482
- ...options,
483
- cursor
484
- }));
485
- },
544
+ listTimeline: (options, requestOptions) => this.#paginate("assets.listTimeline", options, requestOptions, ({ assetId, ...query }) => {
545
+ const assetPath = `${this.#projectPath}/assets/${requireId(assetId, "Asset ID")}`;
546
+ return this.#send("assets.listTimeline", requestOptions, "GET", `${assetPath}/timeline`, { query });
547
+ }),
486
548
  /**
487
549
  * Uploads an asset and returns without waiting for its decision (`wait=false`), with
488
550
  * `classification.status` `queued`. Retried safely with an `Idempotency-Key`.
489
551
  */
490
- create: async (options) => this.submitAsset(checked("assets.create", options), false),
552
+ create: async (options, requestOptions) => this.#submitAsset("assets.create", checked("assets.create", options), false, requestOptions),
491
553
  /**
492
554
  * Uploads an asset and waits for its moderation decision. Documents, websites, audio, video
493
555
  * and files over 20 MiB sent in parts still finish in the background and return `pending`.
494
556
  * Retried safely with an `Idempotency-Key`.
495
557
  */
496
- classify: async (classifyOptions) => {
497
- const options = checked("assets.classify", classifyOptions);
498
- if (options && "content" in options && "plainText" in options.content && (typeof options.content.plainText !== "string" || !options.content.plainText.trim())) throw invalidPayload("Text to classify must be a non-empty string");
499
- return this.submitAsset(options, true);
500
- },
558
+ classify: async (options, requestOptions) => this.#submitAsset("assets.classify", checkedTextContent(checked("assets.classify", options)), true, requestOptions),
501
559
  /**
502
560
  * Uploads the next part of a multipart upload. Whether the final part waits for the
503
561
  * decision was chosen when the upload started; pass `wait` to override it.
504
562
  */
505
- uploadPart: async (partOptions) => {
563
+ uploadPart: async (partOptions, requestOptions) => {
506
564
  const { assetId, ...options } = checked("assets.uploadPart", partOptions);
507
565
  const encodedAssetId = requireId(assetId, "Asset ID");
508
- return expectAsset(await this.#connection.uploadPart(`/assets/${encodedAssetId}/part`, options));
566
+ const connection = this.#connection.forCall("assets.uploadPart", requestOptions);
567
+ return expectAsset(await connection.uploadPart(`/assets/${encodedAssetId}/part`, options));
509
568
  },
510
569
  /** Moves an asset into a folder, or to the project root with `folderId: null`. */
511
- move: async (options) => {
570
+ move: async (options, requestOptions) => {
512
571
  const { assetId, folderId } = checked("assets.move", options);
513
- return this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/move`, { body: { folderId } });
572
+ return this.#send("assets.move", requestOptions, "POST", `/assets/${requireId(assetId, "Asset ID")}/move`, { body: { folderId } });
514
573
  },
515
574
  /**
516
575
  * Processes an asset that failed (classification status `failed`) again. It returns to
517
576
  * `processing` and is
518
577
  * moderated like a new upload; its content must still be stored.
519
578
  */
520
- retry: async (options) => {
579
+ retry: async (options, requestOptions) => {
521
580
  const { assetId } = checked("assets.retry", options);
522
- return this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/retry`);
581
+ return this.#send("assets.retry", requestOptions, "POST", `/assets/${requireId(assetId, "Asset ID")}/retry`);
523
582
  },
524
583
  /**
525
584
  * Records a reviewer's decision, replacing the policy's: the asset's moderation status
@@ -527,53 +586,45 @@ sign: async (options) => {
527
586
  * event is sent. An asset still pending moderation can only be blocked or purged. Purging
528
587
  * needs `confirmPurge: true` and permanently deletes the stored content.
529
588
  */
530
- decide: async (options) => {
589
+ decide: async (options, requestOptions) => {
531
590
  const { assetId, ...body } = checked("assets.decide", options);
532
- return this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/decision`, { body });
533
- },
534
- /**
535
- * Completes the policy evidence behind a decided asset's moderation decision: its
536
- * `classification.moderation.explanationComplete` becomes `true` and every action stays as
537
- * decided. With `rerun: true` the asset is moderated again with the project's current policy
538
- * and an `asset.rerun-requested` event is recorded; use it when the policy has changed since
539
- * the decision (`asset/policy-changed`). The asset returns unchanged: it keeps its decision
540
- * until the re-run's is stored, reported by `asset.classified` and `asset.<status>` events,
541
- * and a failed re-run keeps it. A reviewed asset fails with `asset/reviewed`, and one whose
542
- * content is gone with `asset/content-unavailable`.
543
- */
544
- explain: async (options) => {
545
- const { assetId, rerun } = checked("assets.explain", options);
546
- return this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/explain`, { body: rerun ? { rerun } : {} });
591
+ return this.#send("assets.decide", requestOptions, "POST", `/assets/${requireId(assetId, "Asset ID")}/decision`, { body });
547
592
  },
548
593
  /**
549
594
  * Waits until an asset is settled, its `classification.status` `completed` (with its
550
- * decision in `classification.moderation.status`) or `failed`, and returns that asset,
595
+ * decision in `classification.moderation.decision`) or `failed`, and returns that asset,
551
596
  * checking every few seconds. A `queued` or `processing` asset is still waiting, even when a
552
597
  * reviewer has already decided it. Rejects with `sdk/timeout` if it is not settled within
553
598
  * `timeoutMs` (default 60000). Webhooks report decisions without polling.
554
599
  */
555
- waitForDecision: async (waitOptions) => {
600
+ waitForDecision: async (waitOptions, requestOptions) => {
556
601
  const { assetId, ...options } = checked("assets.waitForDecision", waitOptions);
557
602
  requireId(assetId, "Asset ID");
558
- const client = options.signal ? this.withRequestOptions({ signal: options.signal }) : this;
559
- return pollForDecision(() => client.assets.retrieve({ assetId }), options, this.#connection.sleep, this.#connection.hooks?.now);
603
+ validateCallOptions(requestOptions);
604
+ const signals = [options.signal, requestOptions?.signal].filter((signal) => signal !== void 0);
605
+ const signal = signals.length > 1 ? anySignal(signals) : signals[0];
606
+ const checkOptions = {
607
+ ...requestOptions,
608
+ ...signal && { signal }
609
+ };
610
+ return pollForDecision(() => this.#send("assets.waitForDecision", checkOptions, "GET", `/assets/${requireId(assetId, "Asset ID")}`), options, this.#connection.sleep, this.#connection.hooks?.now);
560
611
  },
561
612
  /**
562
613
  * Removes an asset's stored content (source, preview and retained extracted text) while
563
614
  * keeping the asset record, metadata and classification results. The returned asset has
564
615
  * `content.status` set to `removed` and `content.removalReason` to `requested`; the CDN no longer serves it.
565
616
  */
566
- removeContent: async (options) => {
617
+ removeContent: async (options, requestOptions) => {
567
618
  const { assetId } = checked("assets.removeContent", options);
568
- return this.request("DELETE", `/assets/${requireId(assetId, "Asset ID")}/content`);
619
+ return this.#send("assets.removeContent", requestOptions, "DELETE", `/assets/${requireId(assetId, "Asset ID")}/content`);
569
620
  },
570
621
  /**
571
622
  * Deletes an asset record together with its stored content. An asset extracted from another
572
623
  * (one with a `parentId`) fails with `asset/child-not-deletable`: delete its parent instead.
573
624
  */
574
- delete: async (options) => {
625
+ delete: async (options, requestOptions) => {
575
626
  const { assetId } = checked("assets.delete", options);
576
- await this.request("DELETE", `/assets/${requireId(assetId, "Asset ID")}`);
627
+ await this.#send("assets.delete", requestOptions, "DELETE", `/assets/${requireId(assetId, "Asset ID")}`);
577
628
  },
578
629
  /**
579
630
  * Deletes up to 500 assets (`operation: "delete"`) or removes their stored content
@@ -585,13 +636,13 @@ sign: async (options) => {
585
636
  * fact naming `batchId`. Assets under a safety hold are skipped. Not retried: it carries no
586
637
  * `Idempotency-Key`.
587
638
  */
588
- batch: async (options) => {
639
+ batch: async (options, requestOptions) => {
589
640
  const { assetIds, operation } = checked("assets.batch", options);
590
641
  validateBatchAssetsOptions({
591
642
  assetIds,
592
643
  operation
593
644
  });
594
- return this.request("POST", `${this.projectPath}/assets/batch`, { body: {
645
+ return this.#send("assets.batch", requestOptions, "POST", `${this.#projectPath}/assets/batch`, { body: {
595
646
  assetIds,
596
647
  operation
597
648
  } });
@@ -599,89 +650,47 @@ sign: async (options) => {
599
650
  };
600
651
  }
601
652
  get events() {
602
- return {
603
- /**
604
- * Lists project events after a cursor, oldest first. Call without `cursor` to get a cursor
605
- * for "now", then poll with each response's `nextCursor`. Webhook deliveries carry each
606
- * event's same fields as a flat JSON body. `types` and `assetId` narrow the feed to some
607
- * event types or one asset's events; a cursor belongs to the filters it was issued with, so
608
- * pass the same ones with each `cursor`.
609
- */
610
- list: async (options = {}) => {
611
- const { types, ...query } = checked("events.list", options);
612
- return this.request("GET", `${this.projectPath}/events`, { query: {
613
- ...query,
614
- types: types?.length ? types.join(",") : void 0
615
- } });
616
- },
617
- /**
618
- * Yields pages of events after `cursor` until no more are waiting. Save each page's
619
- * `nextCursor` to resume later. Without `cursor`, yields one empty page whose `nextCursor`
620
- * is "now".
621
- */
622
- pages: (options = {}) => this.iterateEventPages(checked("events.pages", options))
623
- };
624
- }
625
- async *iterateEventPages(options) {
626
- let cursor = options.cursor;
627
- const sent = new Set(cursor === void 0 ? [] : [cursor]);
628
- for (;;) {
629
- const page = await this.events.list({
630
- ...options,
631
- cursor
632
- });
633
- if (page.hasMore) assertNewCursor(sent, page.nextCursor);
634
- yield page;
635
- if (!page.hasMore) return;
636
- cursor = page.nextCursor;
637
- }
638
- }
639
- async *iteratePages(listPage) {
640
- let cursor;
641
- const sent = /* @__PURE__ */ new Set();
642
- for (;;) {
643
- const page = await listPage(cursor);
644
- const more = !!page.nextCursor && page.hasMore && page.items.length > 0;
645
- if (more) assertNewCursor(sent, page.nextCursor);
646
- yield* page.items;
647
- if (!more) return;
648
- cursor = page.nextCursor;
649
- }
653
+ return {
654
+ /**
655
+ * Lists project events after a cursor, oldest first. Call without `cursor` to get a cursor
656
+ * for "now", then poll with each response's `nextCursor`. Webhook deliveries carry each
657
+ * event's same fields as a flat JSON body. `types` and `assetId` narrow the feed to some
658
+ * event types or one asset's events; a cursor belongs to the filters it was issued with, so
659
+ * pass the same ones with each `cursor`. `for await` over it yields every event waiting
660
+ * after `cursor`; save the last page's `nextCursor` to resume later.
661
+ */
662
+ list: (options = {}, requestOptions) => this.#paginate("events.list", options, requestOptions, ({ types, ...query }) => this.#send("events.list", requestOptions, "GET", `${this.#projectPath}/events`, { query: {
663
+ ...query,
664
+ types: types?.length ? types.join(",") : void 0
665
+ } })) };
650
666
  }
651
667
  get folders() {
652
668
  return {
653
669
  /**
654
- * Lists one page of child folders, sorted by name unless `sort` says otherwise. Pass
655
- * `nextCursor` as `cursor` for the next page; fetch a branch when it is opened.
670
+ * Lists the child folders of `parentId` (or the project root), sorted by name unless
671
+ * `sort` says otherwise. Await it for one page, or `for await` over it for every folder;
672
+ * fetch a branch when it is opened.
656
673
  */
657
- list: async (options = {}) => this.request("GET", `${this.projectPath}/folders`, { query: checked("folders.list", options) }),
658
- /** Yields every child folder of `parentId` (or the project root), fetching pages as needed. */
659
- iterate: (options = {}) => {
660
- checked("folders.iterate", options);
661
- return this.iteratePages((cursor) => this.folders.list({
662
- ...options,
663
- cursor
664
- }));
665
- },
666
- retrieve: async (options) => {
674
+ list: (options = {}, requestOptions) => this.#paginate("folders.list", options, requestOptions, (query) => this.#send("folders.list", requestOptions, "GET", `${this.#projectPath}/folders`, { query })),
675
+ retrieve: async (options, requestOptions) => {
667
676
  const { folderId } = checked("folders.retrieve", options);
668
- return this.request("GET", `/folders/${requireId(folderId, "Folder ID")}`);
677
+ return this.#send("folders.retrieve", requestOptions, "GET", `/folders/${requireId(folderId, "Folder ID")}`);
669
678
  },
670
679
  /** Creates a folder at the project root or inside `parentId`. */
671
- create: async (options) => this.request("POST", `${this.projectPath}/folders`, { body: checked("folders.create", options) }),
672
- update: async (options) => {
680
+ create: async (options, requestOptions) => this.#send("folders.create", requestOptions, "POST", `${this.#projectPath}/folders`, { body: checked("folders.create", options) }),
681
+ update: async (options, requestOptions) => {
673
682
  const { folderId, ...body } = checked("folders.update", options);
674
- return this.request("PATCH", `/folders/${requireId(folderId, "Folder ID")}`, { body });
683
+ return this.#send("folders.update", requestOptions, "PATCH", `/folders/${requireId(folderId, "Folder ID")}`, { body });
675
684
  },
676
685
  /** Deletes an empty folder; throws `folder/not-empty` otherwise. */
677
- delete: async (options) => {
686
+ delete: async (options, requestOptions) => {
678
687
  const { folderId } = checked("folders.delete", options);
679
- await this.request("DELETE", `/folders/${requireId(folderId, "Folder ID")}`);
688
+ await this.#send("folders.delete", requestOptions, "DELETE", `/folders/${requireId(folderId, "Folder ID")}`);
680
689
  },
681
690
  /** Moves a folder under `parentId`, or to the project root with `parentId: null`. */
682
- move: async (options) => {
691
+ move: async (options, requestOptions) => {
683
692
  const { folderId, parentId } = checked("folders.move", options);
684
- return this.request("POST", `/folders/${requireId(folderId, "Folder ID")}/move`, { body: { parentId } });
693
+ return this.#send("folders.move", requestOptions, "POST", `/folders/${requireId(folderId, "Folder ID")}/move`, { body: { parentId } });
685
694
  }
686
695
  };
687
696
  }
@@ -691,53 +700,33 @@ sign: async (options) => {
691
700
  */
692
701
  get hashLists() {
693
702
  return {
694
- /** Lists one page of the project's hash lists, newest first unless `sort` says otherwise. */
695
- list: async (options = {}) => this.request("GET", `${this.projectPath}/hash-lists`, { query: checked("hashLists.list", options) }),
696
- /** Yields every hash list, fetching pages as needed. */
697
- iterate: (options = {}) => {
698
- checked("hashLists.iterate", options);
699
- return this.iteratePages((cursor) => this.hashLists.list({
700
- ...options,
701
- cursor
702
- }));
703
- },
704
- retrieve: async (options) => {
703
+ /** Lists the project's hash lists, newest first unless `sort` says otherwise. */
704
+ list: (options = {}, requestOptions) => this.#paginate("hashLists.list", options, requestOptions, (query) => this.#send("hashLists.list", requestOptions, "GET", `${this.#projectPath}/hash-lists`, { query })),
705
+ retrieve: async (options, requestOptions) => {
705
706
  const { hashListId } = checked("hashLists.retrieve", options);
706
- return this.request("GET", `/hash-lists/${requireId(hashListId, "Hash list ID")}`);
707
+ return this.#send("hashLists.retrieve", requestOptions, "GET", `/hash-lists/${requireId(hashListId, "Hash list ID")}`);
707
708
  },
708
- create: async (options) => this.request("POST", `${this.projectPath}/hash-lists`, { body: checked("hashLists.create", options) }),
709
+ create: async (options, requestOptions) => this.#send("hashLists.create", requestOptions, "POST", `${this.#projectPath}/hash-lists`, { body: checked("hashLists.create", options) }),
709
710
  /** Renames a list or changes its action; the new action applies to later uploads. */
710
- update: async (options) => {
711
+ update: async (options, requestOptions) => {
711
712
  const { hashListId, ...body } = checked("hashLists.update", options);
712
- return this.request("PATCH", `/hash-lists/${requireId(hashListId, "Hash list ID")}`, { body });
713
+ return this.#send("hashLists.update", requestOptions, "PATCH", `/hash-lists/${requireId(hashListId, "Hash list ID")}`, { body });
713
714
  },
714
715
  /** Deletes the list and every entry in it. */
715
- delete: async (options) => {
716
+ delete: async (options, requestOptions) => {
716
717
  const { hashListId } = checked("hashLists.delete", options);
717
- await this.request("DELETE", `/hash-lists/${requireId(hashListId, "Hash list ID")}`);
718
- },
719
- /** Yields every entry of a list, fetching pages as needed. */
720
- iterateEntries: (options) => {
721
- checked("hashLists.iterateEntries", options);
722
- requireId(options?.hashListId, "Hash list ID");
723
- return this.iteratePages((cursor) => this.hashLists.listEntries({
724
- ...options,
725
- cursor
726
- }));
727
- },
728
- /** Lists one page of a list's entries, newest first unless `sort` says otherwise. */
729
- listEntries: async (options) => {
730
- const { hashListId, ...query } = checked("hashLists.listEntries", options);
731
- return this.request("GET", `/hash-lists/${requireId(hashListId, "Hash list ID")}/entries`, { query });
718
+ await this.#send("hashLists.delete", requestOptions, "DELETE", `/hash-lists/${requireId(hashListId, "Hash list ID")}`);
732
719
  },
720
+ /** Lists a list's entries, newest first unless `sort` says otherwise. */
721
+ listEntries: (options, requestOptions) => this.#paginate("hashLists.listEntries", options, requestOptions, ({ hashListId, ...query }) => this.#send("hashLists.listEntries", requestOptions, "GET", `/hash-lists/${requireId(hashListId, "Hash list ID")}/entries`, { query })),
733
722
  /** Adds a hash, or an image asset's hash; a hash already in the list returns its entry. */
734
- addEntry: async (options) => {
723
+ addEntry: async (options, requestOptions) => {
735
724
  const { hashListId, ...body } = checked("hashLists.addEntry", options);
736
- return this.request("POST", `/hash-lists/${requireId(hashListId, "Hash list ID")}/entries`, { body });
725
+ return this.#send("hashLists.addEntry", requestOptions, "POST", `/hash-lists/${requireId(hashListId, "Hash list ID")}/entries`, { body });
737
726
  },
738
- removeEntry: async (options) => {
727
+ removeEntry: async (options, requestOptions) => {
739
728
  const { entryId } = checked("hashLists.removeEntry", options);
740
- await this.request("DELETE", `/hash-list-entries/${requireId(entryId, "Hash list entry ID")}`);
729
+ await this.#send("hashLists.removeEntry", requestOptions, "DELETE", `/hash-list-entries/${requireId(entryId, "Hash list entry ID")}`);
741
730
  }
742
731
  };
743
732
  }
@@ -749,47 +738,39 @@ sign: async (options) => {
749
738
  get policies() {
750
739
  const policyPath = (policyId) => `/policies/${requireId(policyId, "Policy ID")}`;
751
740
  return {
752
- /** Lists one page of the organisation's policies, oldest first unless `sort` says otherwise. */
753
- list: async (options = {}) => this.request("GET", "/policies", { query: checked("policies.list", options) }),
754
- /** Yields every policy of the organisation, fetching pages as needed. */
755
- iterate: (options = {}) => {
756
- checked("policies.iterate", options);
757
- return this.iteratePages((cursor) => this.policies.list({
758
- ...options,
759
- cursor
760
- }));
761
- },
762
- retrieve: async (options) => this.request("GET", policyPath(checked("policies.retrieve", options).policyId)),
741
+ /** Lists the organisation's policies, oldest first unless `sort` says otherwise. */
742
+ list: (options = {}, requestOptions) => this.#paginate("policies.list", options, requestOptions, (query) => this.#send("policies.list", requestOptions, "GET", "/policies", { query })),
743
+ retrieve: async (options, requestOptions) => this.#send("policies.retrieve", requestOptions, "GET", policyPath(checked("policies.retrieve", options).policyId)),
763
744
  /** Creates a policy from `settings`, or a copy of a built-in preset with `presetId`. */
764
- create: async (options) => this.request("POST", "/policies", { body: checked("policies.create", options) }),
745
+ create: async (options, requestOptions) => this.#send("policies.create", requestOptions, "POST", "/policies", { body: checked("policies.create", options) }),
765
746
  /** Changes the name, description or settings; later moderation uses them. */
766
- update: async (options) => {
747
+ update: async (options, requestOptions) => {
767
748
  const { policyId, ...body } = checked("policies.update", options);
768
- return this.request("PATCH", policyPath(policyId), { body });
749
+ return this.#send("policies.update", requestOptions, "PATCH", policyPath(policyId), { body });
769
750
  },
770
751
  /** Restores the settings of the preset release a `pinned` or `copy` policy is pinned to. */
771
- reset: async (options) => {
752
+ reset: async (options, requestOptions) => {
772
753
  const { policyId, ...body } = checked("policies.reset", options);
773
- return this.request("POST", `${policyPath(policyId)}/reset`, { body });
754
+ return this.#send("policies.reset", requestOptions, "POST", `${policyPath(policyId)}/reset`, { body });
774
755
  },
775
756
  /** Moves an unchanged `pinned` or `copy` policy to the latest release of its preset. */
776
- upgrade: async (options) => {
757
+ upgrade: async (options, requestOptions) => {
777
758
  const { policyId, ...body } = checked("policies.upgrade", options);
778
- return this.request("POST", `${policyPath(policyId)}/upgrade`, { body });
759
+ return this.#send("policies.upgrade", requestOptions, "POST", `${policyPath(policyId)}/upgrade`, { body });
779
760
  },
780
761
  /** Switches automatic updates on (`live`) or off (`pinned`) for the organisation's own preset policy. */
781
- setAutomaticUpdates: async (options) => {
762
+ setAutomaticUpdates: async (options, requestOptions) => {
782
763
  const { policyId, ...body } = checked("policies.setAutomaticUpdates", options);
783
- return this.request("PUT", `${policyPath(policyId)}/automatic-updates`, { body });
764
+ return this.#send("policies.setAutomaticUpdates", requestOptions, "PUT", `${policyPath(policyId)}/automatic-updates`, { body });
784
765
  },
785
766
  /** Deletes a policy that no project or upload preset uses. */
786
- delete: async (options) => {
787
- await this.request("DELETE", policyPath(checked("policies.delete", options).policyId));
767
+ delete: async (options, requestOptions) => {
768
+ await this.#send("policies.delete", requestOptions, "DELETE", policyPath(checked("policies.delete", options).policyId));
788
769
  },
789
770
  /** The policy the project moderates with. */
790
- retrieveAssigned: async () => this.request("GET", `${this.projectPath}/policy`),
771
+ retrieveAssigned: async (requestOptions) => this.#send("policies.retrieveAssigned", requestOptions, "GET", `${this.#projectPath}/policy`),
791
772
  /** Chooses the policy the project moderates with. */
792
- assign: async (options) => this.request("PUT", `${this.projectPath}/policy`, { body: checked("policies.assign", options) })
773
+ assign: async (options, requestOptions) => this.#send("policies.assign", requestOptions, "PUT", `${this.#projectPath}/policy`, { body: checked("policies.assign", options) })
793
774
  };
794
775
  }
795
776
  /**
@@ -799,25 +780,17 @@ sign: async (options) => {
799
780
  */
800
781
  get uploadPresets() {
801
782
  return {
802
- /** Lists one page of the project's upload presets, oldest first unless `sort` says otherwise. */
803
- list: async (options = {}) => this.request("GET", `${this.projectPath}/upload-presets`, { query: checked("uploadPresets.list", options) }),
804
- /** Yields every upload preset of the project, fetching pages as needed. */
805
- iterate: (options = {}) => {
806
- checked("uploadPresets.iterate", options);
807
- return this.iteratePages((cursor) => this.uploadPresets.list({
808
- ...options,
809
- cursor
810
- }));
811
- },
783
+ /** Lists the project's upload presets, oldest first unless `sort` says otherwise. */
784
+ list: (options = {}, requestOptions) => this.#paginate("uploadPresets.list", options, requestOptions, (query) => this.#send("uploadPresets.list", requestOptions, "GET", `${this.#projectPath}/upload-presets`, { query })),
812
785
  /**
813
786
  * Creates each preset, or replaces it with the definition sent, by key. Every preset is
814
787
  * checked before any is saved. Returns the stored presets in the order sent.
815
788
  */
816
- ensure: async (options) => this.request("PUT", `${this.projectPath}/upload-presets`, { body: checked("uploadPresets.ensure", options) }),
789
+ ensure: async (options, requestOptions) => this.#send("uploadPresets.ensure", requestOptions, "PUT", `${this.#projectPath}/upload-presets`, { body: checked("uploadPresets.ensure", options) }),
817
790
  /** Deletes an upload preset; assets already uploaded through it stay. */
818
- delete: async (options) => {
791
+ delete: async (options, requestOptions) => {
819
792
  const { uploadPresetId } = checked("uploadPresets.delete", options);
820
- await this.request("DELETE", `/upload-presets/${requireId(uploadPresetId, "Upload preset ID")}`);
793
+ await this.#send("uploadPresets.delete", requestOptions, "DELETE", `/upload-presets/${requireId(uploadPresetId, "Upload preset ID")}`);
821
794
  }
822
795
  };
823
796
  }
@@ -827,8 +800,8 @@ sign: async (options) => {
827
800
  */
828
801
  get projectSettings() {
829
802
  return {
830
- get: async () => this.request("GET", `${this.projectPath}/settings`),
831
- update: async (options) => this.request("PUT", `${this.projectPath}/settings`, { body: checked("projectSettings.update", options) })
803
+ get: async (requestOptions) => this.#send("projectSettings.get", requestOptions, "GET", `${this.#projectPath}/settings`),
804
+ update: async (options, requestOptions) => this.#send("projectSettings.update", requestOptions, "PUT", `${this.#projectPath}/settings`, { body: checked("projectSettings.update", options) })
832
805
  };
833
806
  }
834
807
  /**
@@ -837,12 +810,12 @@ sign: async (options) => {
837
810
  */
838
811
  get metadataFields() {
839
812
  return {
840
- list: async () => this.request("GET", `${this.projectPath}/metadata-fields`),
841
- ensure: async (options) => this.request("PUT", `${this.projectPath}/metadata-fields`, { body: checked("metadataFields.ensure", options) }),
813
+ list: async (requestOptions) => this.#send("metadataFields.list", requestOptions, "GET", `${this.#projectPath}/metadata-fields`),
814
+ ensure: async (options, requestOptions) => this.#send("metadataFields.ensure", requestOptions, "PUT", `${this.#projectPath}/metadata-fields`, { body: checked("metadataFields.ensure", options) }),
842
815
  /** Deletes a field definition; assets keep their values. */
843
- delete: async (options) => {
816
+ delete: async (options, requestOptions) => {
844
817
  const { fieldId, ...query } = checked("metadataFields.delete", options);
845
- await this.request("DELETE", `${this.projectPath}/metadata-fields/${requireId(fieldId, "Metadata field ID")}`, { query });
818
+ await this.#send("metadataFields.delete", requestOptions, "DELETE", `${this.#projectPath}/metadata-fields/${requireId(fieldId, "Metadata field ID")}`, { query });
846
819
  }
847
820
  };
848
821
  }
@@ -857,34 +830,26 @@ sign: async (options) => {
857
830
  for (const [cacheKey, lens] of this.#lenses.ensuredLenses) if (matches(lens)) this.#lenses.ensuredLenses.delete(cacheKey);
858
831
  };
859
832
  return {
860
- /** Lists one page of the project's lenses, newest first unless `sort` says otherwise. */
861
- list: async (options = {}) => this.request("GET", `${this.projectPath}/lenses`, { query: checked("lenses.list", options) }),
862
- /** Yields every lens of the project, fetching pages as needed. */
863
- iterate: (options = {}) => {
864
- checked("lenses.iterate", options);
865
- return this.iteratePages((cursor) => this.lenses.list({
866
- ...options,
867
- cursor
868
- }));
869
- },
833
+ /** Lists the project's lenses, newest first unless `sort` says otherwise. */
834
+ list: (options = {}, requestOptions) => this.#paginate("lenses.list", options, requestOptions, (query) => this.#send("lenses.list", requestOptions, "GET", `${this.#projectPath}/lenses`, { query })),
870
835
  /** Creates a lens; its identifier must be new to the project. */
871
- create: async (options) => {
872
- const lens = await this.request("POST", `${this.projectPath}/lenses`, { body: checked("lenses.create", options) });
836
+ create: async (options, requestOptions) => {
837
+ const lens = await this.#send("lenses.create", requestOptions, "POST", `${this.#projectPath}/lenses`, { body: checked("lenses.create", options) });
873
838
  forget((cached) => cached.identifier === lens.identifier);
874
839
  return lens;
875
840
  },
876
- retrieve: async (options) => this.request("GET", lensPath(checked("lenses.retrieve", options).lensId)),
841
+ retrieve: async (options, requestOptions) => this.#send("lenses.retrieve", requestOptions, "GET", lensPath(checked("lenses.retrieve", options).lensId)),
877
842
  /** Changes a lens's name, description, type, transform or whether the CDN serves it. */
878
- update: async (options) => {
843
+ update: async (options, requestOptions) => {
879
844
  const { lensId, ...body } = checked("lenses.update", options);
880
- const lens = await this.request("PATCH", lensPath(lensId), { body });
845
+ const lens = await this.#send("lenses.update", requestOptions, "PATCH", lensPath(lensId), { body });
881
846
  forget((cached) => cached.id === lens.id);
882
847
  return lens;
883
848
  },
884
849
  /** Deletes a lens; URLs that select it stop being served. */
885
- delete: async (options) => {
850
+ delete: async (options, requestOptions) => {
886
851
  const { lensId } = checked("lenses.delete", options);
887
- await this.request("DELETE", lensPath(lensId));
852
+ await this.#send("lenses.delete", requestOptions, "DELETE", lensPath(lensId));
888
853
  forget((cached) => cached.id === lensId);
889
854
  }
890
855
  };
@@ -893,10 +858,10 @@ sign: async (options) => {
893
858
  * Creates a named lens, or changes it to this definition. Sending the same definition again
894
859
  * returns the lens unchanged, from the client's lens cache once it has seen it.
895
860
  */
896
- async ensureLens(options) {
861
+ async ensureLens(options, requestOptions) {
897
862
  checked("ensureLens", options);
898
863
  if (!options?.identifier) throw invalidArgument("Lens identifier is required");
899
- const [lens] = await this.ensureLenses({ lenses: [options] });
864
+ const [lens] = await this.ensureLenses({ lenses: [options] }, requestOptions);
900
865
  return lens;
901
866
  }
902
867
  /**
@@ -904,7 +869,8 @@ sign: async (options) => {
904
869
  * consecutive requests of at most {@link ENSURE_LENSES_MAX_PER_REQUEST} definitions, in order.
905
870
  * Each lens is created or changed as ensureLens() does.
906
871
  */
907
- async ensureLenses(options) {
872
+ async ensureLenses(options, requestOptions) {
873
+ validateCallOptions(requestOptions);
908
874
  const { lenses } = checked("ensureLenses", options);
909
875
  if (!Array.isArray(lenses) || lenses.length === 0) throw invalidArgument("At least one lens is required");
910
876
  if (lenses.some((option) => !option?.identifier)) throw invalidArgument("Lens identifier is required");
@@ -923,7 +889,7 @@ sign: async (options) => {
923
889
  const batchCacheKey = JSON.stringify([...missingKeys].sort());
924
890
  let pending = pendingEnsureLenses.get(batchCacheKey);
925
891
  if (!pending) {
926
- pending = this.submitEnsureLenses(missingOptions);
892
+ pending = this.#submitEnsureLenses(missingOptions, requestOptions);
927
893
  pendingEnsureLenses.set(batchCacheKey, pending);
928
894
  pending.then(() => pendingEnsureLenses.delete(batchCacheKey), () => pendingEnsureLenses.delete(batchCacheKey));
929
895
  }
@@ -935,11 +901,11 @@ sign: async (options) => {
935
901
  return lens;
936
902
  });
937
903
  }
938
- async submitEnsureLenses(options) {
939
- for (let start = 0; start < options.length; start += 100) await this.submitEnsureLensesChunk(options.slice(start, start + 100));
904
+ async #submitEnsureLenses(options, requestOptions) {
905
+ for (let start = 0; start < options.length; start += 100) await this.#submitEnsureLensesChunk(options.slice(start, start + 100), requestOptions);
940
906
  }
941
- async submitEnsureLensesChunk(options) {
942
- const result = await this.request("PUT", `${this.projectPath}/lenses`, { body: { lenses: options } });
907
+ async #submitEnsureLensesChunk(options, requestOptions) {
908
+ const result = await this.#send("ensureLenses", requestOptions, "PUT", `${this.#projectPath}/lenses`, { body: { lenses: options } });
943
909
  const returned = Array.isArray(result?.lenses) ? result.lenses : [];
944
910
  if (returned.length !== options.length) throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, { message: `Expected ${options.length} lenses but CalmLens returned ${returned.length}` });
945
911
  const { ensuredLenses } = this.#lenses;