calmlens 0.19.0 → 0.21.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 (108) hide show
  1. package/README.md +13 -9
  2. package/bin/calmlens.js +1646 -706
  3. package/cjs/{BrowserUpload-CJ4Xc9bR.js → BrowserUpload-CeSwiMo5.js} +1 -1
  4. package/{esm/BrowserUpload-RkxV_Vv7.d.ts → cjs/BrowserUpload-D-NnAN7g.d.ts} +2 -2
  5. package/cjs/{CalmLensAppClient-LHMEQ-UZ.js → CalmLensAppClient-0UVCuNqW.js} +30 -10
  6. package/cjs/{CalmLensAppClient-B5gfOB6J.d.ts → CalmLensAppClient-gG16T2py.d.ts} +13 -3
  7. package/cjs/{CalmLensOptionKeys-BUj7v5AG.js → CalmLensOptionKeys-CYY6elxg.js} +242 -345
  8. package/cjs/{CalmLensServerClient-DCSbwIBs.d.ts → CalmLensServerClient-BHx3x_nZ.d.ts} +107 -49
  9. package/cjs/{CalmLensServerClient-BVOEUT_v.js → CalmLensServerClient-nfu6_YEW.js} +297 -92
  10. package/cjs/{CalmLensTypes-DpU-hXq2.d.ts → CalmLensTypes-CUB0YYVz.d.ts} +26601 -27354
  11. package/cjs/{Classification-D3SkprrQ-CMnQKW13.d.ts → Classification-Q5zGpR8l-CEWjnE39.d.ts} +731 -607
  12. package/cjs/Core-C82YmjjX.d.ts +823 -0
  13. package/cjs/Core-Dc3cteU7.js +998 -0
  14. package/cjs/FileIcons-4qSX7DW2.d.ts +67 -0
  15. package/cjs/{ModerationContextLimits-FDpQmw_T.js → ModerationContextLimits-BxOmeSqq.js} +970 -278
  16. package/cjs/{ReactUpload-BvpW4hJi.js → ReactUpload-BK2O3dnK.js} +1 -1
  17. package/cjs/{ReactUpload-huIMnOJ4.d.ts → ReactUpload-DiiXfKvj.d.ts} +1 -1
  18. package/cjs/{TestTriggers-CMwMrbjy-K0YBzu2a.js → TestTriggers-BTyXtX0Q-ATuFDhLX.js} +343 -35
  19. package/{esm/TestTriggers-D-fwfhEP-hlaP1oW2.d.ts → cjs/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts} +146 -8
  20. package/cjs/{UploadController-D4qOZZc3.js → UploadController-DLyiLDTB.js} +34 -14
  21. package/cjs/{WebhookPayload-CQg8BBZQ.d.ts → WebhookPayload-BLT2y_Jy.d.ts} +93 -86
  22. package/cjs/app.d.ts +6 -7
  23. package/cjs/app.js +4 -3
  24. package/cjs/elements.d.ts +123 -22
  25. package/cjs/elements.js +553 -156
  26. package/cjs/file-icons.d.ts +2 -67
  27. package/cjs/index-CKRgjV16.d.ts +16 -0
  28. package/cjs/index.d.ts +5 -6
  29. package/cjs/index.js +3 -2
  30. package/cjs/react-native.d.ts +52 -11
  31. package/cjs/react-native.js +231 -99
  32. package/cjs/react.d.ts +42 -9
  33. package/cjs/react.js +381 -118
  34. package/cjs/server.d.ts +48 -7
  35. package/cjs/server.js +7 -3
  36. package/cjs/test-inputs.d.ts +2 -2
  37. package/cjs/test-inputs.js +13 -9
  38. package/cjs/testing.d.ts +29 -16
  39. package/cjs/testing.js +1511 -397
  40. package/cjs/ui-CTBUxnVp.d.ts +139 -0
  41. package/cjs/ui-CZ8exACq.js +1359 -0
  42. package/cjs/ui.d.ts +3 -2
  43. package/cjs/ui.js +45 -22
  44. package/cjs/vue.d.ts +802 -199
  45. package/cjs/vue.js +359 -127
  46. package/{cjs/BrowserUpload-RkxV_Vv7.d.ts → esm/BrowserUpload-D-NnAN7g.d.ts} +2 -2
  47. package/esm/{BrowserUpload-DpzS2bbj.js → BrowserUpload-i9OhCzMJ.js} +1 -1
  48. package/esm/{CalmLensAppClient-BjlvBweS.js → CalmLensAppClient-CK4_Py0c.js} +30 -10
  49. package/esm/{CalmLensAppClient-B5gfOB6J.d.ts → CalmLensAppClient-gG16T2py.d.ts} +13 -3
  50. package/esm/{CalmLensOptionKeys-BKez0Wiw.js → CalmLensOptionKeys-BGZlIsT2.js} +235 -338
  51. package/esm/{CalmLensServerClient-DCSbwIBs.d.ts → CalmLensServerClient-BHx3x_nZ.d.ts} +107 -49
  52. package/esm/{CalmLensServerClient-DemxbNMn.js → CalmLensServerClient-dAQUcDWb.js} +274 -93
  53. package/esm/{CalmLensTypes-DpU-hXq2.d.ts → CalmLensTypes-CUB0YYVz.d.ts} +26601 -27354
  54. package/esm/{Classification-D3SkprrQ-CMnQKW13.d.ts → Classification-Q5zGpR8l-CEWjnE39.d.ts} +731 -607
  55. package/esm/Core-BxeIud_S.js +843 -0
  56. package/esm/Core-C82YmjjX.d.ts +823 -0
  57. package/esm/FileIcons-4qSX7DW2.d.ts +67 -0
  58. package/esm/{ModerationContextLimits-lLfmyLni.js → ModerationContextLimits-B6_RalCQ.js} +911 -261
  59. package/esm/{ReactUpload-huIMnOJ4.d.ts → ReactUpload-DiiXfKvj.d.ts} +1 -1
  60. package/esm/{ReactUpload-6klucehl.js → ReactUpload-DxwVqfX1.js} +1 -1
  61. package/esm/{TestTriggers-CMwMrbjy-bdowBBKw.js → TestTriggers-BTyXtX0Q-GRB9jQwo.js} +320 -36
  62. package/{cjs/TestTriggers-D-fwfhEP-hlaP1oW2.d.ts → esm/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts} +146 -8
  63. package/esm/{UploadController-UxP6gj7A.js → UploadController-D9Z-h00Q.js} +34 -14
  64. package/esm/{WebhookPayload-CQg8BBZQ.d.ts → WebhookPayload-BLT2y_Jy.d.ts} +93 -86
  65. package/esm/app.d.ts +6 -7
  66. package/esm/app.js +3 -3
  67. package/esm/elements.d.ts +123 -22
  68. package/esm/elements.js +497 -128
  69. package/esm/file-icons.d.ts +2 -67
  70. package/esm/index-CKRgjV16.d.ts +16 -0
  71. package/esm/index.d.ts +5 -6
  72. package/esm/index.js +1 -1
  73. package/esm/react-native.d.ts +52 -11
  74. package/esm/react-native.js +205 -75
  75. package/esm/react.d.ts +42 -9
  76. package/esm/react.js +327 -91
  77. package/esm/server.d.ts +48 -7
  78. package/esm/server.js +3 -3
  79. package/esm/styles.css +142 -22
  80. package/esm/svelte/AssetViewer.svelte +25 -0
  81. package/esm/svelte/CalmLensAsset.svelte +318 -0
  82. package/esm/svelte/CalmLensDocumentViewer.svelte +7 -0
  83. package/esm/svelte/CalmLensImageViewer.svelte +7 -0
  84. package/esm/svelte/CalmLensSpreadsheetViewer.svelte +7 -0
  85. package/esm/svelte/CalmLensTextViewer.svelte +7 -0
  86. package/esm/svelte/CalmLensWebsiteViewer.svelte +7 -0
  87. package/esm/svelte/index.d.ts +29 -6
  88. package/esm/svelte/index.js +7 -2
  89. package/esm/test-inputs.d.ts +2 -2
  90. package/esm/test-inputs.js +1 -1
  91. package/esm/testing.d.ts +29 -16
  92. package/esm/testing.js +1507 -393
  93. package/esm/ui-CTBUxnVp.d.ts +139 -0
  94. package/esm/ui-Cr7s6JHm.js +1258 -0
  95. package/esm/ui.d.ts +3 -2
  96. package/esm/ui.js +4 -3
  97. package/esm/vue.d.ts +802 -199
  98. package/esm/vue.js +308 -103
  99. package/package.json +3 -1
  100. package/cjs/ModerationContext-9lGm-Mna-CcmbRnOy.d.ts +0 -67
  101. package/cjs/index-BcDDQJF2.d.ts +0 -253
  102. package/cjs/ui-B23r8BvW.d.ts +0 -539
  103. package/cjs/ui-Dq-cm6Rx.js +0 -586
  104. package/esm/ModerationContext-9lGm-Mna-CcmbRnOy.d.ts +0 -67
  105. package/esm/index-BcDDQJF2.d.ts +0 -253
  106. package/esm/svelte/CalmLensMedia.svelte +0 -134
  107. package/esm/ui-B23r8BvW.d.ts +0 -539
  108. package/esm/ui-Bn29rfAi.js +0 -461
package/bin/calmlens.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // src/cli/index.ts
3
3
  import { parseArgs } from "node:util";
4
4
  // package.json
5
- var version = "0.19.0";
5
+ var version = "0.21.0";
6
6
 
7
7
  // src/contract/ModerationCategories-CHFRoeWV.js
8
8
  var CLASSIFICATION_CATEGORIES = [
@@ -22,390 +22,65 @@ var stringifyJsonCanonical = (value) => JSON.stringify(value, (_key, nestedValue
22
22
  return Object.fromEntries(Object.keys(nestedValue).sort().map((key) => [key, nestedValue[key]]));
23
23
  });
24
24
 
25
- // src/contract/AssetPayload.js
26
- var bufferInputToBytes = (value) => {
27
- if (value instanceof ArrayBuffer)
28
- return new Uint8Array(value);
29
- return Uint8Array.from(value);
30
- };
31
- var BASE64_PART_BOUNDARY_ERROR = "Invalid base64 part. For multipart uploads, split the original bytes first, then base64-encode each part. Do not split one full base64 string into substrings.";
32
- var MULTIPART_PART_TOO_SMALL_ERROR = `Multipart upload parts must be at least 5MiB except the final part.`;
33
- var getRawBase64 = (value) => {
34
- const markerIndex = value.indexOf(";base64,");
35
- if (markerIndex === -1)
36
- return value;
37
- return value.slice(markerIndex + 8);
38
- };
39
- var validateBase64PayloadString = (payload, options) => {
40
- const raw = getRawBase64(payload.base64).replace(/\s/g, "");
41
- if (options?.multipart && raw.length % 4 !== 0)
42
- return {
43
- ok: false,
44
- error: BASE64_PART_BOUNDARY_ERROR
45
- };
46
- return { ok: true };
47
- };
48
- var assetToData = (payload) => {
49
- if ("plainText" in payload && payload.plainText !== undefined)
50
- return new TextEncoder().encode(payload.plainText);
51
- if ("data" in payload && payload.data)
52
- return payload.data;
53
- if ("buffer" in payload) {
54
- if (payload.buffer instanceof ArrayBuffer)
55
- return payload.buffer;
56
- return bufferInputToBytes(payload.buffer);
57
- }
58
- if (payload.uint8Array !== undefined)
59
- return Uint8Array.from(payload.uint8Array);
60
- if (payload.base64 === undefined)
61
- throw new Error("Invalid asset payload");
62
- const raw = getRawBase64(payload.base64);
63
- if (typeof Buffer !== "undefined")
64
- return Uint8Array.from(Buffer.from(raw, "base64"));
65
- const binary = atob(raw);
66
- return Uint8Array.from(binary, (char) => char.charCodeAt(0));
67
- };
68
- var getAssetPayloadByteLength = (payload) => {
69
- if ("plainText" in payload && payload.plainText !== undefined)
70
- return new TextEncoder().encode(payload.plainText).byteLength;
71
- if ("data" in payload && payload.data) {
72
- if (payload.data instanceof Blob)
73
- return payload.data.size;
74
- if (payload.data instanceof Response) {
75
- const contentLength = payload.data.headers.get("content-length");
76
- return contentLength ? Number(contentLength) : undefined;
77
- }
78
- return;
79
- }
80
- if ("buffer" in payload && payload.buffer)
81
- return payload.buffer.byteLength;
82
- if (payload.uint8Array !== undefined) {
83
- if (Array.isArray(payload.uint8Array))
84
- return payload.uint8Array.length;
85
- return payload.uint8Array.byteLength;
86
- }
87
- if (payload.base64 === undefined)
88
- return;
89
- const raw = getRawBase64(payload.base64).replace(/\s/g, "");
90
- const padding = raw.endsWith("==") ? 2 : raw.endsWith("=") ? 1 : 0;
91
- return Math.max(0, Math.floor(raw.length * 3 / 4) - padding);
92
- };
93
- var validateAssetPayload = (payload, options) => {
94
- if ("base64" in payload && payload.base64 !== undefined) {
95
- const validation = validateBase64PayloadString(payload, options);
96
- if (!validation.ok)
97
- return {
98
- ok: false,
99
- error: validation.error
100
- };
101
- }
102
- const byteLength = getAssetPayloadByteLength(payload);
103
- if (options?.multipart && !options.isFinal && byteLength !== undefined && byteLength < 5242880)
104
- return {
105
- ok: false,
106
- error: MULTIPART_PART_TOO_SMALL_ERROR
107
- };
108
- return { ok: true };
109
- };
110
-
111
- // src/contract/Media.js
112
- var MAX_MEDIA_UPLOAD_BYTES = 52428800;
113
-
114
- // src/contract/ModerationContextLimits-BIMUlk2e.js
115
- var countModerationContextCharacters = (text) => {
116
- let count = 0;
117
- for (const _ of text)
118
- count++;
119
- return count;
120
- };
121
- var selectModerationContextItems = (items) => {
122
- const selected = [];
123
- let characters = 0;
124
- for (let index = items.length - 1;index >= 0; index--) {
125
- if (selected.length === 5)
126
- break;
127
- const item = items[index];
128
- const length = countModerationContextCharacters(item.text);
129
- if (selected.length && characters + length > 2000)
130
- break;
131
- selected.unshift(item);
132
- characters += length;
133
- }
134
- return selected;
135
- };
136
- // src/contract/SharedConstants-CrqW8Uco.js
137
- var IMPERSONATION_COOKIE_NAME = "CL_impersonation";
138
- var DAY_MS = 86400000;
139
- var YEAR_MS = 365 * DAY_MS;
140
- var FIRST_PARTY_COOKIES = {
141
- ACCEPTED_COOKIES_VERSION: {
142
- name: "CL_acceptedCookiesVersion",
143
- description: "Records your cookie choice: the version of this cookie list you answered and whether you allowed functional and analytics cookies",
144
- expirationDescription: "1 year",
145
- expirationMs: YEAR_MS,
146
- type: "essential",
147
- providerName: "CalmLens"
148
- },
149
- EVER_LOGGED_IN: {
150
- name: "CL_everLoggedIn",
151
- description: "Remembers which sign-in method you last used on this device so the sign-in page can suggest it",
152
- expirationDescription: "10 years",
153
- type: "functional",
154
- providerName: "CalmLens"
155
- },
156
- ID_TOKEN: {
157
- name: "CL_idToken",
158
- description: "Authentication token that keeps you signed in (HttpOnly)",
159
- expirationDescription: "When the token expires (about 1 hour); renewed while you are signed in",
160
- type: "essential",
161
- providerName: "CalmLens"
162
- },
163
- ID_TOKEN_EXPIRES_AT: {
164
- name: "CL_idTokenExpiresAt",
165
- description: "When the current authentication token expires, so it can be renewed in time",
166
- expirationDescription: "10 years, or until you sign out",
167
- type: "essential",
168
- providerName: "CalmLens"
169
- },
170
- REFRESH_TOKEN: {
171
- name: "CL_refreshToken",
172
- description: "Token used to renew your sign-in without asking for your password again (HttpOnly)",
173
- expirationDescription: "10 years, or until you sign out",
174
- type: "essential",
175
- providerName: "CalmLens"
176
- },
177
- LOGGED_IN: {
178
- name: "CL_loggedIn",
179
- description: "Indicates that you are signed in, so pages can show the signed-in view",
180
- expirationDescription: "10 years, or until you sign out",
181
- type: "essential",
182
- providerName: "CalmLens"
183
- },
184
- IMPERSONATION: {
185
- name: IMPERSONATION_COOKIE_NAME,
186
- description: "Staff support access only: lets an authorised CalmLens staff member view the service as a specific user for support, security, safety or legal reasons. Only honoured for staff accounts and never set for other users",
187
- expirationDescription: "Session",
188
- type: "essential",
189
- providerName: "CalmLens"
190
- },
191
- MAINTENANCE_BYPASS: {
192
- name: "CL_maintenanceBypass",
193
- description: "Staff only: allows authorised staff to use the site while it is in maintenance mode (HttpOnly)",
194
- expirationDescription: "1 hour",
195
- expirationMs: 3600000,
196
- type: "essential",
197
- providerName: "CalmLens"
198
- },
199
- WAITLIST_BYPASS: {
200
- name: "CL_waitlistBypass",
201
- description: "Staff only: allows authorised staff to use the site while access is limited to the waitlist (HttpOnly)",
202
- expirationDescription: "1 hour",
203
- expirationMs: 3600000,
204
- type: "essential",
205
- providerName: "CalmLens"
206
- },
207
- SIGN_IN_CODE: {
208
- name: "CL_signInCode",
209
- description: "Records that you entered the sign-in code while access is limited to the waitlist, so you can sign in (HttpOnly)",
210
- expirationDescription: "30 days",
211
- expirationMs: 30 * DAY_MS,
212
- type: "essential",
213
- providerName: "CalmLens"
214
- },
215
- SIGN_IN_CODE_ACCEPTED: {
216
- name: "CL_signInCodeAccepted",
217
- description: "Indicates that you entered the sign-in code, so the sign-in page shows the sign-in options",
218
- expirationDescription: "30 days",
219
- expirationMs: 30 * DAY_MS,
220
- type: "essential",
221
- providerName: "CalmLens"
222
- },
223
- PRE_RENDERED_WIDTH: {
224
- name: "CL_preRenderedWidth",
225
- description: "Your browser's viewport width, so pages are rendered with the right layout for your screen",
226
- expirationDescription: "30 days",
227
- expirationMs: 30 * DAY_MS,
228
- type: "essential",
229
- providerName: "CalmLens"
230
- },
231
- SELECTED_PROJECT_ID: {
232
- name: "CL_selectedProjectId",
233
- description: "Remembers the project you last selected in the portal",
234
- expirationDescription: "1 year",
235
- expirationMs: YEAR_MS,
236
- type: "functional",
237
- providerName: "CalmLens"
238
- },
239
- SELECTED_ORGANISATION_ID: {
240
- name: "CL_selectedOrganisationId",
241
- description: "Remembers the organisation you last selected in the portal",
242
- expirationDescription: "1 year",
243
- expirationMs: YEAR_MS,
244
- type: "functional",
245
- providerName: "CalmLens"
246
- },
247
- ASSET_DASHBOARD_STATE: {
248
- name: "CL_assetDashboardState",
249
- description: "Remembers your asset dashboard view (view mode, filters, sorting and folder)",
250
- expirationDescription: "1 year",
251
- expirationMs: YEAR_MS,
252
- type: "functional",
253
- providerName: "CalmLens"
254
- },
255
- ASSET_VIEW: {
256
- name: "CL_assetView",
257
- description: "Remembers whether you chose the grid or table view for an asset's sub-assets (one cookie per asset, named CL_assetView_<assetId>)",
258
- expirationDescription: "30 days",
259
- expirationMs: 30 * DAY_MS,
260
- type: "functional",
261
- providerName: "CalmLens",
262
- isPrefix: true
263
- },
264
- PORTAL_GUIDANCE_HIDDEN: {
265
- name: "CL_portalGuidanceHidden",
266
- description: "Remembers whether you hid next-step tips for a project",
267
- expirationDescription: "1 year",
268
- expirationMs: YEAR_MS,
269
- type: "functional",
270
- providerName: "CalmLens",
271
- isPrefix: true
272
- },
273
- PORTAL_LAYOUT_SPLIT_PANE: {
274
- name: "CL_portalLayoutSplitPane",
275
- description: "Remembers the width you set for the portal sidebar",
276
- expirationDescription: "1 year",
277
- expirationMs: YEAR_MS,
278
- type: "functional",
279
- providerName: "CalmLens"
280
- },
281
- DOCS_UI_LIBRARY: {
282
- name: "CL_docsUiLibrary",
283
- description: "Remembers the UI library you selected for documentation examples",
284
- expirationDescription: "1 year",
285
- expirationMs: YEAR_MS,
286
- type: "functional",
287
- providerName: "CalmLens"
288
- },
289
- DOCS_LANGUAGE: {
290
- name: "CL_docsLanguage",
291
- description: "Remembers the programming language you selected for documentation examples",
292
- expirationDescription: "1 year",
293
- expirationMs: YEAR_MS,
294
- type: "functional",
295
- providerName: "CalmLens"
296
- },
297
- SEARCH_SDK_LANGUAGE: {
298
- name: "CL_searchSdkLanguage",
299
- description: "Remembers the SDK you chose to filter documentation search results by",
300
- expirationDescription: "1 year",
301
- expirationMs: YEAR_MS,
302
- type: "functional",
303
- providerName: "CalmLens"
304
- }
305
- };
306
- var THIRD_PARTY_COOKIES = {
307
- GOOGLE_ANALYTICS: {
308
- name: "_ga",
309
- description: "Google Analytics distinguishes visitors and maintains session state, only with analytics consent",
310
- expirationDescription: "2 years",
311
- type: "analytics",
312
- providerName: "Google Analytics",
313
- isPrefix: true
314
- },
315
- GOOGLE_AD_CLICK: {
316
- name: "_gcl",
317
- description: "Links consented ad clicks to signups; no personalised advertising",
318
- expirationDescription: "Up to 90 days",
319
- type: "marketing",
320
- providerName: "Google",
321
- isPrefix: true
322
- },
323
- GOOGLE_CAMPAIGN: {
324
- name: "_gac",
325
- description: "Stores consented campaign attribution",
326
- expirationDescription: "Up to 90 days",
327
- type: "marketing",
328
- providerName: "Google",
329
- isPrefix: true
330
- }
331
- };
332
- [...Object.values(FIRST_PARTY_COOKIES), ...Object.values(THIRD_PARTY_COOKIES)];
333
- var MAX_IMAGE_UPLOAD_BYTES = /* @__PURE__ */ (() => 20971520)();
334
- var MAX_DIRECT_IMAGE_UPLOAD_BYTES = /* @__PURE__ */ (() => 10485760)();
335
- var MAX_NON_IMAGE_UPLOAD_MB = 5000;
336
- var MAX_NON_IMAGE_UPLOAD_BYTES = /* @__PURE__ */ (() => MAX_NON_IMAGE_UPLOAD_MB * 1024 * 1024)();
337
- var REJECTED_UPLOAD_MIME_TYPE_SET = /* @__PURE__ */ new Set([
338
- "application/octet-stream",
339
- "multipart/form-data",
340
- "multipart/mixed",
341
- "multipart/alternative",
342
- "multipart/related",
343
- "multipart/signed",
344
- "multipart/encrypted"
345
- ]);
346
- var normalizeUploadMimeType = (mimeType) => mimeType.toLowerCase().split(";")[0]?.trim() || mimeType.toLowerCase().trim();
347
- var isRejectedUploadMimeType = (mimeType) => REJECTED_UPLOAD_MIME_TYPE_SET.has(normalizeUploadMimeType(mimeType));
348
- var getRejectedUploadMimeTypeError = (mimeType) => `${normalizeUploadMimeType(mimeType)} is not a valid upload file type. Uploads must use a concrete file MIME type that CalmLens can store and process, such as image/png, image/jpeg, application/pdf, or text/plain.`;
349
- var DOMAIN = "calmlens.com";
350
25
  // src/client/CalmLensErrorCodes.ts
351
26
  var API_ERROR_CODES = {
352
- INVALID_VIEWER_CLAIMS: "viewer/invalid-claims",
27
+ INVALID_VIEWER_CLAIMS: "viewer-claims/invalid",
353
28
  AGE_CONFIRMATION_REQUIRED: "viewer/age-confirmation-required",
354
- INVALID_VIEWER_REGION: "viewer/invalid-region",
29
+ INVALID_VIEWER_REGION: "viewer-region/invalid",
355
30
  VIEWER_REGION_REQUIRED: "viewer/region-required",
356
31
  REGIONAL_EVIDENCE_REQUIRED: "asset/regional-evidence-required",
357
32
  SIGNED_URL_EXPIRED: "signed-url/expired",
358
33
  SIGNED_URL_INVALID: "signed-url/invalid",
34
+ SIGNED_URL_ORIGINAL_NOT_GRANTED: "signed-url/original-not-granted",
35
+ INVALID_REQUEST: "validation/invalid-request",
359
36
  INVALID_TYPE: "validation/invalid-type",
360
37
  TOO_SMALL: "validation/too-small",
361
38
  TOO_BIG: "validation/too-big",
362
39
  INVALID_FORMAT: "validation/invalid-format",
363
40
  INVALID_VALUE: "validation/invalid-value",
364
41
  UNKNOWN_FIELD: "validation/unknown-field",
365
- UNSUPPORTED_CONTENT_TYPE: "validation/unsupported-content-type",
366
- INVALID_FILTER: "validation/invalid-filter",
367
- INVALID_ORDERING_FIELD: "validation/invalid-ordering-field",
368
- ROUTE_NOT_FOUND: "misc/route-not-found",
369
- INTERNAL_ERROR: "misc/internal-error",
42
+ UNSUPPORTED_CONTENT_TYPE: "request/unsupported-content-type",
43
+ INVALID_FILTER: "filter/invalid",
44
+ UNSUPPORTED_ORDERING_FIELD: "ordering/unsupported-field",
45
+ ROUTE_NOT_FOUND: "request/route-not-found",
46
+ INTERNAL_ERROR: "server/internal-error",
370
47
  UNAUTHENTICATED: "auth/unauthenticated",
371
- TOKEN_EXPIRED: "auth/token-expired",
372
- INVALID_TOKEN: "auth/invalid-token",
48
+ TOKEN_EXPIRED: "session-token/expired",
49
+ INVALID_TOKEN: "session-token/invalid",
373
50
  SEARCH_UNAVAILABLE: "search/unavailable",
374
- INVALID_TRANSFORM: "asset/invalid-transform",
375
- INVALID_TRANSFORM_OPTIONS: "asset/invalid-transform-options",
376
- REMOTE_URL_REDIRECT_LIMIT: "asset/remote-url-redirect-limit",
377
- COPYRIGHT_CONTENT_HELD: "copyright/content-held",
378
- DOWNLOAD_PERMISSION_REQUIRED: "asset/api-key-missing-permission",
379
- INVALID_CURSOR: "validation/invalid-cursor",
380
- MISSING_TOKEN: "auth/missing-token",
381
- INVALID_API_KEY: "auth/invalid-api-key",
382
- API_KEY_PROJECT_MISMATCH: "auth/project-mismatch",
383
- API_KEY_NOT_ACCEPTED: "auth/api-key-not-accepted",
51
+ INVALID_TRANSFORM: "transform/invalid",
52
+ INVALID_TRANSFORM_OPTIONS: "transform-options/invalid",
53
+ REMOTE_URL_TOO_MANY_REDIRECTS: "remote-url/too-many-redirects",
54
+ INVALID_CURSOR: "cursor/invalid",
55
+ MISSING_API_KEY: "api-key/missing",
56
+ INVALID_API_KEY: "api-key/invalid",
57
+ API_KEY_PROJECT_MISMATCH: "api-key/project-mismatch",
58
+ API_KEY_NOT_ACCEPTED: "api-key/not-accepted",
384
59
  PERMISSION_DENIED: "auth/permission-denied",
385
- FILE_TOO_LARGE: "upload/file-too-large",
386
- MULTIPART_IMAGE_TOO_LARGE: "upload/multipart-image-too-large",
387
- IMAGE_EXCEEDED_MAX_DIMENSIONS: "upload/image-exceeded-max-dimensions",
388
- IMAGE_INVALID_INPUT: "image/invalid-input",
389
- IMAGE_UNSUPPORTED_FORMAT: "image/unsupported-format",
390
- IMAGE_INPUT_LIMIT: "image/input-limit",
391
- UPLOAD_LIMIT_EXCEEDED: "upload/limit-exceeded",
392
- SPEND_LIMIT_REACHED: "upload/spend-limit-reached",
393
- INVALID_UPLOAD_MIME_TYPE: "upload/invalid-mime-type",
394
- INVALID_UPLOAD_PAYLOAD: "upload/invalid-payload",
60
+ UPLOAD_TOO_LARGE: "upload/too-large",
61
+ DOCUMENT_TOO_MANY_ITEMS: "document/too-many-items",
62
+ INVALID_IMAGE: "image/invalid",
63
+ IMAGE_TOO_LARGE: "image/too-large",
64
+ FREE_UPLOADS_EXHAUSTED: "usage/free-uploads-exhausted",
65
+ UPLOADS_PAUSED: "usage/uploads-paused",
66
+ UNSUPPORTED_UPLOAD_TYPE: "upload/unsupported-type",
67
+ INVALID_UPLOAD_PAYLOAD: "upload-payload/invalid",
395
68
  USE_UPLOAD_PART: "upload/use-upload-part",
396
69
  UPLOAD_NOT_OPEN: "upload/not-open",
397
- INVALID_UPLOAD_PART_NUMBER: "upload/invalid-part-number",
70
+ INVALID_UPLOAD_PART_NUMBER: "upload-part/invalid-number",
398
71
  UPLOAD_MISSING: "upload/missing",
399
72
  UPLOAD_SIZE_MISMATCH: "upload/size-mismatch",
400
73
  INVALID_IDEMPOTENCY_KEY: "idempotency/invalid-key",
401
74
  IDEMPOTENCY_KEY_REUSED: "idempotency/key-reused",
402
75
  IDEMPOTENT_REQUEST_IN_PROGRESS: "idempotency/request-in-progress",
76
+ NO_RENDERED_VERSION: "asset/no-rendered-version",
403
77
  ASSET_NOT_FOUND: "asset/not-found",
404
78
  PROJECT_NOT_FOUND: "project/not-found",
79
+ ASSET_CHILD_NOT_DELETABLE: "asset/child-not-deletable",
405
80
  ASSET_REVIEW_CHANGED: "asset/review-changed",
406
81
  ASSET_REVIEW_NOTE_REQUIRED: "asset/review-note-required",
407
82
  ASSET_UPDATE_FAILED: "asset/update-failed",
408
- ASSET_SAFETY_HELD: "asset/safety-held",
83
+ ASSET_HELD: "asset/held",
409
84
  ASSET_PROCESSING: "asset/processing",
410
85
  ASSET_DECISION_NOT_ALLOWED: "asset/decision-not-allowed",
411
86
  ASSET_DECISION_UNCHANGED: "asset/decision-unchanged",
@@ -415,18 +90,19 @@ var API_ERROR_CODES = {
415
90
  ASSET_NOT_DECIDED: "asset/not-decided",
416
91
  ASSET_POLICY_CHANGED: "asset/policy-changed",
417
92
  ASSET_REVIEWED: "asset/reviewed",
418
- SUPPORT_TICKET_NOT_FOUND: "support/ticket-not-found",
93
+ SUPPORT_TICKET_NOT_FOUND: "support-ticket/not-found",
419
94
  DUPLICATE_EXTERNAL_ID: "asset/duplicate-external-id",
420
95
  FOLDER_NOT_FOUND: "folder/not-found",
421
96
  DUPLICATE_FOLDER_NAME: "folder/duplicate-name",
422
97
  FOLDER_NOT_EMPTY: "folder/not-empty",
423
98
  FOLDER_PARENT_CYCLE: "folder/parent-cycle",
424
- LENS_VERSION_CONFLICT: "lens/version-conflict",
99
+ LENS_NOT_FOUND: "lens/not-found",
100
+ LENS_IDENTIFIER_TAKEN: "lens/identifier-taken",
425
101
  LENS_IDENTIFIER_RESERVED: "lens/identifier-reserved",
426
102
  HASH_LIST_NOT_FOUND: "hash-list/not-found",
427
- HASH_LIST_ENTRY_NOT_FOUND: "hash-list/entry-not-found",
103
+ HASH_LIST_ENTRY_NOT_FOUND: "hash-list-entry/not-found",
428
104
  HASH_LIST_LIMIT_REACHED: "hash-list/limit-reached",
429
- HASH_LIST_ENTRY_LIMIT_REACHED: "hash-list/entry-limit-reached",
105
+ HASH_LIST_ENTRY_LIMIT_REACHED: "hash-list-entry/limit-reached",
430
106
  HASH_LIST_ASSET_NOT_HASHED: "hash-list/asset-not-hashed",
431
107
  POLICY_NOT_FOUND: "policy/not-found",
432
108
  POLICY_REVISION_CONFLICT: "policy/revision-conflict",
@@ -440,18 +116,16 @@ var API_ERROR_CODES = {
440
116
  UPLOAD_PRESET_NOT_FOUND: "upload-preset/not-found",
441
117
  UPLOAD_PRESET_DISABLED: "upload-preset/disabled",
442
118
  UPLOAD_PRESET_TOKEN_REQUIRED: "upload-preset/token-required",
443
- REMOTE_URL_NOT_ALLOWED: "upload/remote-url-not-allowed",
444
- WEBSITE_RATE_LIMIT_EXCEEDED: "upload/website-rate-limit-exceeded",
445
- UPLOAD_PRESET_CONTENT_TYPE_NOT_ALLOWED: "upload-preset/content-type-not-allowed",
446
- UPLOAD_PRESET_TOO_LARGE: "upload-preset/too-large",
119
+ REMOTE_URL_NOT_ALLOWED: "remote-url/not-allowed",
120
+ WEBSITE_RATE_LIMIT_REACHED: "upload/website-rate-limit-reached",
447
121
  UPLOAD_PRESET_DAILY_LIMIT_REACHED: "upload-preset/daily-limit-reached",
448
122
  UPLOAD_PRESET_ORIGIN_NOT_ALLOWED: "upload-preset/origin-not-allowed",
449
123
  UPLOAD_PRESET_FIELD_NOT_ALLOWED: "upload-preset/field-not-allowed",
450
124
  UPLOAD_TOKEN_INVALID: "upload-token/invalid",
451
125
  UPLOAD_TOKEN_EXPIRED: "upload-token/expired",
452
126
  UPLOAD_TOKEN_USED: "upload-token/used",
453
- INVALID_REMOTE_URL: "asset/invalid-remote-url",
454
- REMOTE_URL_UNAVAILABLE: "asset/remote-url-unavailable",
127
+ INVALID_REMOTE_URL: "remote-url/invalid",
128
+ REMOTE_URL_UNAVAILABLE: "remote-url/unavailable",
455
129
  APPEAL_NOT_FOUND: "appeal/not-found",
456
130
  APPEAL_JUDGMENT_NOT_FOUND: "appeal/judgment-not-found",
457
131
  APPEAL_ASSET_NOT_FOUND: "appeal/asset-not-found",
@@ -459,7 +133,6 @@ var API_ERROR_CODES = {
459
133
  APPEAL_ALREADY_REVIEWED: "appeal/already-reviewed",
460
134
  APPEAL_DECISION_CHANGED: "appeal/decision-changed",
461
135
  APPEAL_INVALID_ACTION: "appeal/invalid-action",
462
- APPEAL_SAFETY_HELD: "appeal/safety-held",
463
136
  APPEAL_CONTENT_UNAVAILABLE: "appeal/content-unavailable"
464
137
  };
465
138
 
@@ -479,7 +152,7 @@ var SDK_ERROR_CODES = {
479
152
  };
480
153
  var CALMLENS_ERROR_CODES = { ...API_ERROR_CODES, ...SDK_ERROR_CODES };
481
154
  var BRAND = Symbol.for("calmlens.sdk.CalmLensError");
482
- var RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
155
+ var RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504]);
483
156
  var RETRYABLE_CODES = new Set([
484
157
  SDK_ERROR_CODES.TRANSPORT_ERROR,
485
158
  SDK_ERROR_CODES.TIMEOUT,
@@ -546,7 +219,7 @@ var isReactNativeRuntime = () => globalThis.navigator?.product === "ReactNative"
546
219
  var RETRY_BASE_DELAY_MS = 500;
547
220
  var RETRY_MAX_DELAY_MS = 8000;
548
221
  var RETRY_AFTER_MAX_MS = 60000;
549
- var RETRYABLE_STATUSES2 = new Set([429, 502, 503, 504]);
222
+ var RETRYABLE_STATUSES2 = new Set([429, 500, 502, 503, 504]);
550
223
  var timeoutReason = () => {
551
224
  const reason = new Error("The operation timed out.");
552
225
  reason.name = "TimeoutError";
@@ -762,83 +435,482 @@ class CalmLensTransport {
762
435
  await this.sleep(getRetryDelayMs(attemptNumber), this.settings.signal);
763
436
  continue;
764
437
  }
765
- throw failure;
438
+ throw failure;
439
+ }
440
+ if (request.deadline === "headers")
441
+ attempt.clearDeadline();
442
+ if (response.ok)
443
+ return { response, attempt };
444
+ if (allowHttpErrors) {
445
+ const retryAfter = parseRetryAfter(response.headers.get("retry-after"));
446
+ const delayMs = retryAfter !== undefined ? retryAfter * 1000 : getRetryDelayMs(attemptNumber);
447
+ if (!canRetryAgain || !RETRYABLE_STATUSES2.has(response.status) || delayMs > RETRY_AFTER_MAX_MS) {
448
+ return { response, attempt };
449
+ }
450
+ attempt.release();
451
+ await response.body?.cancel().catch(() => {});
452
+ await this.sleep(delayMs, this.settings.signal);
453
+ continue;
454
+ }
455
+ let error;
456
+ try {
457
+ error = toHttpError(response, await readBody(response, this.settings.maxResponseBytes));
458
+ } catch (cause) {
459
+ error = toFailure(cause, attempt);
460
+ } finally {
461
+ attempt.release();
462
+ }
463
+ const retryDelayMs = error.retryAfter !== undefined ? error.retryAfter * 1000 : getRetryDelayMs(attemptNumber);
464
+ const shouldRetry = canRetryAgain && retryDelayMs <= RETRY_AFTER_MAX_MS && error.isRetryable();
465
+ if (shouldRetry) {
466
+ await this.sleep(retryDelayMs, this.settings.signal);
467
+ continue;
468
+ }
469
+ throw error;
470
+ }
471
+ }
472
+ async json(request) {
473
+ const { response, attempt } = await this.send(request);
474
+ try {
475
+ const bytes = await readBody(response, this.settings.maxResponseBytes);
476
+ if (bytes.byteLength === 0 && (response.status === 204 || request.method === "DELETE")) {
477
+ return;
478
+ }
479
+ try {
480
+ return JSON.parse(new TextDecoder().decode(bytes));
481
+ } catch (cause) {
482
+ throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
483
+ message: `Invalid JSON response (HTTP ${response.status})`,
484
+ ...responseInfo(response),
485
+ cause
486
+ });
487
+ }
488
+ } catch (cause) {
489
+ throw toFailure(cause, attempt);
490
+ } finally {
491
+ attempt.release();
492
+ }
493
+ }
494
+ }
495
+
496
+ // src/contract/SharedConstants-DxUCZwLZ.js
497
+ var IMPERSONATION_COOKIE_NAME = "CL_impersonation";
498
+ var DAY_MS = 86400000;
499
+ var YEAR_MS = 365 * DAY_MS;
500
+ var FIRST_PARTY_COOKIES = {
501
+ ACCEPTED_COOKIES_VERSION: {
502
+ name: "CL_acceptedCookiesVersion",
503
+ description: "Records your cookie choice: the version of this cookie list you answered and whether you allowed functional and analytics cookies",
504
+ expirationDescription: "1 year",
505
+ expirationMs: YEAR_MS,
506
+ type: "essential",
507
+ providerName: "CalmLens"
508
+ },
509
+ EVER_LOGGED_IN: {
510
+ name: "CL_everLoggedIn",
511
+ description: "Remembers which sign-in method you last used on this device so the sign-in page can suggest it",
512
+ expirationDescription: "10 years",
513
+ type: "functional",
514
+ providerName: "CalmLens"
515
+ },
516
+ ID_TOKEN: {
517
+ name: "CL_idToken",
518
+ description: "Authentication token that keeps you signed in (HttpOnly)",
519
+ expirationDescription: "When the token expires (about 1 hour); renewed while you are signed in",
520
+ type: "essential",
521
+ providerName: "CalmLens"
522
+ },
523
+ ID_TOKEN_EXPIRES_AT: {
524
+ name: "CL_idTokenExpiresAt",
525
+ description: "When the current authentication token expires, so it can be renewed in time",
526
+ expirationDescription: "10 years, or until you sign out",
527
+ type: "essential",
528
+ providerName: "CalmLens"
529
+ },
530
+ REFRESH_TOKEN: {
531
+ name: "CL_refreshToken",
532
+ description: "Token used to renew your sign-in without asking for your password again (HttpOnly)",
533
+ expirationDescription: "10 years, or until you sign out",
534
+ type: "essential",
535
+ providerName: "CalmLens"
536
+ },
537
+ LOGGED_IN: {
538
+ name: "CL_loggedIn",
539
+ description: "Indicates that you are signed in, so pages can show the signed-in view",
540
+ expirationDescription: "10 years, or until you sign out",
541
+ type: "essential",
542
+ providerName: "CalmLens"
543
+ },
544
+ IMPERSONATION: {
545
+ name: IMPERSONATION_COOKIE_NAME,
546
+ description: "Staff support access only: lets an authorised CalmLens staff member view the service as a specific user for support, security, safety or legal reasons. Only honoured for staff accounts and never set for other users",
547
+ expirationDescription: "Session",
548
+ type: "essential",
549
+ providerName: "CalmLens"
550
+ },
551
+ MAINTENANCE_BYPASS: {
552
+ name: "CL_maintenanceBypass",
553
+ description: "Staff only: allows authorised staff to use the site while it is in maintenance mode (HttpOnly)",
554
+ expirationDescription: "1 hour",
555
+ expirationMs: 3600000,
556
+ type: "essential",
557
+ providerName: "CalmLens"
558
+ },
559
+ WAITLIST_BYPASS: {
560
+ name: "CL_waitlistBypass",
561
+ description: "Staff only: allows authorised staff to use the site while access is limited to the waitlist (HttpOnly)",
562
+ expirationDescription: "1 hour",
563
+ expirationMs: 3600000,
564
+ type: "essential",
565
+ providerName: "CalmLens"
566
+ },
567
+ SIGN_IN_CODE: {
568
+ name: "CL_signInCode",
569
+ description: "Records that you entered the sign-in code while access is limited to the waitlist, so you can sign in (HttpOnly)",
570
+ expirationDescription: "30 days",
571
+ expirationMs: 30 * DAY_MS,
572
+ type: "essential",
573
+ providerName: "CalmLens"
574
+ },
575
+ SIGN_IN_CODE_ACCEPTED: {
576
+ name: "CL_signInCodeAccepted",
577
+ description: "Indicates that you entered the sign-in code, so the sign-in page shows the sign-in options",
578
+ expirationDescription: "30 days",
579
+ expirationMs: 30 * DAY_MS,
580
+ type: "essential",
581
+ providerName: "CalmLens"
582
+ },
583
+ PRE_RENDERED_WIDTH: {
584
+ name: "CL_preRenderedWidth",
585
+ description: "Your browser's viewport width, so pages are rendered with the right layout for your screen",
586
+ expirationDescription: "30 days",
587
+ expirationMs: 30 * DAY_MS,
588
+ type: "essential",
589
+ providerName: "CalmLens"
590
+ },
591
+ SELECTED_PROJECT_ID: {
592
+ name: "CL_selectedProjectId",
593
+ description: "Remembers the project you last selected in the portal",
594
+ expirationDescription: "1 year",
595
+ expirationMs: YEAR_MS,
596
+ type: "functional",
597
+ providerName: "CalmLens"
598
+ },
599
+ SELECTED_ORGANISATION_ID: {
600
+ name: "CL_selectedOrganisationId",
601
+ description: "Remembers the organisation you last selected in the portal",
602
+ expirationDescription: "1 year",
603
+ expirationMs: YEAR_MS,
604
+ type: "functional",
605
+ providerName: "CalmLens"
606
+ },
607
+ ASSET_DASHBOARD_STATE: {
608
+ name: "CL_assetDashboardState",
609
+ description: "Remembers your asset dashboard view (view mode, filters, sorting and folder)",
610
+ expirationDescription: "1 year",
611
+ expirationMs: YEAR_MS,
612
+ type: "functional",
613
+ providerName: "CalmLens"
614
+ },
615
+ ASSET_VIEW: {
616
+ name: "CL_assetView",
617
+ description: "Remembers whether you chose the grid or table view for an asset's sub-assets (one cookie per asset, named CL_assetView_<assetId>)",
618
+ expirationDescription: "30 days",
619
+ expirationMs: 30 * DAY_MS,
620
+ type: "functional",
621
+ providerName: "CalmLens",
622
+ isPrefix: true
623
+ },
624
+ PORTAL_GUIDANCE_HIDDEN: {
625
+ name: "CL_portalGuidanceHidden",
626
+ description: "Remembers whether you hid next-step tips for a project",
627
+ expirationDescription: "1 year",
628
+ expirationMs: YEAR_MS,
629
+ type: "functional",
630
+ providerName: "CalmLens",
631
+ isPrefix: true
632
+ },
633
+ PORTAL_LAYOUT_SPLIT_PANE: {
634
+ name: "CL_portalLayoutSplitPane",
635
+ description: "Remembers the width you set for the portal sidebar",
636
+ expirationDescription: "1 year",
637
+ expirationMs: YEAR_MS,
638
+ type: "functional",
639
+ providerName: "CalmLens"
640
+ },
641
+ DOCS_UI_LIBRARY: {
642
+ name: "CL_docsUiLibrary",
643
+ description: "Remembers the UI library you selected for documentation examples",
644
+ expirationDescription: "1 year",
645
+ expirationMs: YEAR_MS,
646
+ type: "functional",
647
+ providerName: "CalmLens"
648
+ },
649
+ DOCS_LANGUAGE: {
650
+ name: "CL_docsLanguage",
651
+ description: "Remembers the programming language you selected for documentation examples",
652
+ expirationDescription: "1 year",
653
+ expirationMs: YEAR_MS,
654
+ type: "functional",
655
+ providerName: "CalmLens"
656
+ },
657
+ SEARCH_SDK_LANGUAGE: {
658
+ name: "CL_searchSdkLanguage",
659
+ description: "Remembers the SDK you chose to filter documentation search results by",
660
+ expirationDescription: "1 year",
661
+ expirationMs: YEAR_MS,
662
+ type: "functional",
663
+ providerName: "CalmLens"
664
+ }
665
+ };
666
+ var THIRD_PARTY_COOKIES = {
667
+ GOOGLE_ANALYTICS: {
668
+ name: "_ga",
669
+ description: "Google Analytics distinguishes visitors and maintains session state, only with analytics consent",
670
+ expirationDescription: "2 years",
671
+ type: "analytics",
672
+ providerName: "Google Analytics",
673
+ isPrefix: true
674
+ },
675
+ GOOGLE_AD_CLICK: {
676
+ name: "_gcl",
677
+ description: "Links consented ad clicks to signups; no personalised advertising",
678
+ expirationDescription: "Up to 90 days",
679
+ type: "marketing",
680
+ providerName: "Google",
681
+ isPrefix: true
682
+ },
683
+ GOOGLE_CAMPAIGN: {
684
+ name: "_gac",
685
+ description: "Stores consented campaign attribution",
686
+ expirationDescription: "Up to 90 days",
687
+ type: "marketing",
688
+ providerName: "Google",
689
+ isPrefix: true
690
+ }
691
+ };
692
+ [...Object.values(FIRST_PARTY_COOKIES), ...Object.values(THIRD_PARTY_COOKIES)];
693
+ var MAX_IMAGE_UPLOAD_BYTES = /* @__PURE__ */ (() => 20971520)();
694
+ var MAX_DIRECT_IMAGE_UPLOAD_BYTES = /* @__PURE__ */ (() => 10485760)();
695
+ var MAX_NON_IMAGE_UPLOAD_MB = 5000;
696
+ var MAX_NON_IMAGE_UPLOAD_BYTES = /* @__PURE__ */ (() => MAX_NON_IMAGE_UPLOAD_MB * 1024 * 1024)();
697
+ var normalizeUploadMimeType = (mimeType) => mimeType.toLowerCase().split(";")[0]?.trim() || mimeType.toLowerCase().trim();
698
+ var getRejectedUploadMimeTypeError = (mimeType) => `${normalizeUploadMimeType(mimeType)} is not a valid upload file type. Uploads must use a concrete file MIME type that CalmLens can store and process, such as image/png, image/jpeg, application/pdf, or text/plain.`;
699
+ var DOMAIN = "calmlens.com";
700
+ // src/client/CalmLensTransformSchema.ts
701
+ var TRANSFORM_OPTIONS_SCHEMA = {
702
+ type: "object",
703
+ properties: {
704
+ format: {
705
+ type: "string",
706
+ enum: ["jpg", "png", "webp", "avif", "gif"]
707
+ },
708
+ width: {
709
+ type: "integer",
710
+ minimum: 1,
711
+ maximum: 1e4
712
+ },
713
+ height: {
714
+ type: "integer",
715
+ minimum: 1,
716
+ maximum: 1e4
717
+ },
718
+ dpr: {
719
+ type: "number",
720
+ minimum: 1,
721
+ maximum: 3
722
+ },
723
+ anim: {
724
+ type: "boolean"
725
+ },
726
+ background: {
727
+ type: "string"
728
+ },
729
+ blur: {
730
+ type: "number"
731
+ },
732
+ redact: {
733
+ type: "object",
734
+ properties: {
735
+ text: {
736
+ type: "boolean"
737
+ },
738
+ personalInformation: {
739
+ type: "boolean"
740
+ },
741
+ faces: {
742
+ type: "boolean"
743
+ }
766
744
  }
767
- if (request.deadline === "headers")
768
- attempt.clearDeadline();
769
- if (response.ok)
770
- return { response, attempt };
771
- if (allowHttpErrors) {
772
- const retryAfter = parseRetryAfter(response.headers.get("retry-after"));
773
- const delayMs = retryAfter !== undefined ? retryAfter * 1000 : getRetryDelayMs(attemptNumber);
774
- if (!canRetryAgain || !RETRYABLE_STATUSES2.has(response.status) || delayMs > RETRY_AFTER_MAX_MS) {
775
- return { response, attempt };
745
+ },
746
+ border: {
747
+ type: "object",
748
+ properties: {
749
+ color: {
750
+ type: "string"
751
+ },
752
+ width: {
753
+ type: "number"
776
754
  }
777
- attempt.release();
778
- await response.body?.cancel().catch(() => {});
779
- await this.sleep(delayMs, this.settings.signal);
780
- continue;
781
- }
782
- let error;
783
- try {
784
- error = toHttpError(response, await readBody(response, this.settings.maxResponseBytes));
785
- } catch (cause) {
786
- error = toFailure(cause, attempt);
787
- } finally {
788
- attempt.release();
789
- }
790
- const retryDelayMs = error.retryAfter !== undefined ? error.retryAfter * 1000 : getRetryDelayMs(attemptNumber);
791
- const shouldRetry = canRetryAgain && retryDelayMs <= RETRY_AFTER_MAX_MS && error.isRetryable();
792
- if (shouldRetry) {
793
- await this.sleep(retryDelayMs, this.settings.signal);
794
- continue;
795
- }
796
- throw error;
797
- }
798
- }
799
- async json(request) {
800
- const { response, attempt } = await this.send(request);
801
- try {
802
- const bytes = await readBody(response, this.settings.maxResponseBytes);
803
- if (bytes.byteLength === 0 && (response.status === 204 || request.method === "DELETE")) {
804
- return;
805
- }
806
- try {
807
- return JSON.parse(new TextDecoder().decode(bytes));
808
- } catch (cause) {
809
- throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
810
- message: `Invalid JSON response (HTTP ${response.status})`,
811
- ...responseInfo(response),
812
- cause
813
- });
814
755
  }
815
- } catch (cause) {
816
- throw toFailure(cause, attempt);
817
- } finally {
818
- attempt.release();
756
+ },
757
+ brightness: {
758
+ type: "number"
759
+ },
760
+ contrast: {
761
+ type: "number"
762
+ },
763
+ quality: {
764
+ oneOf: [
765
+ {
766
+ type: "integer",
767
+ minimum: 1,
768
+ maximum: 100
769
+ },
770
+ {
771
+ type: "string",
772
+ enum: ["low", "medium", "high"]
773
+ }
774
+ ]
775
+ },
776
+ fit: {
777
+ type: "string",
778
+ enum: ["scale-down", "contain", "pad", "squeeze", "cover", "crop"]
779
+ },
780
+ flip: {
781
+ type: "string",
782
+ enum: ["h", "v", "hv"]
783
+ },
784
+ gamma: {
785
+ type: "number"
786
+ },
787
+ segment: {
788
+ type: "string",
789
+ enum: ["foreground"]
790
+ },
791
+ gravity: {
792
+ oneOf: [
793
+ {
794
+ type: "string",
795
+ enum: ["face", "left", "right", "top", "bottom", "center", "auto", "entropy"]
796
+ },
797
+ {
798
+ type: "object",
799
+ properties: {
800
+ mode: {
801
+ type: "string",
802
+ enum: ["remainder", "box-center"]
803
+ },
804
+ x: {
805
+ type: "number"
806
+ },
807
+ y: {
808
+ type: "number"
809
+ }
810
+ },
811
+ required: ["mode"]
812
+ }
813
+ ]
814
+ },
815
+ rotate: {
816
+ type: "integer",
817
+ enum: [0, 90, 180, 270]
818
+ },
819
+ saturation: {
820
+ type: "number"
821
+ },
822
+ sharpen: {
823
+ type: "number"
824
+ },
825
+ trim: {
826
+ oneOf: [
827
+ {
828
+ type: "string",
829
+ enum: ["border"]
830
+ },
831
+ {
832
+ type: "object",
833
+ properties: {
834
+ top: {
835
+ type: "number"
836
+ },
837
+ bottom: {
838
+ type: "number"
839
+ },
840
+ left: {
841
+ type: "number"
842
+ },
843
+ right: {
844
+ type: "number"
845
+ },
846
+ width: {
847
+ type: "number"
848
+ },
849
+ height: {
850
+ type: "number"
851
+ },
852
+ border: {
853
+ oneOf: [
854
+ {
855
+ type: "boolean"
856
+ },
857
+ {
858
+ type: "object",
859
+ properties: {
860
+ color: {
861
+ type: "string"
862
+ },
863
+ tolerance: {
864
+ type: "number"
865
+ },
866
+ keep: {
867
+ type: "number"
868
+ }
869
+ }
870
+ }
871
+ ]
872
+ }
873
+ }
874
+ }
875
+ ]
819
876
  }
820
877
  }
821
- }
822
-
823
- // src/client/CalmLensViewerClaims.ts
824
- var VIEWER_COUNTRIES = new Set("AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW".split(" "));
825
- var EU_COUNTRIES = new Set("AT BE BG HR CY CZ DK EE FI FR DE GR HU IE IT LV LT LU MT NL PL PT RO SK SI ES SE".split(" "));
826
- var parseViewerClaims = (value) => {
827
- if (!value || typeof value !== "object" || Array.isArray(value))
828
- return;
829
- const { region, ageConfirmed, ...rest } = value;
830
- if (Object.keys(rest).length)
831
- return;
832
- if (region !== undefined && (typeof region !== "string" || !VIEWER_COUNTRIES.has(region)))
833
- return;
834
- if (ageConfirmed !== undefined && typeof ageConfirmed !== "boolean")
835
- return;
836
- return {
837
- ...region !== undefined && { region },
838
- ...ageConfirmed !== undefined && { ageConfirmed }
839
- };
840
878
  };
841
879
 
880
+ // src/client/CalmLensUploadMimeTypes.ts
881
+ var UPLOAD_MIME_REJECTED = [
882
+ "application/octet-stream",
883
+ "multipart/form-data",
884
+ "multipart/mixed",
885
+ "multipart/alternative",
886
+ "multipart/related",
887
+ "multipart/signed",
888
+ "multipart/encrypted"
889
+ ];
890
+ var UPLOAD_MIME_PREFIXES = ["image/", "video/", "audio/", "text/"];
891
+ var UPLOAD_MIME_SUFFIXES = ["+json", "+xml"];
892
+ var UPLOAD_MIME_TYPES = [
893
+ "application/pdf",
894
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
895
+ "application/msword",
896
+ "application/rtf",
897
+ "application/vnd.oasis.opendocument.text",
898
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
899
+ "application/vnd.ms-excel.sheet.macroenabled.12",
900
+ "application/vnd.ms-excel",
901
+ "application/vnd.oasis.opendocument.spreadsheet",
902
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
903
+ "application/vnd.ms-powerpoint.presentation.macroenabled.12",
904
+ "application/vnd.ms-powerpoint",
905
+ "application/vnd.oasis.opendocument.presentation",
906
+ "application/javascript",
907
+ "application/json",
908
+ "application/x-javascript",
909
+ "application/x-yaml",
910
+ "application/xml",
911
+ "application/yaml"
912
+ ];
913
+
842
914
  // src/client/CalmLensUtils.ts
843
915
  var assertHttpUrl = (name, value) => {
844
916
  if (value === undefined)
@@ -900,11 +972,20 @@ var validateRequestOptions = (options) => {
900
972
  assertInteger("uploadTimeoutMs", options.uploadTimeoutMs, 1);
901
973
  assertInteger("maxRetries", options.maxRetries, 0);
902
974
  };
975
+ var CDN_LOCATION_KEYS = [
976
+ "assetId",
977
+ "externalId",
978
+ "lens",
979
+ "projectId",
980
+ "resource",
981
+ "transform",
982
+ "viewerClaims"
983
+ ];
903
984
  var LOCAL_OPTION_KEYS = {
904
985
  "assets.waitForDecision": ["assetId", "signal", "timeoutMs"],
905
- "cdn.getAssetUrl": ["assetIdentifier", "lens", "resource", "transform", "viewerClaims"],
906
- "cdn.serve": ["assetIdentifier", "init", "lens", "resource", "transform", "viewerClaims"],
907
- "uploadTokens.sign": ["expiresInSeconds", "externalId", "uploadPresetId"]
986
+ "cdn.getAssetUrl": CDN_LOCATION_KEYS,
987
+ "cdn.serve": [...CDN_LOCATION_KEYS, "init"],
988
+ "uploadTokens.sign": ["expiresIn", "externalId", "uploadPresetId"]
908
989
  };
909
990
  var IDEMPOTENT_OPERATIONS = [
910
991
  "assets.create",
@@ -954,6 +1035,12 @@ var encodePathSegment = (value, name) => {
954
1035
  throw invalidArgument(`${name} cannot be "." or ".."`);
955
1036
  return encodeURIComponent(value);
956
1037
  };
1038
+ var isAcceptedUploadMimeType = (mimeType) => {
1039
+ const type = normalizeUploadMimeType(mimeType);
1040
+ if (UPLOAD_MIME_REJECTED.includes(type))
1041
+ return false;
1042
+ return UPLOAD_MIME_PREFIXES.some((prefix) => type.startsWith(prefix)) || UPLOAD_MIME_SUFFIXES.some((suffix) => type.endsWith(suffix)) || UPLOAD_MIME_TYPES.includes(type);
1043
+ };
957
1044
  var TRANSFORM_OPTION_NAME = /^[a-z][a-zA-Z0-9]*$/;
958
1045
  var TRANSFORM_COLOUR_KEYS = new Set(["background", "border.color", "trim.border.color"]);
959
1046
  var HEX_COLOUR = /^#((?:[0-9a-f]{3}){1,2}|(?:[0-9a-f]{4}){1,2})$/i;
@@ -983,9 +1070,65 @@ var appendTransformOptions = (pairs, key, value) => {
983
1070
  throw invalidArgument(`Transform option "${key}" must be a string, number, boolean or object`);
984
1071
  pairs.push(`${key}=${encodeTransformComponent(text)}`);
985
1072
  };
1073
+ var hasRuleType = (type, value) => {
1074
+ switch (type) {
1075
+ case "object":
1076
+ return isPlainObject(value);
1077
+ case "string":
1078
+ case "boolean":
1079
+ return typeof value === type;
1080
+ case "number":
1081
+ return typeof value === "number" && Number.isFinite(value);
1082
+ case "integer":
1083
+ return typeof value === "number" && Number.isInteger(value);
1084
+ default:
1085
+ return true;
1086
+ }
1087
+ };
1088
+ var checkTransformOptions = (options) => {
1089
+ const unknownKeys = [];
1090
+ const invalidKeys = [];
1091
+ const check = (schema, value, key) => {
1092
+ const rule = schema.oneOf ? schema.oneOf.find(({ type }) => hasRuleType(type, value)) : schema;
1093
+ if (!rule || !hasRuleType(rule.type, value) || rule.enum && !rule.enum.includes(value) || rule.minimum !== undefined && value < rule.minimum || rule.maximum !== undefined && value > rule.maximum) {
1094
+ invalidKeys.push(key);
1095
+ return;
1096
+ }
1097
+ if (rule.type !== "object")
1098
+ return;
1099
+ const object = value;
1100
+ const path = (name) => key ? `${key}.${name}` : name;
1101
+ for (const name of rule.required ?? []) {
1102
+ if (object[name] === undefined || object[name] === null)
1103
+ invalidKeys.push(path(name));
1104
+ }
1105
+ for (const name of Object.keys(object).sort()) {
1106
+ if (object[name] === undefined || object[name] === null)
1107
+ continue;
1108
+ const child = rule.properties?.[name];
1109
+ if (child)
1110
+ check(child, object[name], path(name));
1111
+ else
1112
+ unknownKeys.push(path(name));
1113
+ }
1114
+ };
1115
+ check(TRANSFORM_OPTIONS_SCHEMA, options, "");
1116
+ return { unknownKeys, invalidKeys };
1117
+ };
1118
+ var assertTransformOptions = (options) => {
1119
+ const { unknownKeys, invalidKeys } = checkTransformOptions(options);
1120
+ if (!unknownKeys.length && !invalidKeys.length)
1121
+ return;
1122
+ const problems = [
1123
+ ...unknownKeys.length ? [`unknown option${unknownKeys.length > 1 ? "s" : ""} ${unknownKeys.join(", ")}`] : [],
1124
+ ...invalidKeys.length ? [`invalid value${invalidKeys.length > 1 ? "s" : ""} for ${invalidKeys.join(", ")}`] : []
1125
+ ];
1126
+ throw invalidArgument(`Transform options are invalid: ${problems.join("; ")}. Pass the options themselves, such as { width: 640, format: "webp" }.`, { unknownKeys, invalidKeys });
1127
+ };
986
1128
  var serializeTransform = (transform) => {
987
1129
  if (!isPlainObject(transform))
988
1130
  throw invalidArgument("Transform options must be an object");
1131
+ assertTransformOptions(transform);
989
1132
  const pairs = [];
990
1133
  for (const key of Object.keys(transform).sort()) {
991
1134
  if (!TRANSFORM_OPTION_NAME.test(key)) {
@@ -1007,13 +1150,6 @@ var transformSelector = (transform) => {
1007
1150
  return transform;
1008
1151
  };
1009
1152
  var DEFAULT_CDN_BASE_URL = `https://cdn.${DOMAIN}/v1`;
1010
- var CDN_RESOURCES = new Set([
1011
- "original",
1012
- "rendered",
1013
- "placeholder"
1014
- ]);
1015
- var DEFAULT_SIGNED_URL_EXPIRES_IN_SECONDS = 60 * 15;
1016
- var MAX_SIGNED_URL_SECONDS = 60 * 60 * 24;
1017
1153
  var ASSET_BATCH_MAX_ASSETS = 500;
1018
1154
  var ASSET_BATCH_OPERATIONS = ["delete", "remove-content"];
1019
1155
  var validateBatchAssetsOptions = ({ assetIds, operation }) => {
@@ -1027,115 +1163,323 @@ var validateBatchAssetsOptions = ({ assetIds, operation }) => {
1027
1163
  throw invalidArgument(`operation must be one of ${ASSET_BATCH_OPERATIONS.join(", ")}`);
1028
1164
  }
1029
1165
  };
1030
- var validateSignedUrlOptions = (options) => {
1031
- const { resource = "rendered", lens, transform, expiresInSeconds } = options;
1032
- if (resource !== "original" && resource !== "rendered") {
1033
- throw invalidArgument("A signed URL's resource must be original or rendered");
1166
+ var stringifyQuery = (query) => Object.entries(query).flatMap(([key, value]) => {
1167
+ if (value === undefined || value === null)
1168
+ return [];
1169
+ const text = Array.isArray(value) ? value.every((item) => typeof item === "string" || typeof item === "number") ? value.join(",") : JSON.stringify(value) : typeof value === "object" ? JSON.stringify(value) : String(value);
1170
+ return [`${encodeURIComponent(key)}=${encodeURIComponent(text)}`];
1171
+ }).join("&");
1172
+ var isAssetDecided = (asset) => asset.classification.status === "completed" || asset.classification.status === "failed";
1173
+ var DECISION_POLL_FIRST_DELAY_MS = 500;
1174
+ var DECISION_POLL_DELAY_FACTOR = 1.5;
1175
+ var DECISION_POLL_MAX_DELAY_MS = 2000;
1176
+ var DEFAULT_DECISION_TIMEOUT_MS = 60000;
1177
+ var pollForDecision = async (retrieve, {
1178
+ timeoutMs = DEFAULT_DECISION_TIMEOUT_MS,
1179
+ signal
1180
+ }, sleep, now = Date.now) => {
1181
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
1182
+ throw invalidArgument("timeoutMs must be a non-negative number");
1183
+ }
1184
+ const deadline = now() + timeoutMs;
1185
+ let delay = DECISION_POLL_FIRST_DELAY_MS;
1186
+ for (;; ) {
1187
+ if (signal?.aborted) {
1188
+ throw new CalmLensError(SDK_ERROR_CODES.CANCELLED, { message: "Request cancelled" });
1189
+ }
1190
+ const asset = await retrieve();
1191
+ if (isAssetDecided(asset))
1192
+ return asset;
1193
+ const remaining = deadline - now();
1194
+ if (remaining <= 0) {
1195
+ throw new CalmLensError(SDK_ERROR_CODES.TIMEOUT, {
1196
+ message: `Asset ${asset.id} had no moderation decision after ${timeoutMs}ms (processing ${asset.classification.status}, moderation ${asset.classification.moderation.status})`,
1197
+ details: {
1198
+ assetId: asset.id,
1199
+ classificationStatus: asset.classification.status,
1200
+ moderationStatus: asset.classification.moderation.status
1201
+ }
1202
+ });
1203
+ }
1204
+ await sleep(Math.min(delay, remaining), signal);
1205
+ delay = Math.min(DECISION_POLL_MAX_DELAY_MS, delay * DECISION_POLL_DELAY_FACTOR);
1206
+ }
1207
+ };
1208
+
1209
+ // src/client/CalmLensViewerClaims.ts
1210
+ var VIEWER_COUNTRIES = new Set("AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW".split(" "));
1211
+ var EU_COUNTRIES = new Set("AT BE BG HR CY CZ DK EE FI FR DE GR HU IE IT LV LT LU MT NL PL PT RO SK SI ES SE".split(" "));
1212
+ var parseViewerClaims = (value) => {
1213
+ if (!value || typeof value !== "object" || Array.isArray(value))
1214
+ return;
1215
+ const { region, ageConfirmed, ...rest } = value;
1216
+ if (Object.keys(rest).length)
1217
+ return;
1218
+ if (region !== undefined && (typeof region !== "string" || !VIEWER_COUNTRIES.has(region)))
1219
+ return;
1220
+ if (ageConfirmed !== undefined && typeof ageConfirmed !== "boolean")
1221
+ return;
1222
+ return {
1223
+ ...region !== undefined && { region },
1224
+ ...ageConfirmed !== undefined && { ageConfirmed }
1225
+ };
1226
+ };
1227
+
1228
+ // src/client/CalmLensCdn.ts
1229
+ var ASSET_RESOURCE_PATHS = {
1230
+ original: "original",
1231
+ rendered: "rendered",
1232
+ preview: "preview",
1233
+ placeholder: "placeholder",
1234
+ hls: "hls/index.m3u8",
1235
+ embed: "embed",
1236
+ info: "info"
1237
+ };
1238
+ var EXTERNAL_ID_SEGMENT_PREFIX = "ext:";
1239
+ var CDN_RESOURCES = Object.keys(ASSET_RESOURCE_PATHS);
1240
+ var UNSELECTABLE = new Set([
1241
+ "original",
1242
+ "hls",
1243
+ "embed",
1244
+ "placeholder",
1245
+ "info"
1246
+ ]);
1247
+ var DEFAULT_SIGNED_URL_EXPIRES_IN = 60 * 15;
1248
+ var MAX_SIGNED_URL_EXPIRES_IN = 60 * 60 * 24;
1249
+ var getAssetSegment = (options) => {
1250
+ const { assetId, externalId } = options;
1251
+ if (assetId === undefined === (externalId === undefined)) {
1252
+ throw invalidArgument("Pass either assetId or externalId");
1253
+ }
1254
+ if (assetId !== undefined)
1255
+ return encodePathSegment(assetId, "Asset ID");
1256
+ if (typeof externalId !== "string" || !externalId) {
1257
+ throw invalidArgument("External ID is required");
1258
+ }
1259
+ return `${EXTERNAL_ID_SEGMENT_PREFIX}${encodeURIComponent(externalId)}`;
1260
+ };
1261
+ var toUrlViewerClaims = (claims) => {
1262
+ if (claims === undefined)
1263
+ return;
1264
+ const parsed = parseViewerClaims(claims);
1265
+ if (!parsed)
1266
+ throw invalidArgument("Invalid viewerClaims");
1267
+ const { region, ageConfirmed } = parsed;
1268
+ if (!region && ageConfirmed !== true)
1269
+ return;
1270
+ return { ...region ? { region } : {}, ...ageConfirmed === true ? { ageConfirmed } : {} };
1271
+ };
1272
+ var viewerClaimsQuery = (claims) => {
1273
+ const sent = toUrlViewerClaims(claims);
1274
+ return sent ? `?${new URLSearchParams({ viewerClaims: JSON.stringify(sent) })}` : "";
1275
+ };
1276
+ var appendAssetLocation = (assetUrl, location) => {
1277
+ const { resource, lens, transform, viewerClaims } = location;
1278
+ const selected = lens !== undefined || transform !== undefined;
1279
+ let path = assetUrl;
1280
+ if (resource === undefined) {
1281
+ if (selected)
1282
+ throw invalidArgument("A lens or transform needs a resource, such as rendered");
1283
+ } else {
1284
+ if (typeof resource !== "string" || !Object.hasOwn(ASSET_RESOURCE_PATHS, resource)) {
1285
+ throw invalidArgument(`resource must be one of ${CDN_RESOURCES.join(", ")}`);
1286
+ }
1287
+ if (UNSELECTABLE.has(resource) && selected) {
1288
+ throw invalidArgument(`The ${resource} resource takes no lens or transform`);
1289
+ }
1290
+ path = `${assetUrl}/${ASSET_RESOURCE_PATHS[resource]}`;
1291
+ const selector = transformSelector(transform);
1292
+ const parts = [
1293
+ ...lens !== undefined ? [`@${encodePathSegment(lens, "Lens")}`] : [],
1294
+ ...selector ? [typeof transform === "string" ? encodeURI(selector) : selector] : []
1295
+ ];
1296
+ if (parts.length)
1297
+ path = `${path}/${parts.join(",")}`;
1298
+ }
1299
+ return `${path}${viewerClaimsQuery(viewerClaims)}`;
1300
+ };
1301
+ var buildAssetUrl = (cdnBaseUrl, projectId, options) => {
1302
+ const { assetId, externalId, resource, lens, transform, viewerClaims } = options;
1303
+ const base = `${cdnBaseUrl.replace(/\/+$/, "")}/assets/${encodePathSegment(projectId, "Project ID")}/${getAssetSegment({ assetId, externalId })}`;
1304
+ return appendAssetLocation(base, { resource, lens, transform, viewerClaims });
1305
+ };
1306
+ var validateSignAssetUrlOptions = (options) => {
1307
+ const { expiresIn, original } = options;
1308
+ if (expiresIn !== undefined && (!Number.isInteger(expiresIn) || expiresIn < 1 || expiresIn > MAX_SIGNED_URL_EXPIRES_IN)) {
1309
+ throw invalidArgument(`expiresIn must be a whole number from 1 to ${MAX_SIGNED_URL_EXPIRES_IN}`);
1310
+ }
1311
+ if (original !== undefined && typeof original !== "boolean") {
1312
+ throw invalidArgument("original must be a boolean");
1313
+ }
1314
+ getAssetSegment(options);
1315
+ appendAssetLocation("", options);
1316
+ };
1317
+ var splitAssetUrl = (url) => {
1318
+ const [path = "", query] = url.split("?", 2);
1319
+ const base = path.replace(/\/+$/, "");
1320
+ const raw = query ? new URLSearchParams(query).get("viewerClaims") : null;
1321
+ if (raw === null)
1322
+ return { base };
1323
+ try {
1324
+ return { base, claims: JSON.parse(raw) };
1325
+ } catch {
1326
+ throw invalidArgument("The asset URL's viewerClaims are not JSON");
1034
1327
  }
1035
- if (resource === "original" && (lens !== undefined || transform !== undefined)) {
1036
- throw invalidArgument("Lenses and transforms apply only to the rendered resource");
1328
+ };
1329
+ var isAssetInfo = (value) => {
1330
+ if (!value || typeof value !== "object")
1331
+ return false;
1332
+ const info = value;
1333
+ return typeof info.id === "string" && typeof info.projectId === "string" && typeof info.type === "string" && !!info.content && typeof info.content === "object" && (info.availability === "available" || info.availability === "age-restricted" || info.availability === "unavailable");
1334
+ };
1335
+ var getAssetInfo = async (url, options = {}) => {
1336
+ if (typeof url !== "string" || !URL.canParse(url)) {
1337
+ throw invalidArgument("url must be an absolute asset URL");
1338
+ }
1339
+ const { base, claims } = splitAssetUrl(url);
1340
+ const infoUrl = `${base}/info${viewerClaimsQuery(options.viewerClaims ?? claims)}`;
1341
+ const fetcher = options.fetch ?? globalThis.fetch;
1342
+ let response;
1343
+ try {
1344
+ response = await fetcher(infoUrl, {
1345
+ headers: { Accept: "application/json" },
1346
+ signal: options.signal
1347
+ });
1348
+ } catch (cause) {
1349
+ if (options.signal?.aborted)
1350
+ throw cause;
1351
+ throw new CalmLensError(SDK_ERROR_CODES.TRANSPORT_ERROR, {
1352
+ message: "The asset's info could not be fetched",
1353
+ cause
1354
+ });
1037
1355
  }
1038
- if (expiresInSeconds !== undefined && (!Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_SIGNED_URL_SECONDS)) {
1039
- throw invalidArgument("expiresInSeconds must be a whole number from 1 to 86400");
1356
+ const bytes = new Uint8Array(await response.arrayBuffer());
1357
+ if (!response.ok)
1358
+ throw toHttpError(response, bytes);
1359
+ let data;
1360
+ try {
1361
+ data = JSON.parse(new TextDecoder().decode(bytes));
1362
+ } catch {}
1363
+ if (!isAssetInfo(data)) {
1364
+ throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
1365
+ message: "The CDN returned no asset info",
1366
+ status: response.status
1367
+ });
1040
1368
  }
1369
+ return data;
1370
+ };
1371
+
1372
+ // src/contract/AssetPayload.js
1373
+ var bufferInputToBytes = (value) => {
1374
+ if (value instanceof ArrayBuffer)
1375
+ return new Uint8Array(value);
1376
+ return Uint8Array.from(value);
1377
+ };
1378
+ var BASE64_PART_BOUNDARY_ERROR = "Invalid base64 part. For multipart uploads, split the original bytes first, then base64-encode each part. Do not split one full base64 string into substrings.";
1379
+ var MULTIPART_PART_TOO_SMALL_ERROR = `Multipart upload parts must be at least 5MiB except the final part.`;
1380
+ var getRawBase64 = (value) => {
1381
+ const markerIndex = value.indexOf(";base64,");
1382
+ if (markerIndex === -1)
1383
+ return value;
1384
+ return value.slice(markerIndex + 8);
1385
+ };
1386
+ var validateBase64PayloadString = (payload, options) => {
1387
+ const raw = getRawBase64(payload.base64).replace(/\s/g, "");
1388
+ if (options?.multipart && raw.length % 4 !== 0)
1389
+ return {
1390
+ ok: false,
1391
+ error: BASE64_PART_BOUNDARY_ERROR
1392
+ };
1393
+ return { ok: true };
1041
1394
  };
1042
- var getAssetUrl = ({
1043
- projectId,
1044
- assetIdentifier,
1045
- cdnBaseUrl = DEFAULT_CDN_BASE_URL,
1046
- resource = "rendered",
1047
- ...options
1048
- }) => {
1049
- if (!CDN_RESOURCES.has(resource)) {
1050
- throw invalidArgument("resource must be original, rendered or placeholder");
1051
- }
1052
- if (resource === "original" && (options.lens !== undefined || options.transform !== undefined)) {
1053
- throw invalidArgument("Lenses and transforms apply only to the rendered resource");
1054
- }
1055
- if (resource === "placeholder" && (options.lens !== undefined || options.transform !== undefined)) {
1056
- throw invalidArgument("A placeholder takes no lens or transform");
1395
+ var assetToData = (payload) => {
1396
+ if ("plainText" in payload && payload.plainText !== undefined)
1397
+ return new TextEncoder().encode(payload.plainText);
1398
+ if ("data" in payload && payload.data)
1399
+ return payload.data;
1400
+ if ("buffer" in payload) {
1401
+ if (payload.buffer instanceof ArrayBuffer)
1402
+ return payload.buffer;
1403
+ return bufferInputToBytes(payload.buffer);
1057
1404
  }
1058
- const url = `${cdnBaseUrl.replace(/\/+$/, "")}/assets/${encodePathSegment(projectId, "Project ID")}/${encodePathSegment(assetIdentifier, "Asset identifier")}/${resource}`;
1059
- return appendCdnSelector(url, options);
1060
- };
1061
- var appendCdnSelector = (url, options) => {
1062
- const path = appendCdnPathSelector(url, options);
1063
- const query = new URLSearchParams;
1064
- if (options.viewerClaims !== undefined) {
1065
- const claims = parseViewerClaims(options.viewerClaims);
1066
- if (!claims)
1067
- throw invalidArgument("Invalid viewerClaims");
1068
- query.set("viewerClaims", JSON.stringify(claims));
1069
- }
1070
- return query.size ? `${path}?${query}` : path;
1071
- };
1072
- var appendCdnPathSelector = (url, options) => {
1073
- const transform = transformSelector(options.transform);
1074
- const selector = [
1075
- ...options.lens ? [`@${encodePathSegment(options.lens, "Lens")}`] : [],
1076
- ...transform ? [typeof options.transform === "string" ? encodeURI(transform) : transform] : []
1077
- ].join(",");
1078
- return selector ? `${url}/${selector}` : url;
1405
+ if (payload.uint8Array !== undefined)
1406
+ return Uint8Array.from(payload.uint8Array);
1407
+ if (payload.base64 === undefined)
1408
+ throw new Error("Invalid asset payload");
1409
+ const raw = getRawBase64(payload.base64);
1410
+ if (typeof Buffer !== "undefined")
1411
+ return Uint8Array.from(Buffer.from(raw, "base64"));
1412
+ const binary = atob(raw);
1413
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
1079
1414
  };
1080
- var appendQueryValue = (parts, key, value) => {
1081
- if (value === undefined || value === null)
1082
- return;
1083
- if (Array.isArray(value)) {
1084
- for (const [index, item] of value.entries())
1085
- appendQueryValue(parts, `${key}[${index}]`, item);
1415
+ var getAssetPayloadByteLength = (payload) => {
1416
+ if ("plainText" in payload && payload.plainText !== undefined)
1417
+ return new TextEncoder().encode(payload.plainText).byteLength;
1418
+ if ("data" in payload && payload.data) {
1419
+ if (payload.data instanceof Blob)
1420
+ return payload.data.size;
1421
+ if (payload.data instanceof Response) {
1422
+ const contentLength = payload.data.headers.get("content-length");
1423
+ return contentLength ? Number(contentLength) : undefined;
1424
+ }
1086
1425
  return;
1087
1426
  }
1088
- if (typeof value === "object") {
1089
- for (const [field, item] of Object.entries(value)) {
1090
- appendQueryValue(parts, `${key}[${field}]`, item);
1091
- }
1427
+ if ("buffer" in payload && payload.buffer)
1428
+ return payload.buffer.byteLength;
1429
+ if (payload.uint8Array !== undefined) {
1430
+ if (Array.isArray(payload.uint8Array))
1431
+ return payload.uint8Array.length;
1432
+ return payload.uint8Array.byteLength;
1433
+ }
1434
+ if (payload.base64 === undefined)
1092
1435
  return;
1436
+ const raw = getRawBase64(payload.base64).replace(/\s/g, "");
1437
+ const padding = raw.endsWith("==") ? 2 : raw.endsWith("=") ? 1 : 0;
1438
+ return Math.max(0, Math.floor(raw.length * 3 / 4) - padding);
1439
+ };
1440
+ var validateAssetPayload = (payload, options) => {
1441
+ if ("base64" in payload && payload.base64 !== undefined) {
1442
+ const validation = validateBase64PayloadString(payload, options);
1443
+ if (!validation.ok)
1444
+ return {
1445
+ ok: false,
1446
+ error: validation.error
1447
+ };
1093
1448
  }
1094
- parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
1449
+ const byteLength = getAssetPayloadByteLength(payload);
1450
+ if (options?.multipart && !options.isFinal && byteLength !== undefined && byteLength < 5242880)
1451
+ return {
1452
+ ok: false,
1453
+ error: MULTIPART_PART_TOO_SMALL_ERROR
1454
+ };
1455
+ return { ok: true };
1095
1456
  };
1096
- var stringifyQuery = (query) => {
1097
- const parts = [];
1098
- for (const [key, value] of Object.entries(query))
1099
- appendQueryValue(parts, key, value);
1100
- return parts.join("&");
1457
+
1458
+ // src/contract/Media-B2PMcUf7.js
1459
+ var MAX_MEDIA_UPLOAD_BYTES = 52428800;
1460
+ var MAX_LONG_MEDIA_UPLOAD_BYTES = 2147483648;
1461
+ // src/contract/ModerationContextLimits-BIMUlk2e.js
1462
+ var countModerationContextCharacters = (text) => {
1463
+ let count = 0;
1464
+ for (const _ of text)
1465
+ count++;
1466
+ return count;
1101
1467
  };
1102
- var isAssetDecided = (asset) => asset.classification.moderation.status !== "pending" || asset.classification.status === "failed";
1103
- var DECISION_POLL_FIRST_DELAY_MS = 500;
1104
- var DECISION_POLL_DELAY_FACTOR = 1.5;
1105
- var DECISION_POLL_MAX_DELAY_MS = 2000;
1106
- var DEFAULT_DECISION_TIMEOUT_MS = 60000;
1107
- var pollForDecision = async (retrieve, {
1108
- timeoutMs = DEFAULT_DECISION_TIMEOUT_MS,
1109
- signal
1110
- }, sleep, now = Date.now) => {
1111
- if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
1112
- throw invalidArgument("timeoutMs must be a non-negative number");
1113
- }
1114
- const deadline = now() + timeoutMs;
1115
- let delay = DECISION_POLL_FIRST_DELAY_MS;
1116
- for (;; ) {
1117
- if (signal?.aborted) {
1118
- throw new CalmLensError(SDK_ERROR_CODES.CANCELLED, { message: "Request cancelled" });
1119
- }
1120
- const asset = await retrieve();
1121
- if (isAssetDecided(asset))
1122
- return asset;
1123
- const remaining = deadline - now();
1124
- if (remaining <= 0) {
1125
- throw new CalmLensError(SDK_ERROR_CODES.TIMEOUT, {
1126
- message: `Asset ${asset.id} had no moderation decision after ${timeoutMs}ms (processing ${asset.classification.status}, moderation ${asset.classification.moderation.status})`,
1127
- details: {
1128
- assetId: asset.id,
1129
- classificationStatus: asset.classification.status,
1130
- moderationStatus: asset.classification.moderation.status
1131
- }
1132
- });
1133
- }
1134
- await sleep(Math.min(delay, remaining), signal);
1135
- delay = Math.min(DECISION_POLL_MAX_DELAY_MS, delay * DECISION_POLL_DELAY_FACTOR);
1468
+ var selectModerationContextItems = (items) => {
1469
+ const selected = [];
1470
+ let characters = 0;
1471
+ for (let index = items.length - 1;index >= 0; index--) {
1472
+ if (selected.length === 5)
1473
+ break;
1474
+ const item = items[index];
1475
+ const length = countModerationContextCharacters(item.text);
1476
+ if (selected.length && characters + length > 2000)
1477
+ break;
1478
+ selected.unshift(item);
1479
+ characters += length;
1136
1480
  }
1481
+ return selected;
1137
1482
  };
1138
-
1139
1483
  // src/client/CalmLensConnection.ts
1140
1484
  var DEFAULT_TIMEOUT_MS = 120000;
1141
1485
  var MOCK_HOOKS = Symbol.for("@calmlens/sdk.mockHooks");
@@ -1199,10 +1543,10 @@ var setOptionalQueryValue = (params, key, value) => {
1199
1543
  }
1200
1544
  };
1201
1545
  var assertValidUploadMimeType = (mimeType) => {
1202
- if (isRejectedUploadMimeType(mimeType)) {
1203
- throw new CalmLensError(API_ERROR_CODES.INVALID_UPLOAD_MIME_TYPE, {
1546
+ if (!isAcceptedUploadMimeType(mimeType)) {
1547
+ throw new CalmLensError(API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, {
1204
1548
  message: getRejectedUploadMimeTypeError(mimeType),
1205
- details: { mimeType }
1549
+ details: { mimeType, source: "calmlens" }
1206
1550
  });
1207
1551
  }
1208
1552
  };
@@ -1217,17 +1561,23 @@ var assertDeclaredPayloadSize = (payload, declared = payload.sizeInBytes) => {
1217
1561
  throw invalidPayload("sizeInBytes must match the payload byte length");
1218
1562
  }
1219
1563
  };
1220
- var assertDirectUploadSize = (content) => {
1221
- const size = content.sizeInBytes ?? getAssetPayloadByteLength(content);
1564
+ var assertUploadSize = (type, size, inParts) => {
1222
1565
  if (size === undefined)
1223
1566
  return;
1224
- const type = content.type.toLowerCase();
1225
- const [limit, message] = type.startsWith("image/") ? [
1567
+ const mime = type.toLowerCase();
1568
+ const [limit, message] = mime.startsWith("image/") ? [
1226
1569
  MAX_DIRECT_IMAGE_UPLOAD_BYTES,
1227
1570
  "Images uploaded in one request can be at most 10 MiB; upload larger images in parts"
1228
- ] : type.startsWith("audio/") || type.startsWith("video/") ? [MAX_MEDIA_UPLOAD_BYTES, "Audio and video files can be at most 50 MiB"] : [MAX_NON_IMAGE_UPLOAD_BYTES, "Files can be at most 5,000 MiB"];
1229
- if (size > limit)
1230
- throw new CalmLensError(API_ERROR_CODES.FILE_TOO_LARGE, { message });
1571
+ ] : mime.startsWith("audio/") || mime.startsWith("video/") ? [
1572
+ inParts ? MAX_LONG_MEDIA_UPLOAD_BYTES : MAX_MEDIA_UPLOAD_BYTES,
1573
+ "Audio and video files can be at most 50 MiB in one request, or 2 GiB in parts"
1574
+ ] : [MAX_NON_IMAGE_UPLOAD_BYTES, "Files can be at most 5,000 MiB"];
1575
+ if (size > limit) {
1576
+ throw new CalmLensError(API_ERROR_CODES.UPLOAD_TOO_LARGE, {
1577
+ message,
1578
+ details: { limitBytes: limit, source: "plan" }
1579
+ });
1580
+ }
1231
1581
  };
1232
1582
  var prepareSubmitAssetOptions = (options, {
1233
1583
  deferUploadChecks = false,
@@ -1259,12 +1609,14 @@ var prepareSubmitAssetOptions = (options, {
1259
1609
  }
1260
1610
  if (!deferUploadChecks && inParts && isImageMimeType(options.content.type)) {
1261
1611
  if ((getAssetPayloadByteLength(options.content) ?? 0) > MAX_IMAGE_UPLOAD_BYTES) {
1262
- throw new CalmLensError(API_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE, {
1263
- message: "Multipart image uploads cannot exceed 20MB."
1612
+ throw new CalmLensError(API_ERROR_CODES.UPLOAD_TOO_LARGE, {
1613
+ message: "Multipart image uploads cannot exceed 20 MiB.",
1614
+ details: { limitBytes: MAX_IMAGE_UPLOAD_BYTES, source: "plan" }
1264
1615
  });
1265
1616
  }
1266
- } else if (!deferUploadChecks)
1267
- assertDirectUploadSize(options.content);
1617
+ } else if (!deferUploadChecks) {
1618
+ assertUploadSize(options.content.type, options.content.sizeInBytes ?? getAssetPayloadByteLength(options.content), inParts);
1619
+ }
1268
1620
  if (!("plainText" in options.content)) {
1269
1621
  const validation = validateAssetPayload(options.content);
1270
1622
  if (!validation.ok)
@@ -1277,11 +1629,15 @@ var prepareSubmitAssetOptions = (options, {
1277
1629
  const partSizeInBytes = options.part.sizeInBytes ?? getAssetPayloadByteLength(options.part);
1278
1630
  if (!deferUploadChecks && isImageMimeType(options.part.type) && partSizeInBytes !== undefined) {
1279
1631
  if (partSizeInBytes > MAX_IMAGE_UPLOAD_BYTES) {
1280
- throw new CalmLensError(API_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE, {
1281
- message: "Multipart image uploads cannot exceed 20MB."
1632
+ throw new CalmLensError(API_ERROR_CODES.UPLOAD_TOO_LARGE, {
1633
+ message: "Multipart image uploads cannot exceed 20 MiB.",
1634
+ details: { limitBytes: MAX_IMAGE_UPLOAD_BYTES, source: "plan" }
1282
1635
  });
1283
1636
  }
1284
1637
  }
1638
+ if (!deferUploadChecks && !isImageMimeType(options.part.type)) {
1639
+ assertUploadSize(options.part.type, options.totalSizeInBytes, true);
1640
+ }
1285
1641
  const validation = validateAssetPayload(options.part, {
1286
1642
  multipart: true,
1287
1643
  isFinal: deferUploadChecks || options.part.isFinal
@@ -1301,7 +1657,7 @@ var newIdempotencyKey = () => randomUuid();
1301
1657
  var isTextPayload = (payload) => ("plainText" in payload);
1302
1658
  var hasStringStatus = (value) => !!value && typeof value === "object" && typeof value.status === "string";
1303
1659
  var isAsset = (data) => !!data && typeof data === "object" && typeof data.id === "string" && !!data.id && hasStringStatus(data.classification) && hasStringStatus(data.upload) && typeof data.classification?.moderation?.status === "string";
1304
- var isUploadedAsset = (data) => !!data && typeof data === "object" && typeof data.id === "string" && !!data.id;
1660
+ var isUploadedAsset = (data) => !!data && typeof data === "object" && typeof data.id === "string" && !!data.id && hasStringStatus(data.classification) && hasStringStatus(data.upload);
1305
1661
  var expectUploadedAsset = (data) => {
1306
1662
  if (!isUploadedAsset(data)) {
1307
1663
  throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
@@ -1391,14 +1747,15 @@ class CalmLensConnection {
1391
1747
  fetch: this.options.uploadFetch
1392
1748
  });
1393
1749
  }
1394
- submitRawUpload(uploadsPath, options, queue, authHeaders = {}) {
1750
+ submitRawUpload(uploadsPath, options, wait, authHeaders = {}) {
1395
1751
  const query = new URLSearchParams;
1396
1752
  query.set("name", options.name);
1397
- query.set("queue", String(queue));
1753
+ query.set("wait", String(wait));
1398
1754
  setOptionalQueryValue(query, "description", options.description);
1399
1755
  setOptionalQueryValue(query, "processingOptions", options.processingOptions);
1400
1756
  setOptionalQueryValue(query, "visibility", options.visibility);
1401
1757
  setOptionalQueryValue(query, "metadata", options.metadata);
1758
+ setOptionalQueryValue(query, "tags", options.tags);
1402
1759
  setOptionalQueryValue(query, "authorId", options.authorId);
1403
1760
  setOptionalQueryValue(query, "context", options.context);
1404
1761
  setOptionalQueryValue(query, "externalId", options.externalId);
@@ -1426,7 +1783,7 @@ class CalmLensConnection {
1426
1783
  get partSizeBytes() {
1427
1784
  return this.options.partSizeBytes ?? DEFAULT_PART_SIZE_BYTES;
1428
1785
  }
1429
- async submitInParts(uploadsPath, options, queue, {
1786
+ async submitInParts(uploadsPath, options, wait, {
1430
1787
  authHeaders = {},
1431
1788
  partPath,
1432
1789
  onStarted,
@@ -1443,7 +1800,7 @@ class CalmLensConnection {
1443
1800
  part: { ...part(1), type: content.type, partNumber: 1, isFinal: false },
1444
1801
  totalSizeInBytes: source.size,
1445
1802
  idempotencyKey: key
1446
- }, queue, authHeaders);
1803
+ }, wait, authHeaders);
1447
1804
  const assetId = expectUploadedAsset(first).id;
1448
1805
  onStarted?.(assetId);
1449
1806
  let result = first;
@@ -1470,7 +1827,7 @@ class CalmLensConnection {
1470
1827
  }
1471
1828
  return result;
1472
1829
  }
1473
- uploadPart(partPath, { part, queue, idempotencyKey }, authHeaders = {}) {
1830
+ uploadPart(partPath, { part, wait, idempotencyKey }, authHeaders = {}) {
1474
1831
  if (!part)
1475
1832
  throw invalidArgument("Part options are required");
1476
1833
  assertDeclaredPayloadSize(part);
@@ -1484,8 +1841,8 @@ class CalmLensConnection {
1484
1841
  partNumber: String(part.partNumber),
1485
1842
  isFinal: String(part.isFinal ?? false)
1486
1843
  });
1487
- if (queue !== undefined)
1488
- query.set("queue", String(queue));
1844
+ if (wait !== undefined)
1845
+ query.set("wait", String(wait));
1489
1846
  setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? getAssetPayloadByteLength(part));
1490
1847
  return this.upload(this.url(`${partPath}?${query}`), part, { ...authHeaders, "X-CalmLens-Upload": "part" }, idempotencyKey ?? newIdempotencyKey());
1491
1848
  }
@@ -1494,50 +1851,80 @@ class CalmLensConnection {
1494
1851
  // src/client/CalmLensOptionKeys.ts
1495
1852
  var SERVER_OPTION_KEYS = {
1496
1853
  "assets.batch": ["assetIds", "operation"],
1497
- "assets.classify": ["authorId", "content", "context", "description", "externalId", "externalUrl", "folderId", "isFinal", "metadata", "name", "part", "processingOptions", "sizeInBytes", "totalSizeInBytes", "uploadPresetId", "url", "visibility"],
1498
- "assets.create": ["authorId", "content", "context", "description", "externalId", "externalUrl", "folderId", "isFinal", "metadata", "name", "part", "processingOptions", "sizeInBytes", "totalSizeInBytes", "uploadPresetId", "url", "visibility"],
1499
- "assets.createSignedUrl": ["assetId", "expiresInSeconds", "lens", "resource", "transform", "viewerClaims"],
1854
+ "assets.classify": ["authorId", "content", "context", "description", "externalId", "externalUrl", "folderId", "isFinal", "metadata", "name", "part", "processingOptions", "sizeInBytes", "tags", "totalSizeInBytes", "uploadPresetId", "url", "visibility"],
1855
+ "assets.create": ["authorId", "content", "context", "description", "externalId", "externalUrl", "folderId", "isFinal", "metadata", "name", "part", "processingOptions", "sizeInBytes", "tags", "totalSizeInBytes", "uploadPresetId", "url", "visibility"],
1500
1856
  "assets.decide": ["assetId", "confirmPurge", "decision", "note"],
1501
1857
  "assets.delete": ["assetId"],
1502
- "assets.deleteContent": ["assetId"],
1503
1858
  "assets.explain": ["assetId", "rerun"],
1504
- "assets.iterate": ["cursor", "filter", "folderId", "ordering", "pageSize"],
1505
- "assets.iterateChildren": ["assetId", "cursor", "ordering", "pageSize"],
1506
- "assets.list": ["cursor", "filter", "folderId", "ordering", "pageSize"],
1507
- "assets.listChildren": ["assetId", "cursor", "ordering", "pageSize"],
1859
+ "assets.iterate": ["cursor", "filter", "pageSize", "sort"],
1860
+ "assets.iterateChildren": ["assetId", "cursor", "pageSize", "sort"],
1861
+ "assets.iterateTimeline": ["assetId", "cursor", "pageSize"],
1862
+ "assets.list": ["cursor", "filter", "pageSize", "sort"],
1863
+ "assets.listChildren": ["assetId", "cursor", "pageSize", "sort"],
1864
+ "assets.listTimeline": ["assetId", "cursor", "pageSize"],
1508
1865
  "assets.move": ["assetId", "folderId"],
1866
+ "assets.removeContent": ["assetId"],
1509
1867
  "assets.retrieve": ["assetId"],
1510
1868
  "assets.retry": ["assetId"],
1511
- "assets.search": ["limit", "mode", "query"],
1869
+ "assets.search": ["mode", "pageSize", "query"],
1512
1870
  "assets.update": ["assetId", "description", "externalId", "externalUrl", "metadata", "name", "tags", "visibility"],
1513
- "assets.uploadPart": ["assetId", "part", "queue"],
1514
- ensureLens: ["active", "description", "identifier", "name", "transform", "type", "version"],
1871
+ "assets.uploadPart": ["assetId", "part", "wait"],
1872
+ "cdn.signAssetUrl": ["assetId", "expiresIn", "externalId", "lens", "original", "projectId", "resource", "transform", "viewerClaims"],
1873
+ ensureLens: ["active", "description", "identifier", "name", "transform", "type"],
1515
1874
  ensureLenses: ["lenses"],
1516
- "events.list": ["cursor", "pageSize"],
1517
- "events.pages": ["cursor", "pageSize"],
1875
+ "events.list": ["assetId", "cursor", "pageSize", "types"],
1876
+ "events.pages": ["assetId", "cursor", "pageSize", "types"],
1518
1877
  "folders.create": ["name", "parentId"],
1519
1878
  "folders.delete": ["folderId"],
1520
- "folders.list": ["cursor", "ordering", "pageSize", "parentId", "search"],
1879
+ "folders.iterate": ["cursor", "pageSize", "parentId", "search", "sort"],
1880
+ "folders.list": ["cursor", "pageSize", "parentId", "search", "sort"],
1521
1881
  "folders.move": ["folderId", "parentId"],
1522
1882
  "folders.retrieve": ["folderId"],
1523
1883
  "folders.update": ["folderId", "name"],
1524
1884
  "hashLists.addEntry": ["assetId", "hash", "hashListId", "label", "quality"],
1525
1885
  "hashLists.create": ["action", "description", "name"],
1526
1886
  "hashLists.delete": ["hashListId"],
1527
- "hashLists.list": ["cursor", "ordering", "pageSize"],
1528
- "hashLists.listEntries": ["cursor", "hashListId", "ordering", "pageSize"],
1887
+ "hashLists.iterate": ["cursor", "pageSize", "sort"],
1888
+ "hashLists.iterateEntries": ["cursor", "hashListId", "pageSize", "sort"],
1889
+ "hashLists.list": ["cursor", "pageSize", "sort"],
1890
+ "hashLists.listEntries": ["cursor", "hashListId", "pageSize", "sort"],
1529
1891
  "hashLists.removeEntry": ["entryId"],
1530
1892
  "hashLists.retrieve": ["hashListId"],
1531
1893
  "hashLists.update": ["action", "description", "hashListId", "name"],
1532
- "policies.applyPreset": ["operation", "policyId", "presetVersion", "revision"],
1894
+ "lenses.create": ["active", "description", "identifier", "name", "transform", "type"],
1895
+ "lenses.delete": ["lensId"],
1896
+ "lenses.iterate": ["cursor", "pageSize", "sort"],
1897
+ "lenses.list": ["cursor", "pageSize", "sort"],
1898
+ "lenses.retrieve": ["lensId"],
1899
+ "lenses.update": ["active", "description", "lensId", "name", "transform", "type"],
1533
1900
  "policies.assign": ["policyId"],
1534
1901
  "policies.create": ["description", "name", "presetId", "settings"],
1535
1902
  "policies.delete": ["policyId"],
1536
- "policies.list": [],
1903
+ "policies.iterate": ["cursor", "pageSize", "sort"],
1904
+ "policies.list": ["cursor", "pageSize", "sort"],
1905
+ "policies.reset": ["policyId", "presetVersion", "revision"],
1537
1906
  "policies.retrieve": ["policyId"],
1907
+ "policies.retrieveAssigned": [],
1538
1908
  "policies.setAutomaticUpdates": ["enabled", "policyId", "presetVersion", "revision"],
1539
1909
  "policies.update": ["description", "name", "policyId", "revision", "settings"],
1540
- "text.classify": ["authorId", "context", "description", "externalId", "externalUrl", "folderId", "metadata", "name", "processingOptions", "text", "uploadPresetId", "visibility"]
1910
+ "policies.upgrade": ["policyId", "presetVersion", "revision"],
1911
+ "text.classify": ["authorId", "context", "description", "externalId", "externalUrl", "folderId", "metadata", "name", "processingOptions", "tags", "text", "uploadPresetId", "visibility"]
1912
+ };
1913
+ var NULLABLE_OPTION_KEYS = {
1914
+ "assets.classify": ["authorId", "context", "description", "externalId", "folderId", "metadata", "processingOptions", "tags", "uploadPresetId", "visibility"],
1915
+ "assets.create": ["authorId", "context", "description", "externalId", "folderId", "metadata", "processingOptions", "tags", "uploadPresetId", "visibility"],
1916
+ "assets.iterate": ["filter"],
1917
+ "assets.list": ["filter"],
1918
+ "assets.move": ["folderId"],
1919
+ "assets.update": ["description", "externalId", "externalUrl", "metadata", "tags", "visibility"],
1920
+ "folders.create": ["parentId"],
1921
+ "folders.move": ["parentId"],
1922
+ "hashLists.addEntry": ["label", "quality"],
1923
+ "hashLists.create": ["description"],
1924
+ "hashLists.update": ["description"],
1925
+ "lenses.create": ["description", "transform"],
1926
+ "lenses.update": ["description", "transform"],
1927
+ "text.classify": ["authorId", "context", "description", "externalId", "folderId", "metadata", "processingOptions", "tags", "uploadPresetId", "visibility"]
1541
1928
  };
1542
1929
 
1543
1930
  // src/contract/CryptoUtils-B_x8lMIx.js
@@ -1578,19 +1965,15 @@ var signUploadToken = async (claims, apiKey) => {
1578
1965
  var signUploadTokenWithApiKey = async (apiKey, options, { now = Date.now(), nonce = crypto.randomUUID() } = {}) => {
1579
1966
  if (!options || typeof options !== "object")
1580
1967
  throw invalidArgument("Options are required");
1581
- const {
1582
- uploadPresetId,
1583
- externalId,
1584
- expiresInSeconds = UPLOAD_TOKEN_DEFAULT_TTL_SECONDS
1585
- } = options;
1968
+ const { uploadPresetId, externalId, expiresIn = UPLOAD_TOKEN_DEFAULT_TTL_SECONDS } = options;
1586
1969
  encodePathSegment(uploadPresetId, "Upload preset ID");
1587
- if (!Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > UPLOAD_TOKEN_MAX_TTL_SECONDS) {
1588
- throw invalidArgument(`expiresInSeconds must be a whole number from 1 to ${UPLOAD_TOKEN_MAX_TTL_SECONDS}`);
1970
+ if (!Number.isInteger(expiresIn) || expiresIn < 1 || expiresIn > UPLOAD_TOKEN_MAX_TTL_SECONDS) {
1971
+ throw invalidArgument(`expiresIn must be a whole number from 1 to ${UPLOAD_TOKEN_MAX_TTL_SECONDS}`);
1589
1972
  }
1590
1973
  if (externalId !== undefined && (typeof externalId !== "string" || !externalId)) {
1591
1974
  throw invalidArgument("externalId must be a non-empty string");
1592
1975
  }
1593
- const expiresAt = now + expiresInSeconds * 1000;
1976
+ const expiresAt = now + expiresIn * 1000;
1594
1977
  const token = await signUploadToken({
1595
1978
  v: 1,
1596
1979
  u: uploadPresetId,
@@ -1665,13 +2048,15 @@ var getEnsureLensCacheKey = (options) => stringifyJsonCanonical({
1665
2048
  description: options.description ?? null,
1666
2049
  type: options.type,
1667
2050
  active: options.active,
1668
- transform: options.transform ?? null,
1669
- version: options.version
2051
+ transform: options.transform ?? null
1670
2052
  });
1671
2053
  var requireId = (value, name) => encodePathSegment(value, name);
1672
2054
  var checked = (operation, options) => {
1673
2055
  checkOptionKeys(options, operation, SERVER_OPTION_KEYS);
1674
- return options;
2056
+ if (!options || typeof options !== "object" || Array.isArray(options))
2057
+ return options;
2058
+ const nullable = NULLABLE_OPTION_KEYS[operation] ?? [];
2059
+ return Object.fromEntries(Object.entries(options).filter(([key, value]) => value !== null || nullable.includes(key)));
1675
2060
  };
1676
2061
  var assertNewCursor = (sent, cursor) => {
1677
2062
  if (sent.has(cursor)) {
@@ -1724,24 +2109,24 @@ class CalmLensServerClient {
1724
2109
  request(method, path, options = {}) {
1725
2110
  return this.#connection.json(method, path, options);
1726
2111
  }
1727
- async submitAsset(options, queue) {
2112
+ async submitAsset(options, wait) {
1728
2113
  const body = prepareSubmitAssetOptions(options, {
1729
2114
  deferUploadChecks: this.#connection.deferUploadChecks,
1730
2115
  partSizeBytes: this.#connection.partSizeBytes
1731
2116
  });
1732
2117
  const uploadsPath = `${this.projectPath}/assets`;
1733
2118
  if ("content" in body && splitsIntoParts(body.content, this.#connection.partSizeBytes)) {
1734
- return expectAsset(await this.#connection.submitInParts(uploadsPath, body, queue, {
2119
+ return expectAsset(await this.#connection.submitInParts(uploadsPath, body, wait, {
1735
2120
  partPath: (assetId) => `/assets/${encodeURIComponent(assetId)}/part`,
1736
2121
  retrieve: (assetId) => this.buildAssets().retrieve({ assetId })
1737
2122
  }));
1738
2123
  }
1739
2124
  if ("content" in body || "part" in body) {
1740
- return expectAsset(await this.#connection.submitRawUpload(uploadsPath, body, queue));
2125
+ return expectAsset(await this.#connection.submitRawUpload(uploadsPath, body, wait));
1741
2126
  }
1742
2127
  const { idempotencyKey, ...fields } = body;
1743
2128
  const data = await this.#connection.json("POST", uploadsPath, {
1744
- query: { queue },
2129
+ query: { wait },
1745
2130
  body: fields,
1746
2131
  idempotencyKey: idempotencyKey ?? newIdempotencyKey()
1747
2132
  });
@@ -1750,13 +2135,32 @@ class CalmLensServerClient {
1750
2135
  get cdn() {
1751
2136
  return {
1752
2137
  getAssetUrl: (urlOptions) => {
1753
- const { assetIdentifier, ...options } = checked("cdn.getAssetUrl", urlOptions);
1754
- const { projectId, cdnBaseUrl } = this.#settings;
1755
- return getAssetUrl({ projectId, cdnBaseUrl, assetIdentifier, ...options });
2138
+ const { projectId, ...options } = checked("cdn.getAssetUrl", urlOptions);
2139
+ return buildAssetUrl(this.#settings.cdnBaseUrl, projectId ?? this.#settings.projectId, options);
1756
2140
  },
2141
+ signAssetUrl: async (signOptions) => {
2142
+ const options = checked("cdn.signAssetUrl", signOptions);
2143
+ validateSignAssetUrlOptions(options);
2144
+ const { projectId, assetId, externalId, expiresIn, original, ...location } = options;
2145
+ const project = requireId(projectId ?? this.#settings.projectId, "Project ID");
2146
+ const signed = await this.request("POST", `/projects/${project}/signed-asset-urls`, {
2147
+ body: {
2148
+ ...assetId !== undefined ? { assetId } : { externalId },
2149
+ expiresIn: expiresIn ?? DEFAULT_SIGNED_URL_EXPIRES_IN,
2150
+ original: original ?? false
2151
+ }
2152
+ });
2153
+ if (!signed || typeof signed.url !== "string" || !signed.url || typeof signed.expiresAt !== "number") {
2154
+ throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, {
2155
+ message: "The API returned no signed asset URL"
2156
+ });
2157
+ }
2158
+ return { url: appendAssetLocation(signed.url, location), expiresAt: signed.expiresAt };
2159
+ },
2160
+ getAssetInfo: (url, options = {}) => getAssetInfo(url, { ...options, fetch: this.#settings.cdnFetch }),
1757
2161
  serve: async (options) => {
1758
- const { assetIdentifier, init, ...urlOptions } = checked("cdn.serve", options);
1759
- const url = this.cdn.getAssetUrl({ assetIdentifier, ...urlOptions });
2162
+ const { init, resource = "rendered", ...urlOptions } = checked("cdn.serve", options);
2163
+ const url = this.cdn.getAssetUrl({ ...urlOptions, resource });
1760
2164
  const method = init?.method?.toUpperCase() ?? "GET";
1761
2165
  const { response } = await this.#connection.transport.send({
1762
2166
  method,
@@ -1811,38 +2215,36 @@ class CalmLensServerClient {
1811
2215
  query
1812
2216
  });
1813
2217
  },
2218
+ listTimeline: async (options) => {
2219
+ const { assetId, ...query } = checked("assets.listTimeline", options);
2220
+ const assetPath = `${this.projectPath}/assets/${requireId(assetId, "Asset ID")}`;
2221
+ return this.request("GET", `${assetPath}/timeline`, {
2222
+ query
2223
+ });
2224
+ },
2225
+ iterateTimeline: (options) => {
2226
+ checked("assets.iterateTimeline", options);
2227
+ requireId(options?.assetId, "Asset ID");
2228
+ return this.iteratePages((cursor) => this.buildAssets().listTimeline({ ...options, cursor }));
2229
+ },
1814
2230
  iterateChildren: (options) => {
1815
2231
  checked("assets.iterateChildren", options);
1816
2232
  requireId(options?.assetId, "Asset ID");
1817
2233
  return this.iteratePages((cursor) => this.buildAssets().listChildren({ ...options, cursor }));
1818
2234
  },
1819
- create: async (options) => this.submitAsset(checked("assets.create", options), true),
1820
- classify: async (options) => {
1821
- checked("assets.classify", options);
2235
+ create: async (options) => this.submitAsset(checked("assets.create", options), false),
2236
+ classify: async (classifyOptions) => {
2237
+ const options = checked("assets.classify", classifyOptions);
1822
2238
  if (options && "content" in options && "plainText" in options.content && (typeof options.content.plainText !== "string" || !options.content.plainText.trim())) {
1823
2239
  throw invalidPayload("Text to classify must be a non-empty string");
1824
2240
  }
1825
- return this.submitAsset(options, false);
2241
+ return this.submitAsset(options, true);
1826
2242
  },
1827
2243
  uploadPart: async (partOptions) => {
1828
2244
  const { assetId, ...options } = checked("assets.uploadPart", partOptions);
1829
2245
  const encodedAssetId = requireId(assetId, "Asset ID");
1830
2246
  return expectAsset(await this.#connection.uploadPart(`/assets/${encodedAssetId}/part`, options));
1831
2247
  },
1832
- createSignedUrl: async (signedUrlOptions) => {
1833
- const { assetId, ...options } = checked("assets.createSignedUrl", signedUrlOptions);
1834
- const encodedAssetId = requireId(assetId, "Asset ID");
1835
- validateSignedUrlOptions(options);
1836
- return this.request("POST", `/assets/${encodedAssetId}/signed-url`, {
1837
- body: {
1838
- viewerClaims: options.viewerClaims,
1839
- resource: options.resource,
1840
- expiresInSeconds: options.expiresInSeconds ?? DEFAULT_SIGNED_URL_EXPIRES_IN_SECONDS,
1841
- lens: options.lens,
1842
- transform: transformSelector(options.transform)
1843
- }
1844
- });
1845
- },
1846
2248
  move: async (options) => {
1847
2249
  const { assetId, folderId } = checked("assets.move", options);
1848
2250
  return this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/move`, {
@@ -1869,8 +2271,8 @@ class CalmLensServerClient {
1869
2271
  const client = options.signal ? this.withRequestOptions({ signal: options.signal }) : this;
1870
2272
  return pollForDecision(() => client.assets.retrieve({ assetId }), options, this.#connection.sleep, this.#connection.hooks?.now);
1871
2273
  },
1872
- deleteContent: async (options) => {
1873
- const { assetId } = checked("assets.deleteContent", options);
2274
+ removeContent: async (options) => {
2275
+ const { assetId } = checked("assets.removeContent", options);
1874
2276
  return this.request("DELETE", `/assets/${requireId(assetId, "Asset ID")}/content`);
1875
2277
  },
1876
2278
  delete: async (options) => {
@@ -1888,9 +2290,12 @@ class CalmLensServerClient {
1888
2290
  }
1889
2291
  get events() {
1890
2292
  return {
1891
- list: async (options = {}) => this.request("GET", `${this.projectPath}/events`, {
1892
- query: { ...checked("events.list", options) }
1893
- }),
2293
+ list: async (options = {}) => {
2294
+ const { types, ...query } = checked("events.list", options);
2295
+ return this.request("GET", `${this.projectPath}/events`, {
2296
+ query: { ...query, types: types?.length ? types.join(",") : undefined }
2297
+ });
2298
+ },
1894
2299
  pages: (options = {}) => this.iterateEventPages(checked("events.pages", options))
1895
2300
  };
1896
2301
  }
@@ -1926,6 +2331,10 @@ class CalmLensServerClient {
1926
2331
  list: async (options = {}) => this.request("GET", `${this.projectPath}/folders`, {
1927
2332
  query: checked("folders.list", options)
1928
2333
  }),
2334
+ iterate: (options = {}) => {
2335
+ checked("folders.iterate", options);
2336
+ return this.iteratePages((cursor) => this.folders.list({ ...options, cursor }));
2337
+ },
1929
2338
  retrieve: async (options) => {
1930
2339
  const { folderId } = checked("folders.retrieve", options);
1931
2340
  return this.request("GET", `/folders/${requireId(folderId, "Folder ID")}`);
@@ -1954,6 +2363,10 @@ class CalmLensServerClient {
1954
2363
  list: async (options = {}) => this.request("GET", `${this.projectPath}/hash-lists`, {
1955
2364
  query: checked("hashLists.list", options)
1956
2365
  }),
2366
+ iterate: (options = {}) => {
2367
+ checked("hashLists.iterate", options);
2368
+ return this.iteratePages((cursor) => this.hashLists.list({ ...options, cursor }));
2369
+ },
1957
2370
  retrieve: async (options) => {
1958
2371
  const { hashListId } = checked("hashLists.retrieve", options);
1959
2372
  return this.request("GET", `/hash-lists/${requireId(hashListId, "Hash list ID")}`);
@@ -1971,6 +2384,11 @@ class CalmLensServerClient {
1971
2384
  const { hashListId } = checked("hashLists.delete", options);
1972
2385
  await this.request("DELETE", `/hash-lists/${requireId(hashListId, "Hash list ID")}`);
1973
2386
  },
2387
+ iterateEntries: (options) => {
2388
+ checked("hashLists.iterateEntries", options);
2389
+ requireId(options?.hashListId, "Hash list ID");
2390
+ return this.iteratePages((cursor) => this.hashLists.listEntries({ ...options, cursor }));
2391
+ },
1974
2392
  listEntries: async (options) => {
1975
2393
  const { hashListId, ...query } = checked("hashLists.listEntries", options);
1976
2394
  return this.request("GET", `/hash-lists/${requireId(hashListId, "Hash list ID")}/entries`, {
@@ -1988,20 +2406,26 @@ class CalmLensServerClient {
1988
2406
  };
1989
2407
  }
1990
2408
  get policies() {
1991
- const policyPath = (policyId) => `${this.projectPath}/policies/${requireId(policyId, "Policy ID")}`;
2409
+ const policyPath = (policyId) => `/policies/${requireId(policyId, "Policy ID")}`;
1992
2410
  return {
1993
- list: async () => this.request("GET", `${this.projectPath}/policies`),
2411
+ list: async (options = {}) => this.request("GET", "/policies", { query: checked("policies.list", options) }),
2412
+ iterate: (options = {}) => {
2413
+ checked("policies.iterate", options);
2414
+ return this.iteratePages((cursor) => this.policies.list({ ...options, cursor }));
2415
+ },
1994
2416
  retrieve: async (options) => this.request("GET", policyPath(checked("policies.retrieve", options).policyId)),
1995
- create: async (options) => this.request("POST", `${this.projectPath}/policies`, {
1996
- body: checked("policies.create", options)
1997
- }),
2417
+ create: async (options) => this.request("POST", "/policies", { body: checked("policies.create", options) }),
1998
2418
  update: async (options) => {
1999
2419
  const { policyId, ...body } = checked("policies.update", options);
2000
2420
  return this.request("PATCH", policyPath(policyId), { body });
2001
2421
  },
2002
- applyPreset: async (options) => {
2003
- const { policyId, ...body } = checked("policies.applyPreset", options);
2004
- return this.request("POST", `${policyPath(policyId)}/preset`, { body });
2422
+ reset: async (options) => {
2423
+ const { policyId, ...body } = checked("policies.reset", options);
2424
+ return this.request("POST", `${policyPath(policyId)}/reset`, { body });
2425
+ },
2426
+ upgrade: async (options) => {
2427
+ const { policyId, ...body } = checked("policies.upgrade", options);
2428
+ return this.request("POST", `${policyPath(policyId)}/upgrade`, { body });
2005
2429
  },
2006
2430
  setAutomaticUpdates: async (options) => {
2007
2431
  const { policyId, ...body } = checked("policies.setAutomaticUpdates", options);
@@ -2010,11 +2434,48 @@ class CalmLensServerClient {
2010
2434
  delete: async (options) => {
2011
2435
  await this.request("DELETE", policyPath(checked("policies.delete", options).policyId));
2012
2436
  },
2437
+ retrieveAssigned: async () => this.request("GET", `${this.projectPath}/policy`),
2013
2438
  assign: async (options) => this.request("PUT", `${this.projectPath}/policy`, {
2014
2439
  body: checked("policies.assign", options)
2015
2440
  })
2016
2441
  };
2017
2442
  }
2443
+ get lenses() {
2444
+ const lensPath = (lensId) => `/lenses/${requireId(lensId, "Lens ID")}`;
2445
+ const forget = (matches) => {
2446
+ for (const [cacheKey, lens] of this.#lenses.ensuredLenses)
2447
+ if (matches(lens))
2448
+ this.#lenses.ensuredLenses.delete(cacheKey);
2449
+ };
2450
+ return {
2451
+ list: async (options = {}) => this.request("GET", `${this.projectPath}/lenses`, {
2452
+ query: checked("lenses.list", options)
2453
+ }),
2454
+ iterate: (options = {}) => {
2455
+ checked("lenses.iterate", options);
2456
+ return this.iteratePages((cursor) => this.lenses.list({ ...options, cursor }));
2457
+ },
2458
+ create: async (options) => {
2459
+ const lens = await this.request("POST", `${this.projectPath}/lenses`, {
2460
+ body: checked("lenses.create", options)
2461
+ });
2462
+ forget((cached) => cached.identifier === lens.identifier);
2463
+ return lens;
2464
+ },
2465
+ retrieve: async (options) => this.request("GET", lensPath(checked("lenses.retrieve", options).lensId)),
2466
+ update: async (options) => {
2467
+ const { lensId, ...body } = checked("lenses.update", options);
2468
+ const lens = await this.request("PATCH", lensPath(lensId), { body });
2469
+ forget((cached) => cached.id === lens.id);
2470
+ return lens;
2471
+ },
2472
+ delete: async (options) => {
2473
+ const { lensId } = checked("lenses.delete", options);
2474
+ await this.request("DELETE", lensPath(lensId));
2475
+ forget((cached) => cached.id === lensId);
2476
+ }
2477
+ };
2478
+ }
2018
2479
  async ensureLens(options) {
2019
2480
  checked("ensureLens", options);
2020
2481
  if (!options?.identifier)
@@ -4007,39 +4468,162 @@ function handleIntersectionResults(result, left, right) {
4007
4468
  } else {
4008
4469
  return false;
4009
4470
  }
4010
- for (const k of keys) {
4011
- if (!unrecKeys.has(k))
4012
- unrecKeys.set(k, {});
4013
- unrecKeys.get(k)[side] = true;
4471
+ for (const k of keys) {
4472
+ if (!unrecKeys.has(k))
4473
+ unrecKeys.set(k, {});
4474
+ unrecKeys.get(k)[side] = true;
4475
+ }
4476
+ return true;
4477
+ };
4478
+ for (const iss of left.issues) {
4479
+ if (!collect(iss, "l"))
4480
+ result.issues.push(iss);
4481
+ }
4482
+ for (const iss of right.issues) {
4483
+ if (!collect(iss, "r"))
4484
+ result.issues.push(iss);
4485
+ }
4486
+ const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
4487
+ if (bothKeys.length) {
4488
+ const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];
4489
+ if (aggregated.length)
4490
+ result.issues.push({ ...unrecIssue, keys: aggregated });
4491
+ for (const k of bothKeys) {
4492
+ if (!aggregated.includes(k) && keyIssues.has(k))
4493
+ result.issues.push(keyIssues.get(k));
4494
+ }
4495
+ }
4496
+ const merged = mergeValues(left.value, right.value);
4497
+ if (!merged.valid) {
4498
+ if (aborted(result))
4499
+ return result;
4500
+ throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
4501
+ }
4502
+ result.value = merged.data;
4503
+ return result;
4504
+ }
4505
+ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
4506
+ $ZodType.init(inst, def);
4507
+ const items = def.items;
4508
+ const memo = globalConfig.memoizer;
4509
+ memo?.attach(inst);
4510
+ inst._zod.parse = (payload, ctx) => {
4511
+ const input = payload.value;
4512
+ if (!Array.isArray(input)) {
4513
+ payload.issues.push({
4514
+ input,
4515
+ inst,
4516
+ expected: "tuple",
4517
+ code: "invalid_type"
4518
+ });
4519
+ return payload;
4520
+ }
4521
+ payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];
4522
+ const proms = [];
4523
+ const optinStart = getTupleOptStart(items, "optin");
4524
+ const optoutStart = getTupleOptStart(items, "optout");
4525
+ if (!def.rest) {
4526
+ if (input.length < optinStart) {
4527
+ payload.issues.push({
4528
+ code: "too_small",
4529
+ minimum: optinStart,
4530
+ inclusive: true,
4531
+ input,
4532
+ inst,
4533
+ origin: "array"
4534
+ });
4535
+ return payload;
4536
+ }
4537
+ if (input.length > items.length) {
4538
+ payload.issues.push({
4539
+ code: "too_big",
4540
+ maximum: items.length,
4541
+ inclusive: true,
4542
+ input,
4543
+ inst,
4544
+ origin: "array"
4545
+ });
4546
+ }
4547
+ }
4548
+ const itemResults = new Array(items.length);
4549
+ const abortEarly = def.rest ? ctx?.abortEarly : undefined;
4550
+ let itemAborted = false;
4551
+ for (let i = 0;i < items.length; i++) {
4552
+ const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);
4553
+ if (r instanceof Promise) {
4554
+ proms.push(r.then((rr) => {
4555
+ itemResults[i] = rr;
4556
+ }));
4557
+ } else {
4558
+ itemResults[i] = r;
4559
+ if (abortEarly && !itemAborted && r.issues.length)
4560
+ itemAborted = aborted(r);
4561
+ }
4562
+ }
4563
+ if (def.rest && !itemAborted) {
4564
+ let i = items.length - 1;
4565
+ const rest = input.slice(items.length);
4566
+ let seen = payload.issues.length;
4567
+ for (const el of rest) {
4568
+ if (abortEarly && payload.issues.length !== seen) {
4569
+ if (aborted(payload, seen))
4570
+ break;
4571
+ seen = payload.issues.length;
4572
+ }
4573
+ i++;
4574
+ const result = def.rest._zod.run({ value: el, issues: [] }, ctx);
4575
+ if (result instanceof Promise) {
4576
+ proms.push(result.then((r) => handleTupleResult(r, payload, i)));
4577
+ } else {
4578
+ handleTupleResult(result, payload, i);
4579
+ }
4580
+ }
4014
4581
  }
4015
- return true;
4582
+ if (proms.length) {
4583
+ return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));
4584
+ }
4585
+ return handleTupleResults(itemResults, payload, items, input, optoutStart);
4016
4586
  };
4017
- for (const iss of left.issues) {
4018
- if (!collect(iss, "l"))
4019
- result.issues.push(iss);
4587
+ });
4588
+ function getTupleOptStart(items, key) {
4589
+ for (let i = items.length - 1;i >= 0; i--) {
4590
+ const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional";
4591
+ if (!omittable)
4592
+ return i + 1;
4020
4593
  }
4021
- for (const iss of right.issues) {
4022
- if (!collect(iss, "r"))
4023
- result.issues.push(iss);
4594
+ return 0;
4595
+ }
4596
+ function handleTupleResult(result, final, index) {
4597
+ if (result.issues.length) {
4598
+ final.issues.push(...prefixIssues(index, result.issues));
4024
4599
  }
4025
- const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
4026
- if (bothKeys.length) {
4027
- const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];
4028
- if (aggregated.length)
4029
- result.issues.push({ ...unrecIssue, keys: aggregated });
4030
- for (const k of bothKeys) {
4031
- if (!aggregated.includes(k) && keyIssues.has(k))
4032
- result.issues.push(keyIssues.get(k));
4600
+ final.value[index] = result.value;
4601
+ }
4602
+ function handleTupleResults(itemResults, final, items, input, optoutStart) {
4603
+ for (let i = 0;i < items.length; i++) {
4604
+ const r = itemResults[i];
4605
+ const isPresent = i < input.length;
4606
+ if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") {
4607
+ final.value.length = i;
4608
+ break;
4609
+ }
4610
+ if (r.issues.length) {
4611
+ if (!isPresent && i >= optoutStart) {
4612
+ final.value.length = i;
4613
+ break;
4614
+ }
4615
+ final.issues.push(...prefixIssues(i, r.issues));
4033
4616
  }
4617
+ final.value[i] = r.value;
4034
4618
  }
4035
- const merged = mergeValues(left.value, right.value);
4036
- if (!merged.valid) {
4037
- if (aborted(result))
4038
- return result;
4039
- throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
4619
+ for (let i = final.value.length - 1;i >= input.length; i--) {
4620
+ if (items[i]._zod.optout === "optional" && final.value[i] === undefined) {
4621
+ final.value.length = i;
4622
+ } else {
4623
+ break;
4624
+ }
4040
4625
  }
4041
- result.value = merged.data;
4042
- return result;
4626
+ return final;
4043
4627
  }
4044
4628
  var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
4045
4629
  $ZodType.init(inst, def);
@@ -4064,6 +4648,28 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
4064
4648
  return payload;
4065
4649
  };
4066
4650
  });
4651
+ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
4652
+ $ZodType.init(inst, def);
4653
+ const values = new Set(def.values);
4654
+ inst._zod.values = values;
4655
+ defineLazyInternal(inst, "pattern", (zod) => {
4656
+ const vals = zod.def.values;
4657
+ return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$");
4658
+ });
4659
+ inst._zod.parse = (payload, _ctx) => {
4660
+ const input = payload.value;
4661
+ if (values.has(input)) {
4662
+ return payload;
4663
+ }
4664
+ payload.issues.push({
4665
+ code: "invalid_value",
4666
+ values: def.values,
4667
+ input,
4668
+ inst
4669
+ });
4670
+ return payload;
4671
+ };
4672
+ });
4067
4673
  var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
4068
4674
  $ZodType.init(inst, def);
4069
4675
  inst._zod.optin = "optional";
@@ -5580,6 +6186,45 @@ var enumProcessor = (schema, _ctx, json, _params) => {
5580
6186
  json.type = "string";
5581
6187
  json.enum = values;
5582
6188
  };
6189
+ var literalProcessor = (schema, ctx, json, params) => {
6190
+ const def = schema._zod.def;
6191
+ if (def.values.length === 0) {
6192
+ json.not = {};
6193
+ return;
6194
+ }
6195
+ const vals = [];
6196
+ for (const val of def.values) {
6197
+ if (val === undefined) {
6198
+ if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema"))
6199
+ return;
6200
+ } else if (typeof val === "bigint") {
6201
+ if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema"))
6202
+ return;
6203
+ vals.push(Number(val));
6204
+ } else {
6205
+ vals.push(val);
6206
+ }
6207
+ }
6208
+ if (vals.length === 0) {} else if (vals.length === 1) {
6209
+ const val = vals[0];
6210
+ json.type = val === null ? "null" : typeof val;
6211
+ if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
6212
+ json.enum = [val];
6213
+ } else {
6214
+ json.const = val;
6215
+ }
6216
+ } else {
6217
+ if (vals.every((v) => typeof v === "number"))
6218
+ json.type = "number";
6219
+ if (vals.every((v) => typeof v === "string"))
6220
+ json.type = "string";
6221
+ if (vals.every((v) => typeof v === "boolean"))
6222
+ json.type = "boolean";
6223
+ if (vals.every((v) => v === null))
6224
+ json.type = "null";
6225
+ json.enum = vals;
6226
+ }
6227
+ };
5583
6228
  var customProcessor = (schema, ctx, json, params) => {
5584
6229
  handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema");
5585
6230
  };
@@ -5679,6 +6324,70 @@ var intersectionProcessor = (schema, ctx, json, params) => {
5679
6324
  json.allOf = allOf;
5680
6325
  ctx.intersections.push(allOf);
5681
6326
  };
6327
+ var tupleProcessor = (schema, ctx, _json, params) => {
6328
+ const json = _json;
6329
+ const def = schema._zod.def;
6330
+ json.type = "array";
6331
+ const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
6332
+ const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
6333
+ const prefixItems = def.items.map((x, i) => processSchema(x, ctx, {
6334
+ ...params,
6335
+ path: [...params.path, prefixPath, i]
6336
+ }));
6337
+ const rest = def.rest ? processSchema(def.rest, ctx, {
6338
+ ...params,
6339
+ path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []]
6340
+ }) : null;
6341
+ let minItems = def.items.length;
6342
+ while (minItems > 0) {
6343
+ const item = def.items[minItems - 1];
6344
+ const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional";
6345
+ if (!optional)
6346
+ break;
6347
+ minItems--;
6348
+ }
6349
+ const maxItems = def.items.length;
6350
+ const isClosed = !def.rest;
6351
+ if (ctx.target === "draft-2020-12") {
6352
+ json.prefixItems = prefixItems;
6353
+ if (isClosed) {
6354
+ json.items = false;
6355
+ } else if (rest) {
6356
+ json.items = rest;
6357
+ }
6358
+ if (minItems > 0)
6359
+ json.minItems = minItems;
6360
+ if (isClosed)
6361
+ json.maxItems = maxItems;
6362
+ } else if (ctx.target === "openapi-3.0") {
6363
+ json.items = {
6364
+ anyOf: prefixItems
6365
+ };
6366
+ if (rest) {
6367
+ json.items.anyOf.push(rest);
6368
+ }
6369
+ if (minItems > 0)
6370
+ json.minItems = minItems;
6371
+ if (isClosed)
6372
+ json.maxItems = maxItems;
6373
+ } else {
6374
+ json.items = prefixItems;
6375
+ if (isClosed) {
6376
+ json.additionalItems = false;
6377
+ } else if (rest) {
6378
+ json.additionalItems = rest;
6379
+ }
6380
+ if (minItems > 0)
6381
+ json.minItems = minItems;
6382
+ if (isClosed)
6383
+ json.maxItems = maxItems;
6384
+ }
6385
+ const { minimum, maximum } = aggregateChecks(schema);
6386
+ if (typeof minimum === "number")
6387
+ json.minItems = minimum;
6388
+ if (typeof maximum === "number")
6389
+ json.maxItems = maximum;
6390
+ };
5682
6391
  var pendingRecords = new WeakMap;
5683
6392
  var nullableProcessor = (schema, ctx, json, params) => {
5684
6393
  const def = schema._zod.def;
@@ -6214,6 +6923,39 @@ function intersection(left, right) {
6214
6923
  right
6215
6924
  });
6216
6925
  }
6926
+ var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => {
6927
+ _ensureDefaultMemoizer();
6928
+ $ZodTuple.init(inst, def);
6929
+ ZodType.init(inst, def);
6930
+ inst._zod.processJSONSchema = (ctx, json, params) => tupleProcessor(inst, ctx, json, params);
6931
+ }, {
6932
+ rest(rest) {
6933
+ return this.clone({
6934
+ ...this._zod.def,
6935
+ rest
6936
+ });
6937
+ },
6938
+ partial() {
6939
+ const def = this._zod.def;
6940
+ if (def.checks?.length)
6941
+ throw new Error(".partial() cannot be used on tuple schemas containing refinements");
6942
+ return this.clone({
6943
+ ...def,
6944
+ items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item }))
6945
+ });
6946
+ }
6947
+ });
6948
+ function tuple(items, _paramsOrRest, _params) {
6949
+ const hasRest = _paramsOrRest instanceof $ZodType;
6950
+ const params = hasRest ? _params : _paramsOrRest;
6951
+ const rest = hasRest ? _paramsOrRest : null;
6952
+ return new ZodTuple({
6953
+ type: "tuple",
6954
+ items,
6955
+ rest,
6956
+ ...normalizeParams(params)
6957
+ });
6958
+ }
6217
6959
  var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
6218
6960
  $ZodEnum.init(inst, def);
6219
6961
  ZodType.init(inst, def);
@@ -6260,6 +7002,27 @@ function _enum(values, params) {
6260
7002
  ...normalizeParams(params)
6261
7003
  });
6262
7004
  }
7005
+ var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
7006
+ $ZodLiteral.init(inst, def);
7007
+ ZodType.init(inst, def);
7008
+ inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params);
7009
+ inst.values = new Set(def.values);
7010
+ Object.defineProperty(inst, "value", {
7011
+ get() {
7012
+ if (def.values.length > 1) {
7013
+ throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
7014
+ }
7015
+ return def.values[0];
7016
+ }
7017
+ });
7018
+ });
7019
+ function literal(value, params) {
7020
+ return new ZodLiteral({
7021
+ type: "literal",
7022
+ values: Array.isArray(value) ? value : [value],
7023
+ ...normalizeParams(params)
7024
+ });
7025
+ }
6263
7026
  var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
6264
7027
  _ensureDefaultMemoizer();
6265
7028
  $ZodTransform.init(inst, def);
@@ -6432,7 +7195,7 @@ function superRefine(fn, params) {
6432
7195
  return _superRefine(fn, params);
6433
7196
  }
6434
7197
 
6435
- // src/contract/Jurisdiction-DF7spSE4.js
7198
+ // src/contract/Jurisdiction-DnnDdNKC.js
6436
7199
  var JURISDICTIONS = {
6437
7200
  global: {
6438
7201
  name: "Global",
@@ -6485,10 +7248,10 @@ var VIEWER_REGION_SCHEMA = _enum([...COUNTRIES]).describe("Viewer's ISO 3166-1 a
6485
7248
  var EU_COUNTRIES2 = new Set("AT BE BG HR CY CZ DK EE FI FR DE GR HU IE IT LV LT LU MT NL PL PT RO SK SI ES SE".split(" "));
6486
7249
  var VIEWER_CLAIMS_SCHEMA = object({
6487
7250
  region: VIEWER_REGION_SCHEMA.optional().describe("Viewer country. Defaults to the country of the connection reaching CalmLens; proxies should forward the viewer country explicitly."),
6488
- ageConfirmed: boolean2().optional().describe("Your platform's confirmation that the viewer passed its age check, so age-restricted content may be delivered. Defaults to false. Your platform confirms the viewer's age; CalmLens does not verify this claim. Anyone requesting a public asset's URL can set it, so it is not an access control: to restrict who can load an age-restricted asset, make the asset private and include the claim in a signed URL, whose signature covers it.")
7251
+ ageConfirmed: boolean2().optional().describe("Your platform's confirmation that the viewer passed its age check, so age-restricted content may be delivered. Defaults to false. Your platform confirms the viewer's age; CalmLens does not verify this claim. Anyone requesting an asset's URL, public or signed, can set it: a signed URL's signature does not cover viewer claims, so the claim is not an access control. To restrict who can load an age-restricted asset, make it private and issue signed URLs only to viewers who passed your age check.")
6489
7252
  }).strict();
6490
7253
 
6491
- // src/contract/TestRegionalActions-6yfnXdpa.js
7254
+ // src/contract/TestRegionalActions-DPNhFf9c.js
6492
7255
  var msg = (text) => text;
6493
7256
  var MODERATION_QUALIFIER_INFO = {
6494
7257
  "sexual-pornographic-media": {
@@ -6785,6 +7548,24 @@ var MODERATION_QUALIFIER_INFO = {
6785
7548
  description: msg("Pornographic content showing or describing sex with an animal or with a dead body, or a sexual act that threatens a person's life or is likely to cause serious injury to the anus, breasts or genitals, including realistic drawn or generated depictions."),
6786
7549
  exclusions: "Consensual adult content without such an act, including bondage, role play or rough play; non-sexual images of animals, death or injury; reports, education, support or discussion that present no such material."
6787
7550
  },
7551
+ "sexual-strangulation": {
7552
+ category: "sexual",
7553
+ kind: "harm",
7554
+ harmOption: false,
7555
+ displayName: msg("Pornographic strangulation or suffocation"),
7556
+ description: msg("A pornographic image or video frame showing a person strangling, choking or suffocating another: pressure on the neck from a hand, arm or ligature, or breathing blocked by covering the mouth and nose, smothering or compressing the chest. Realistic staged, generated or computer-made depictions count."),
7557
+ exclusions: "A person alone in the image holding their own throat or miming being choked; a hand resting on the shoulder, jaw or chest without gripping the throat; collars and choker jewellery; oral sex, including gagging, without breathing deliberately held off; non-sexual violence, combat sport or medical images; drawings or animation that don't look real; reports, education or support that show no such image.",
7558
+ inputs: ["image"]
7559
+ },
7560
+ "sexual-incest": {
7561
+ category: "sexual",
7562
+ kind: "harm",
7563
+ harmOption: false,
7564
+ displayName: msg("Pornographic incest"),
7565
+ description: msg("A pornographic image or video frame showing sexual activity between people who are, or are presented as, related as parent, grandparent, child, grandchild, brother, sister, half-brother, half-sister, uncle, aunt, nephew or niece, including by adoption. The relationship can be shown by the image or by its caption, title, dialogue or other accompanying text. Realistic staged, generated or computer-made depictions count."),
7566
+ exclusions: "Step, foster and in-law relationships between adults; a family word that is plainly a nickname or fanciful, such as daddy between adult partners; drawings or animation that don't look real; non-sexual family images; reports or discussion that show no such image. Someone presented as under 18 is Sexualised minors.",
7567
+ inputs: ["image"]
7568
+ },
6788
7569
  "sexual-minors": {
6789
7570
  category: "sexual",
6790
7571
  kind: "harm",
@@ -7488,7 +8269,7 @@ var TEST_REGIONAL_ACTIONS_SCHEMA = array(object({
7488
8269
  ])
7489
8270
  }).strict()).max(7).refine((entries) => new Set(entries.map((entry) => entry.region)).size === entries.length, "Choose each region once");
7490
8271
 
7491
- // src/contract/TestTriggers-CMwMrbjy.js
8272
+ // src/contract/TestTriggers-BTyXtX0Q.js
7492
8273
  var TEST_IMAGE_GRID_LEVELS = [
7493
8274
  72,
7494
8275
  128,
@@ -7544,7 +8325,7 @@ function testInputForSignal(signal, kind = "text") {
7544
8325
  case "violence.graphic":
7545
8326
  return { instances: [{
7546
8327
  category: "violence",
7547
- qualifiers: ["violence-graphic"]
8328
+ qualifiers: ["violence-injury", "violence-graphic"]
7548
8329
  }] };
7549
8330
  default:
7550
8331
  return TEST_INPUT_SCHEMA.parse({ instances: [{
@@ -7553,6 +8334,32 @@ function testInputForSignal(signal, kind = "text") {
7553
8334
  }] });
7554
8335
  }
7555
8336
  }
8337
+ var TEST_DETECTION_BOX_MAX = 1e4;
8338
+ var basisPoints = number2().int().min(0).max(TEST_DETECTION_BOX_MAX);
8339
+ var detectionShape = {
8340
+ box: tuple([
8341
+ basisPoints,
8342
+ basisPoints,
8343
+ basisPoints,
8344
+ basisPoints
8345
+ ]),
8346
+ confidence: number2().int().min(0).max(100).optional()
8347
+ };
8348
+ var fitsImage = ({ box: [left, top, width, height] }) => left + width <= 1e4 && top + height <= 1e4;
8349
+ var BOX_MESSAGE = msg("A box must lie inside the image: left + width and top + height are at most 10000.");
8350
+ var ageYears = number2().int().min(0).max(120);
8351
+ var TEST_DETECTED_PERSON_SCHEMA = object(detectionShape).strict().refine(fitsImage, BOX_MESSAGE);
8352
+ var TEST_DETECTED_FACE_SCHEMA = object({
8353
+ ...detectionShape,
8354
+ age: union([_enum(["adult", "minor"]), object({
8355
+ low: ageYears,
8356
+ high: ageYears
8357
+ }).strict().refine(({ low, high }) => low <= high, msg("An age range's low must not be above its high."))]).optional()
8358
+ }).strict().refine(fitsImage, BOX_MESSAGE);
8359
+ var TEST_DETECTIONS_SCHEMA = object({
8360
+ people: union([array(TEST_DETECTED_PERSON_SCHEMA).max(32), literal("unavailable")]).optional(),
8361
+ faces: union([array(TEST_DETECTED_FACE_SCHEMA).max(32), literal("unavailable")]).optional()
8362
+ }).strict();
7556
8363
  var TEST_INPUT_SCHEMA = object({
7557
8364
  regionalActions: TEST_REGIONAL_ACTIONS_SCHEMA.optional(),
7558
8365
  unassessedCategories: array(_enum(CLASSIFICATION_CATEGORIES)).max(CLASSIFICATION_CATEGORIES.length).optional(),
@@ -7572,7 +8379,8 @@ var TEST_INPUT_SCHEMA = object({
7572
8379
  code: "custom",
7573
8380
  message: "Choose unique content qualifiers from this category; input-type facts are automatic."
7574
8381
  });
7575
- })).max(128)
8382
+ })).max(128),
8383
+ detections: TEST_DETECTIONS_SCHEMA.optional()
7576
8384
  }).strict().superRefine((scenario, context) => {
7577
8385
  if (scenario.instances.some((instance) => instance.action !== undefined) && scenario.instances.some((instance) => instance.action === undefined))
7578
8386
  context.addIssue({
@@ -7627,13 +8435,124 @@ var TEST_INPUT_PRESETS = {
7627
8435
  }, {
7628
8436
  category: "harassment",
7629
8437
  qualifiers: ["harassment-threat"]
7630
- }] }
8438
+ }] },
8439
+ oneFace: {
8440
+ instances: [],
8441
+ detections: {
8442
+ people: [{ box: [
8443
+ 2500,
8444
+ 1500,
8445
+ 5000,
8446
+ 8500
8447
+ ] }],
8448
+ faces: [{ box: [
8449
+ 3500,
8450
+ 2000,
8451
+ 3000,
8452
+ 3500
8453
+ ] }]
8454
+ }
8455
+ },
8456
+ noFace: {
8457
+ instances: [],
8458
+ detections: {
8459
+ people: [],
8460
+ faces: []
8461
+ }
8462
+ },
8463
+ adultFace: {
8464
+ instances: [],
8465
+ detections: {
8466
+ people: [{ box: [
8467
+ 2500,
8468
+ 1500,
8469
+ 5000,
8470
+ 8500
8471
+ ] }],
8472
+ faces: [{
8473
+ box: [
8474
+ 3500,
8475
+ 2000,
8476
+ 3000,
8477
+ 3500
8478
+ ],
8479
+ age: "adult"
8480
+ }]
8481
+ }
8482
+ },
8483
+ minorFace: {
8484
+ instances: [],
8485
+ detections: {
8486
+ people: [{ box: [
8487
+ 2500,
8488
+ 1500,
8489
+ 5000,
8490
+ 8500
8491
+ ] }],
8492
+ faces: [{
8493
+ box: [
8494
+ 3500,
8495
+ 2000,
8496
+ 3000,
8497
+ 3500
8498
+ ],
8499
+ age: "minor"
8500
+ }]
8501
+ }
8502
+ },
8503
+ group: {
8504
+ instances: [],
8505
+ detections: {
8506
+ people: [
8507
+ { box: [
8508
+ 500,
8509
+ 2000,
8510
+ 2800,
8511
+ 8000
8512
+ ] },
8513
+ { box: [
8514
+ 3600,
8515
+ 2000,
8516
+ 2800,
8517
+ 8000
8518
+ ] },
8519
+ { box: [
8520
+ 6700,
8521
+ 2000,
8522
+ 2800,
8523
+ 8000
8524
+ ] }
8525
+ ],
8526
+ faces: [
8527
+ { box: [
8528
+ 1200,
8529
+ 2500,
8530
+ 1400,
8531
+ 2000
8532
+ ] },
8533
+ { box: [
8534
+ 4300,
8535
+ 2500,
8536
+ 1400,
8537
+ 2000
8538
+ ] },
8539
+ { box: [
8540
+ 7400,
8541
+ 2500,
8542
+ 1400,
8543
+ 2000
8544
+ ] }
8545
+ ]
8546
+ }
8547
+ }
7631
8548
  };
7632
- var tag = async (payload, key) => (await hmacSha256Hex(key, `calmlens-test:v1:${payload}`)).slice(0, 32);
8549
+ var tag = async (payload, key) => (await hmacSha256Hex(key, `calmlens-test:v2:${payload}`)).slice(0, 32);
8550
+ var toBase64Url2 = (bytes) => btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
8551
+ var envelope = (scenario) => new TextEncoder().encode(JSON.stringify(TEST_INPUT_SCHEMA.parse(scenario)));
7633
8552
  async function generateTestTextCode(scenario, key) {
7634
8553
  if (!/^[a-f0-9]{32}$/.test(key))
7635
8554
  throw new TypeError("Invalid test input key");
7636
- const payload = btoa(JSON.stringify(TEST_INPUT_SCHEMA.parse(typeof scenario === "string" ? testInputForSignal(scenario) : scenario))).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
8555
+ const payload = toBase64Url2(envelope(typeof scenario === "string" ? testInputForSignal(scenario) : scenario));
7637
8556
  if (payload.length > 8000)
7638
8557
  throw new RangeError("Test scenario is too large");
7639
8558
  return `<!calmlens-test ${await tag(payload, key)} ${payload}>`;
@@ -7641,7 +8560,7 @@ async function generateTestTextCode(scenario, key) {
7641
8560
  // src/cli/listen.ts
7642
8561
  import { randomBytes } from "node:crypto";
7643
8562
 
7644
- // src/contract/Ids-D2XfVlL6.js
8563
+ // src/contract/Ids-BESMSxGb.js
7645
8564
  var __defProp = Object.defineProperty;
7646
8565
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
7647
8566
  var __exportAll = (all, no_symbols) => {
@@ -10847,8 +11766,8 @@ var $ZodTuple2 = /* @__PURE__ */ $constructor2("$ZodTuple", (inst, def) => {
10847
11766
  }
10848
11767
  payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];
10849
11768
  const proms = [];
10850
- const optinStart = getTupleOptStart(items, "optin");
10851
- const optoutStart = getTupleOptStart(items, "optout");
11769
+ const optinStart = getTupleOptStart2(items, "optin");
11770
+ const optoutStart = getTupleOptStart2(items, "optout");
10852
11771
  if (!def.rest) {
10853
11772
  if (input.length < optinStart) {
10854
11773
  payload.issues.push({
@@ -10905,28 +11824,28 @@ var $ZodTuple2 = /* @__PURE__ */ $constructor2("$ZodTuple", (inst, def) => {
10905
11824
  issues: []
10906
11825
  }, ctx);
10907
11826
  if (result instanceof Promise)
10908
- proms.push(result.then((r) => handleTupleResult(r, payload, i)));
11827
+ proms.push(result.then((r) => handleTupleResult2(r, payload, i)));
10909
11828
  else
10910
- handleTupleResult(result, payload, i);
11829
+ handleTupleResult2(result, payload, i);
10911
11830
  }
10912
11831
  }
10913
11832
  if (proms.length)
10914
- return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));
10915
- return handleTupleResults(itemResults, payload, items, input, optoutStart);
11833
+ return Promise.all(proms).then(() => handleTupleResults2(itemResults, payload, items, input, optoutStart));
11834
+ return handleTupleResults2(itemResults, payload, items, input, optoutStart);
10916
11835
  };
10917
11836
  });
10918
- function getTupleOptStart(items, key) {
11837
+ function getTupleOptStart2(items, key) {
10919
11838
  for (let i = items.length - 1;i >= 0; i--)
10920
11839
  if (!(key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional"))
10921
11840
  return i + 1;
10922
11841
  return 0;
10923
11842
  }
10924
- function handleTupleResult(result, final, index) {
11843
+ function handleTupleResult2(result, final, index) {
10925
11844
  if (result.issues.length)
10926
11845
  final.issues.push(...prefixIssues2(index, result.issues));
10927
11846
  final.value[index] = result.value;
10928
11847
  }
10929
- function handleTupleResults(itemResults, final, items, input, optoutStart) {
11848
+ function handleTupleResults2(itemResults, final, items, input, optoutStart) {
10930
11849
  for (let i = 0;i < items.length; i++) {
10931
11850
  const r = itemResults[i];
10932
11851
  const isPresent = i < input.length;
@@ -14293,7 +15212,7 @@ var schemas_exports = /* @__PURE__ */ __exportAll({
14293
15212
  ZodJWT: () => ZodJWT,
14294
15213
  ZodKSUID: () => ZodKSUID,
14295
15214
  ZodLazy: () => ZodLazy,
14296
- ZodLiteral: () => ZodLiteral,
15215
+ ZodLiteral: () => ZodLiteral2,
14297
15216
  ZodMAC: () => ZodMAC,
14298
15217
  ZodMap: () => ZodMap,
14299
15218
  ZodNaN: () => ZodNaN,
@@ -14319,7 +15238,7 @@ var schemas_exports = /* @__PURE__ */ __exportAll({
14319
15238
  ZodSymbol: () => ZodSymbol,
14320
15239
  ZodTemplateLiteral: () => ZodTemplateLiteral,
14321
15240
  ZodTransform: () => ZodTransform2,
14322
- ZodTuple: () => ZodTuple,
15241
+ ZodTuple: () => ZodTuple2,
14323
15242
  ZodType: () => ZodType2,
14324
15243
  ZodULID: () => ZodULID,
14325
15244
  ZodURL: () => ZodURL,
@@ -14380,7 +15299,7 @@ var schemas_exports = /* @__PURE__ */ __exportAll({
14380
15299
  keyof: () => keyof,
14381
15300
  ksuid: () => ksuid2,
14382
15301
  lazy: () => lazy,
14383
- literal: () => literal,
15302
+ literal: () => literal2,
14384
15303
  looseObject: () => looseObject,
14385
15304
  looseRecord: () => looseRecord,
14386
15305
  mac: () => mac2,
@@ -14415,7 +15334,7 @@ var schemas_exports = /* @__PURE__ */ __exportAll({
14415
15334
  symbol: () => symbol,
14416
15335
  templateLiteral: () => templateLiteral,
14417
15336
  transform: () => transform2,
14418
- tuple: () => tuple,
15337
+ tuple: () => tuple2,
14419
15338
  uint32: () => uint32,
14420
15339
  uint64: () => uint64,
14421
15340
  ulid: () => ulid2,
@@ -15349,7 +16268,7 @@ function intersection2(left, right) {
15349
16268
  right
15350
16269
  });
15351
16270
  }
15352
- var ZodTuple = /* @__PURE__ */ $constructor2("ZodTuple", (inst, def) => {
16271
+ var ZodTuple2 = /* @__PURE__ */ $constructor2("ZodTuple", (inst, def) => {
15353
16272
  _ensureDefaultMemoizer2();
15354
16273
  $ZodTuple2.init(inst, def);
15355
16274
  ZodType2.init(inst, def);
@@ -15374,9 +16293,9 @@ var ZodTuple = /* @__PURE__ */ $constructor2("ZodTuple", (inst, def) => {
15374
16293
  });
15375
16294
  }
15376
16295
  });
15377
- function tuple(items, _paramsOrRest, _params) {
16296
+ function tuple2(items, _paramsOrRest, _params) {
15378
16297
  const hasRest = _paramsOrRest instanceof $ZodType2;
15379
- return new ZodTuple({
16298
+ return new ZodTuple2({
15380
16299
  type: "tuple",
15381
16300
  items,
15382
16301
  rest: hasRest ? _paramsOrRest : null,
@@ -15512,7 +16431,7 @@ function nativeEnum(entries, params) {
15512
16431
  ...normalizeParams2(params)
15513
16432
  });
15514
16433
  }
15515
- var ZodLiteral = /* @__PURE__ */ $constructor2("ZodLiteral", (inst, def) => {
16434
+ var ZodLiteral2 = /* @__PURE__ */ $constructor2("ZodLiteral", (inst, def) => {
15516
16435
  $ZodLiteral2.init(inst, def);
15517
16436
  ZodType2.init(inst, def);
15518
16437
  inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor2(inst, ctx, json, params);
@@ -15523,8 +16442,8 @@ var ZodLiteral = /* @__PURE__ */ $constructor2("ZodLiteral", (inst, def) => {
15523
16442
  return def.values[0];
15524
16443
  } });
15525
16444
  });
15526
- function literal(value, params) {
15527
- return new ZodLiteral({
16445
+ function literal2(value, params) {
16446
+ return new ZodLiteral2({
15528
16447
  type: "literal",
15529
16448
  values: Array.isArray(value) ? value : [value],
15530
16449
  ...normalizeParams2(params)
@@ -15793,7 +16712,7 @@ var ZodFunction = /* @__PURE__ */ $constructor2("ZodFunction", (inst, def) => {
15793
16712
  function _function(params) {
15794
16713
  return new ZodFunction({
15795
16714
  type: "function",
15796
- input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array2(unknown2()),
16715
+ input: Array.isArray(params?.input) ? tuple2(params?.input) : params?.input ?? array2(unknown2()),
15797
16716
  output: params?.output ?? unknown2()
15798
16717
  });
15799
16718
  }
@@ -15929,6 +16848,7 @@ var ID_PREFIXES = {
15929
16848
  member: "mem",
15930
16849
  invitation: "inv",
15931
16850
  transfer: "xfer",
16851
+ assetBatch: "batch",
15932
16852
  supportTicket: "tkt",
15933
16853
  supportTicketMessage: "msg",
15934
16854
  humanReview: "rev",
@@ -15960,11 +16880,13 @@ var newId = (prefix) => `${prefix}_${randomBase62(20)}`;
15960
16880
  var toWebhookEventPayload = (event) => ({
15961
16881
  id: event.id,
15962
16882
  projectId: event.projectId,
16883
+ actor: event.actor,
15963
16884
  type: event.type,
15964
16885
  severity: event.severity,
15965
16886
  title: event.title,
15966
16887
  description: event.description ?? null,
15967
16888
  assetId: event.assetId ?? null,
16889
+ assetSequence: event.assetSequence ?? null,
15968
16890
  asset: event.asset ?? null,
15969
16891
  facts: event.facts,
15970
16892
  createdAt: event.createdAt
@@ -15983,9 +16905,9 @@ var createWebhookHeaders = async (options) => {
15983
16905
  var FORWARD_TIMEOUT_MS = 1e4;
15984
16906
  var MAX_BACKOFF_MS = 30000;
15985
16907
  var FATAL_ERROR_CODES = new Set([
15986
- "auth/missing-token",
15987
- "auth/invalid-api-key",
15988
- "auth/project-mismatch",
16908
+ "api-key/missing",
16909
+ "api-key/invalid",
16910
+ "api-key/project-mismatch",
15989
16911
  "project/not-found"
15990
16912
  ]);
15991
16913
  var createLocalSigningSecret = () => `whsec_local_${randomBytes(24).toString("hex")}`;
@@ -16043,6 +16965,22 @@ var unavailableWarning = (unavailableTypes) => [
16043
16965
  ""
16044
16966
  ].join(`
16045
16967
  `);
16968
+ var inAssetOrder = (events) => {
16969
+ const byAsset = new Map;
16970
+ for (const event of events)
16971
+ if (event.assetId)
16972
+ byAsset.set(event.assetId, [...byAsset.get(event.assetId) ?? [], event]);
16973
+ for (const assetEvents of byAsset.values())
16974
+ assetEvents.sort((a, b) => (a.assetSequence ?? 0) - (b.assetSequence ?? 0));
16975
+ const next = new Map;
16976
+ return events.map((event) => {
16977
+ if (!event.assetId)
16978
+ return event;
16979
+ const index = next.get(event.assetId) ?? 0;
16980
+ next.set(event.assetId, index + 1);
16981
+ return byAsset.get(event.assetId)[index];
16982
+ });
16983
+ };
16046
16984
  var listen = async (options) => {
16047
16985
  const { client, signal } = options;
16048
16986
  const log = options.log ?? ((line) => process.stdout.write(`${line}
@@ -16059,7 +16997,7 @@ var listen = async (options) => {
16059
16997
  if (failures > 0)
16060
16998
  log(`${formatTime(new Date)} Reconnected to CalmLens.`);
16061
16999
  failures = 0;
16062
- for (const event of page.items) {
17000
+ for (const event of inAssetOrder(page.items)) {
16063
17001
  if (eventTypes.size > 0 && !eventTypes.has(event.type))
16064
17002
  continue;
16065
17003
  log(formatForwardLine(event, await forwardEvent(event, options)));
@@ -16206,12 +17144,14 @@ Commands:
16206
17144
  login Sign in through your browser and choose a project. The CLI keeps the key it
16207
17145
  receives, so listen and trigger need no API key or project ID.
16208
17146
  logout Revoke and forget the key from login.
16209
- listen Forward your project's events to a local webhook handler with the same body
16210
- ({ id, type, createdAt, projectId, data }) and headers (x-calmlens-timestamp,
16211
- x-calmlens-signature: v1=...) as real deliveries. No public URL needed.
17147
+ listen Forward your project's events to a local webhook handler with the same flat
17148
+ body (id, projectId, type, severity, title, description, assetId, asset, facts,
17149
+ createdAt) and headers (x-calmlens-timestamp, x-calmlens-signature: v1=...) as
17150
+ real deliveries. No public URL needed.
16212
17151
  trigger Moderate a harmless test comment so CalmLens creates real events. Each trigger
16213
- counts as one upload. Test comments other than clean carry the project's
16214
- test input key (Assets → Try it → Test inputs in the portal).
17152
+ counts as one upload. Test comments other than clean are signed with the
17153
+ project's test input key (Project settings → Test inputs in the portal, with
17154
+ Recognise test inputs turned on).
16215
17155
 
16216
17156
  Options:
16217
17157
  --forward-to <url> Local webhook URL, e.g. http://localhost:3000/api/webhooks/calmlens
@@ -16362,10 +17302,10 @@ var main = async () => {
16362
17302
  const testInputKey = (values["test-key"] ?? process.env.CALMLENS_TEST_INPUT_KEY)?.trim();
16363
17303
  if (!testInputKey)
16364
17304
  fail(`trigger ${kind} needs your project's test input key: pass --test-key <key> or set CALMLENS_TEST_INPUT_KEY.
16365
- ` + "Copy it from Assets → Try it → Test inputs in the CalmLens portal.");
17305
+ ` + "Copy it from Project settings → Test inputs in the CalmLens portal.");
16366
17306
  if (!TEST_INPUT_KEY_PATTERN.test(testInputKey))
16367
17307
  fail(`"${testInputKey}" isn't a test input key: it is 32 lowercase hexadecimal characters.
16368
- ` + "Copy it from Assets → Try it → Test inputs in the CalmLens portal.");
17308
+ ` + "Copy it from Project settings → Test inputs in the CalmLens portal.");
16369
17309
  text = await generateTestTextCode(kind, testInputKey);
16370
17310
  }
16371
17311
  try {