calmlens 0.3.1 → 0.5.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.
package/cjs/index.js CHANGED
@@ -1,6 +1,323 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_CalmLensUtils = require("./CalmLensUtils-DocJkqQj.js");
2
+ const require_CalmLensUtils = require("./CalmLensUtils-0QaxbI3A.js");
3
+ let zod = require("zod");
4
+ zod = require_CalmLensUtils.__toESM(zod);
5
+ require("zod/v4");
3
6
  let api_def = require("api-def");
7
+ //#region ../shared/src/ModerationCategoryDefinitions.ts
8
+ const MODERATION_CATEGORY_DEFINITIONS = {
9
+ sexual: {
10
+ summary: "Sexual acts, explicit sexual anatomy, sexual services, sexual assault depictions and clearly erotic material.",
11
+ definition: "covers sexual acts, explicit sexual anatomy, sexual services and clearly erotic material. Descriptions of sexual assault can qualify without erotic intent. Fictional, illustrated and generated depictions can also qualify.",
12
+ exclusions: "Ordinary affection, swimwear, fitness, fashion, non-erotic medical diagrams and general sexual-health education do not qualify on their own. A person accepting money or wearing revealing clothing does not establish sexual content without a qualifying act, display or offer.",
13
+ docsHref: "/docs/guides/moderation-categories#sexual-content"
14
+ },
15
+ violence: {
16
+ summary: "Physical attacks, injury, death, threats against others, and planning or encouraging physical violence.",
17
+ definition: "covers physical attacks, bodily injury, death and threats against others. Accidental or medical injuries and natural death also count; an attacker or intent to harm is not required. It also includes planning, requesting, encouraging or praising physical violence. A depicted or described act can qualify in fiction or news reporting even when the author condemns it.",
18
+ exclusions: "Solely intentional self-injury or suicide belongs under self-harm. Property damage alone, figurative language, abstract discussion of violence, injury or death and merely possessing a weapon do not establish violence. Consensual sport or training without injury or abuse is excluded.",
19
+ docsHref: "/docs/guides/moderation-categories#violence"
20
+ },
21
+ "self-harm": {
22
+ summary: "Intentional self-injury, suicide, preparation, methods or encouragement; text also includes current or recurring self-harm thoughts.",
23
+ definition: "covers intentional self-injury, suicide, current self-harm risk, preparation, methods and encouragement. For text, it also includes current or recurring self-harm thoughts and an explicitly expressed desire to die. Asking for support does not cancel a separate disclosure of current risk or behavior.",
24
+ exclusions: "For images, require evidence of a self-directed act, preparation, harmful methods or encouragement. An injury or covered body does not establish that harm was self-inflicted. General sadness, neutral statistics, prevention, recovery and healed scars alone are excluded.",
25
+ docsHref: "/docs/guides/moderation-categories#self-harm"
26
+ },
27
+ harassment: {
28
+ summary: "Targeted personal abuse, humiliation, bullying or serious intimidation; ordinary criticism and neutral reporting are excluded.",
29
+ definition: "covers personal abuse, humiliation, bullying and serious intimidation directed at a person or identifiable group. The target can be named, implied or defined by an activity or affiliation. A protected identity is not required.",
30
+ exclusions: "Disagreement, ordinary criticism of conduct or competence, untargeted profanity and neutral reporting of abuse do not qualify without a separate personal attack. Criticism can still qualify when it also contains personal degradation.",
31
+ docsHref: "/docs/guides/moderation-categories#harassment-and-bullying"
32
+ },
33
+ hate: {
34
+ summary: "Identity-based abuse, dehumanization, discriminatory exclusion or threats against people because of protected characteristics.",
35
+ definition: "covers attacks on people because of race, ethnicity, nationality, religion, caste, sex, gender identity, sexual orientation or disability. It includes dehumanization, asserted inferiority, discriminatory exclusion, identity-based abuse and threats.",
36
+ exclusions: "Both the protected target and the identity-based attack must be supported. Identity mentions, cultural clothing, religious imagery, criticism of beliefs or an unrelated threat do not establish hate. Neutral reporting, condemnation and opposition to hate are excluded unless a separate attack is expressed or endorsed.",
37
+ docsHref: "/docs/guides/moderation-categories#hate-and-identity-abuse"
38
+ },
39
+ "criminal-activity": {
40
+ summary: "Planning, assistance, instructions, encouragement or facilitation of a concrete criminal or seriously dangerous act.",
41
+ definition: "covers planning, requests for assistance, instructions, encouragement or facilitation of a concrete criminal or seriously dangerous act. A request can qualify even when no act occurs and a later reply refuses it. Dangerous activity requires a concrete serious risk of physical harm.",
42
+ exclusions: "Neutral reporting, prevention, lawful safety advice, fiction without criminal assistance, and vague dangerous references do not qualify. Masks, computers, payment cards, detention or ordinary tools do not establish criminal facilitation by themselves. A clear visual demonstration of how to carry out a crime can qualify.",
43
+ docsHref: "/docs/guides/moderation-categories#criminal-and-dangerous-activity"
44
+ }
45
+ };
46
+ //#endregion
47
+ //#region ../shared/src/ModerationPolicyDimensions.ts
48
+ const MODERATION_QUALIFIERS = [
49
+ "nudity",
50
+ "sexual-activity",
51
+ "explicit-sexual-language",
52
+ "sexual-solicitation",
53
+ "physical-attack",
54
+ "violent-threat",
55
+ "violent-preparation",
56
+ "violent-encouragement",
57
+ "injury",
58
+ "death",
59
+ "graphic",
60
+ "self-harm-thoughts",
61
+ "self-harm-preparation",
62
+ "self-harm-act",
63
+ "self-harm-methods",
64
+ "self-harm-encouragement",
65
+ "personal-abuse",
66
+ "targeted-intimidation",
67
+ "harassment-threat",
68
+ "sexual-harassment",
69
+ "harassment-encouragement",
70
+ "identity-abuse",
71
+ "dehumanization",
72
+ "identity-inferiority",
73
+ "discriminatory-exclusion",
74
+ "hate-threat",
75
+ "criminal-demonstration",
76
+ "criminal-preparation",
77
+ "criminal-request",
78
+ "criminal-instructions",
79
+ "criminal-promotion",
80
+ "historical",
81
+ "documentary",
82
+ "fictional",
83
+ "support-prevention"
84
+ ];
85
+ const SHARED_QUALIFIERS = [
86
+ "historical",
87
+ "documentary",
88
+ "fictional",
89
+ "support-prevention"
90
+ ];
91
+ [...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS];
92
+ //#endregion
93
+ //#region ../../node_modules/zod-meta/esm/index.js
94
+ const createMetaType = (type) => {
95
+ return Object.assign((value) => {
96
+ return {
97
+ type,
98
+ data: value !== null && value !== void 0 ? value : {}
99
+ };
100
+ }, type);
101
+ };
102
+ createMetaType({ id: "docPropertyInfo" });
103
+ //#endregion
104
+ //#region ../shared/src/ZodUtils.ts
105
+ const SIZE_LIMITS = {
106
+ small: 64,
107
+ medium: 200,
108
+ large: 1500
109
+ };
110
+ const saneStringField = (options) => {
111
+ return zod.string().transform((value) => value.trim()).refine((value) => {
112
+ if ((options === null || options === void 0 ? void 0 : options.minWidth) && value.length < options.minWidth) return false;
113
+ return true;
114
+ }, "Not long enough").refine((value) => {
115
+ var _options$type;
116
+ const sizeLimit = SIZE_LIMITS[(_options$type = options === null || options === void 0 ? void 0 : options.type) !== null && _options$type !== void 0 ? _options$type : "medium"];
117
+ return typeof value === "string" && value.length < sizeLimit;
118
+ }, "Too long");
119
+ };
120
+ const CLASSIFICATION_INPUT_TYPE_SCHEMA = zod.enum(["text", "image"]);
121
+ const CLASSIFICATION_CATEGORIES = [
122
+ "sexual",
123
+ "violence",
124
+ "self-harm",
125
+ "harassment",
126
+ "hate",
127
+ "criminal-activity"
128
+ ];
129
+ const CLASSIFICATION_CATEGORY_SCHEMA = zod.enum(CLASSIFICATION_CATEGORIES);
130
+ zod.object({
131
+ category: CLASSIFICATION_CATEGORY_SCHEMA,
132
+ displayName: saneStringField(),
133
+ description: saneStringField(),
134
+ supportedInputTypes: zod.array(CLASSIFICATION_INPUT_TYPE_SCHEMA).min(1)
135
+ });
136
+ MODERATION_CATEGORY_DEFINITIONS.sexual.summary, MODERATION_CATEGORY_DEFINITIONS.violence.summary, MODERATION_CATEGORY_DEFINITIONS["self-harm"].summary, MODERATION_CATEGORY_DEFINITIONS.harassment.summary, MODERATION_CATEGORY_DEFINITIONS.hate.summary, MODERATION_CATEGORY_DEFINITIONS["criminal-activity"].summary;
137
+ const LIKELIHOOD_SCHEMA = zod.enum([
138
+ "very-unlikely",
139
+ "unlikely",
140
+ "possible",
141
+ "likely",
142
+ "very-likely"
143
+ ]);
144
+ const CLASSIFICATION_NOT_EVALUATED_REASON_SCHEMA = zod.enum(["not-supported", "unavailable"]);
145
+ const CLASSIFICATION_QUALIFIER_RESULTS_SCHEMA = zod.partialRecord(zod.enum(MODERATION_QUALIFIERS), zod.discriminatedUnion("status", [zod.object({
146
+ status: zod.literal("evaluated"),
147
+ score: zod.number().min(0).max(1),
148
+ scopeScore: zod.number().min(0).max(1).optional(),
149
+ likelihood: LIKELIHOOD_SCHEMA
150
+ }).strict().refine(({ score, scopeScore }) => scopeScore === void 0 || scopeScore <= score, {
151
+ message: "Only confidence cannot exceed Any confidence",
152
+ path: ["scopeScore"]
153
+ }), zod.object({
154
+ status: zod.literal("not-evaluated"),
155
+ reason: CLASSIFICATION_NOT_EVALUATED_REASON_SCHEMA
156
+ }).strict()]));
157
+ const CLASSIFICATION_CATEGORY_REPORT_SCHEMA = zod.discriminatedUnion("status", [
158
+ zod.object({
159
+ status: zod.literal("evaluated"),
160
+ likelihood: LIKELIHOOD_SCHEMA,
161
+ score: zod.number().min(0).max(1),
162
+ qualifiers: CLASSIFICATION_QUALIFIER_RESULTS_SCHEMA.optional()
163
+ }).strict(),
164
+ zod.object({
165
+ status: zod.literal("partial"),
166
+ likelihood: LIKELIHOOD_SCHEMA,
167
+ score: zod.number().min(0).max(1),
168
+ qualifiers: CLASSIFICATION_QUALIFIER_RESULTS_SCHEMA.optional()
169
+ }).strict(),
170
+ zod.object({
171
+ status: zod.literal("not-evaluated"),
172
+ reason: CLASSIFICATION_NOT_EVALUATED_REASON_SCHEMA,
173
+ qualifiers: CLASSIFICATION_QUALIFIER_RESULTS_SCHEMA.optional()
174
+ }).strict()
175
+ ]);
176
+ const CATEGORIES_SCHEMA = zod.object({
177
+ sexual: CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
178
+ violence: CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
179
+ "self-harm": CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
180
+ harassment: CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
181
+ hate: CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
182
+ "criminal-activity": CLASSIFICATION_CATEGORY_REPORT_SCHEMA
183
+ }).strict();
184
+ const CLASSIFICATION_LABEL_SCHEMA = zod.object({
185
+ description: saneStringField(),
186
+ score: zod.number(),
187
+ topicalityScore: zod.number().nullish(),
188
+ likelihood: LIKELIHOOD_SCHEMA,
189
+ knowledgeBaseId: saneStringField().nullish()
190
+ });
191
+ zod.object({
192
+ processedAt: zod.number(),
193
+ categories: CATEGORIES_SCHEMA,
194
+ flagged: zod.boolean(),
195
+ score: zod.number(),
196
+ notes: saneStringField().nullish(),
197
+ media: zod.object({
198
+ durationSeconds: zod.number().positive(),
199
+ frameIntervalSeconds: zod.number().positive().optional(),
200
+ sampledFrames: zod.number().int().nonnegative(),
201
+ audioTranscribed: zod.boolean(),
202
+ segments: zod.array(zod.object({
203
+ source: zod.enum([
204
+ "frame",
205
+ "speech",
206
+ "frame-text"
207
+ ]),
208
+ startSeconds: zod.number().nonnegative(),
209
+ endSeconds: zod.number().nonnegative(),
210
+ categories: CATEGORIES_SCHEMA
211
+ }).strict())
212
+ }).strict().optional(),
213
+ labels: zod.array(CLASSIFICATION_LABEL_SCHEMA).nullish()
214
+ }).strict();
215
+ //#endregion
216
+ //#region ../shared/src/MediaTestTriggers.ts
217
+ const MEDIA_TEST_SIGNALS = [...CLASSIFICATION_CATEGORIES, "violence.graphic"];
218
+ const HEX_WORDS = [
219
+ "zero",
220
+ "one",
221
+ "two",
222
+ "three",
223
+ "four",
224
+ "five",
225
+ "six",
226
+ "seven",
227
+ "eight",
228
+ "nine",
229
+ "alpha",
230
+ "bravo",
231
+ "charlie",
232
+ "delta",
233
+ "echo",
234
+ "foxtrot"
235
+ ];
236
+ /** Read this aloud, or render it as large, high-contrast text in a video frame. */
237
+ function generateMediaTestCode(signal, projectId) {
238
+ if (!MEDIA_TEST_SIGNALS.includes(signal)) throw new Error("Unsupported media test signal");
239
+ const suffix = projectId.slice(-8).toLowerCase();
240
+ if (!/^[a-f0-9]{8}$/.test(suffix)) throw new Error("Expected a project ID with an eight-character hexadecimal suffix");
241
+ return `Calm Lens test ${[...suffix].map((character) => HEX_WORDS[Number.parseInt(character, 16)]).join(" ")} ${signal.replace(/[.-]/g, " ")} end test`;
242
+ }
243
+ //#endregion
244
+ //#region src/client/CalmLensWebhooks.ts
245
+ const WEBHOOK_DELIVERY_HEADER = "x-calmlens-delivery";
246
+ const WEBHOOK_TIMESTAMP_HEADER = "x-calmlens-timestamp";
247
+ const WEBHOOK_SIGNATURE_HEADER = "x-calmlens-signature";
248
+ /** Deliveries whose timestamp is further than this from the receiver's clock are rejected. */
249
+ const WEBHOOK_SIGNATURE_TOLERANCE_SECONDS = 300;
250
+ const encoder = new TextEncoder();
251
+ const hmacSha256Hex = function() {
252
+ var _ref = require_CalmLensUtils._asyncToGenerator(function* (secret, message) {
253
+ const key = yield crypto.subtle.importKey("raw", encoder.encode(secret), {
254
+ name: "HMAC",
255
+ hash: "SHA-256"
256
+ }, false, ["sign"]);
257
+ const signature = yield crypto.subtle.sign("HMAC", key, encoder.encode(message));
258
+ return Array.from(new Uint8Array(signature), (byte) => byte.toString(16).padStart(2, "0")).join("");
259
+ });
260
+ return function hmacSha256Hex(_x, _x2) {
261
+ return _ref.apply(this, arguments);
262
+ };
263
+ }();
264
+ /** Constant-time comparison of two strings of the same length. */
265
+ const timingSafeEqual = (a, b) => {
266
+ if (a.length !== b.length) return false;
267
+ let diff = 0;
268
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
269
+ return diff === 0;
270
+ };
271
+ /** `v1=<hex HMAC-SHA256 of "<timestamp>.<body>">`, the `x-calmlens-signature` header value. */
272
+ const createWebhookSignatureHeader = function() {
273
+ var _ref2 = require_CalmLensUtils._asyncToGenerator(function* (secret, timestamp, body) {
274
+ return `v1=${yield hmacSha256Hex(secret, `${timestamp}.${body}`)}`;
275
+ });
276
+ return function createWebhookSignatureHeader(_x3, _x4, _x5) {
277
+ return _ref2.apply(this, arguments);
278
+ };
279
+ }();
280
+ (function() {
281
+ var _ref3 = require_CalmLensUtils._asyncToGenerator(function* (options) {
282
+ var _options$timestampSec;
283
+ const timestamp = (_options$timestampSec = options.timestampSeconds) !== null && _options$timestampSec !== void 0 ? _options$timestampSec : Math.floor(Date.now() / 1e3);
284
+ return {
285
+ "content-type": "application/json",
286
+ [WEBHOOK_DELIVERY_HEADER]: options.deliveryId,
287
+ [WEBHOOK_TIMESTAMP_HEADER]: String(timestamp),
288
+ [WEBHOOK_SIGNATURE_HEADER]: yield createWebhookSignatureHeader(options.secret, timestamp, options.body)
289
+ };
290
+ });
291
+ return function createWebhookHeaders(_x6) {
292
+ return _ref3.apply(this, arguments);
293
+ };
294
+ })();
295
+ /**
296
+ * Verifies a webhook delivery: `x-calmlens-signature` must contain a `v1=` HMAC-SHA256 of
297
+ * `"<x-calmlens-timestamp>.<raw body>"`, and the timestamp must be within `toleranceSeconds`
298
+ * (default 300) of now. Returns `false` for anything missing or malformed.
299
+ */
300
+ function verifyWebhookSignature(_x7) {
301
+ return _verifyWebhookSignature.apply(this, arguments);
302
+ }
303
+ function _verifyWebhookSignature() {
304
+ _verifyWebhookSignature = require_CalmLensUtils._asyncToGenerator(function* ({ payload, signature, timestamp, secret, toleranceSeconds = 300, now }) {
305
+ if (!secret || !signature || timestamp === null || timestamp === void 0) return false;
306
+ const timestampText = String(timestamp).trim();
307
+ if (!/^\d+$/.test(timestampText)) return false;
308
+ const nowMs = now === void 0 ? Date.now() : now instanceof Date ? now.getTime() : now;
309
+ if (Math.abs(Math.floor(nowMs / 1e3) - Number(timestampText)) > toleranceSeconds) return false;
310
+ const candidates = signature.split(",").map((part) => part.trim()).filter((part) => part.startsWith("v1=")).map((part) => part.slice(3).toLowerCase());
311
+ if (candidates.length === 0) return false;
312
+ const body = typeof payload === "string" ? payload : JSON.stringify(payload);
313
+ const expected = yield hmacSha256Hex(secret, `${timestampText}.${body}`);
314
+ let matched = false;
315
+ for (const candidate of candidates) if (timingSafeEqual(expected, candidate)) matched = true;
316
+ return matched;
317
+ });
318
+ return _verifyWebhookSignature.apply(this, arguments);
319
+ }
320
+ //#endregion
4
321
  //#region src/client/CalmLensClient.ts
5
322
  const _excluded = ["uint8Array"];
6
323
  const _excluded2 = ["buffer"];
@@ -43,7 +360,7 @@ const normalizeAssetOptionsForRequest = (options) => {
43
360
  const toRawUploadBody = (payload) => {
44
361
  const data = require_CalmLensUtils.assetToData(normalizePayloadForRequest(payload));
45
362
  if (data instanceof Response) {
46
- if (!data.body) throw new Error("Response upload data must have a body");
363
+ if (!data.body) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Response upload data must have a body" });
47
364
  return data.body;
48
365
  }
49
366
  if (data instanceof ArrayBuffer || data instanceof Blob) return data;
@@ -61,8 +378,8 @@ const assertValidUploadMimeType = (mimeType) => {
61
378
  };
62
379
  const isImageMimeType = (mimeType) => mimeType.toLowerCase().startsWith("image/");
63
380
  const prepareSubmitAssetOptions = (options) => {
64
- if (!("content" in options) && !("url" in options) && !("part" in options)) throw new Error("Either file content, URL, or multipart part is required");
65
- if (!options.name) throw new Error("Asset name is required");
381
+ if (!("content" in options) && !("url" in options) && !("part" in options)) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Either file content, URL, or multipart part is required" });
382
+ if (!options.name) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset name is required" });
66
383
  if (!("part" in options) && "isFinal" in options) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "isFinal is only valid for multipart uploads" });
67
384
  if ("part" in options && options.part.partNumber && options.part.partNumber > 1) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.PUBLIC_ERROR_CODES.USE_UPLOAD_PART);
68
385
  if ("content" in options) {
@@ -77,8 +394,8 @@ const prepareSubmitAssetOptions = (options) => {
77
394
  assertValidUploadMimeType(options.part.type);
78
395
  const partSizeInBytes = (_options$part$sizeInB = options.part.sizeInBytes) !== null && _options$part$sizeInB !== void 0 ? _options$part$sizeInB : require_CalmLensUtils.getAssetPayloadByteLength(options.part);
79
396
  if (isImageMimeType(options.part.type) && partSizeInBytes !== void 0) {
80
- if (partSizeInBytes > 20971520) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
81
- if (options.part.isFinal && partSizeInBytes < 10485760) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
397
+ if (partSizeInBytes > require_CalmLensUtils.MAX_IMAGE_UPLOAD_BYTES) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
398
+ if (options.part.isFinal && partSizeInBytes < require_CalmLensUtils.MIN_MULTIPART_IMAGE_UPLOAD_BYTES) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
82
399
  }
83
400
  const validation = require_CalmLensUtils.validateAssetPayload(options.part, {
84
401
  multipart: true,
@@ -89,7 +406,7 @@ const prepareSubmitAssetOptions = (options) => {
89
406
  return options;
90
407
  };
91
408
  const appendCdnSelector = (url, options) => {
92
- if (options.lens && options.transform) throw new Error("Specify either a lens or a transform, not both");
409
+ if (options.lens && options.transform) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Specify either a lens or a transform, not both" });
93
410
  if (options.lens) return `${url}/@${encodeURIComponent(options.lens)}`;
94
411
  if (!options.transform) return url;
95
412
  return `${url}/${encodeURI(options.transform.replace(/^\/+/, ""))}`;
@@ -109,8 +426,42 @@ const getEnsureLensCacheKey = (options) => {
109
426
  const withApiKeyHeader = (init, apiKey) => {
110
427
  const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);
111
428
  headers.set("X-Api-Key", apiKey);
112
- return require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, init), {}, { headers: Object.fromEntries(headers.entries()) });
429
+ return require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, init), {}, {
430
+ redirect: "error",
431
+ headers: Object.fromEntries(headers.entries())
432
+ });
113
433
  };
434
+ const requestSignal = (options, signal) => {
435
+ var _options$timeoutMs;
436
+ const signals = [
437
+ options.signal,
438
+ signal,
439
+ AbortSignal.timeout((_options$timeoutMs = options.timeoutMs) !== null && _options$timeoutMs !== void 0 ? _options$timeoutMs : 12e4)
440
+ ].filter((value) => value != null);
441
+ return AbortSignal.any(signals);
442
+ };
443
+ const safeFetch = (fetchImpl, options) => function() {
444
+ var _ref = require_CalmLensUtils._asyncToGenerator(function* (input, init) {
445
+ var _init$signal;
446
+ const signal = requestSignal(options, (_init$signal = init === null || init === void 0 ? void 0 : init.signal) !== null && _init$signal !== void 0 ? _init$signal : input instanceof Request ? input.signal : void 0);
447
+ try {
448
+ signal.throwIfAborted();
449
+ return yield fetchImpl(input, require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, init), {}, {
450
+ redirect: "error",
451
+ signal
452
+ }));
453
+ } catch (cause) {
454
+ var _signal$reason;
455
+ throw require_CalmLensUtils.calmLensError({ id: signal.aborted ? ((_signal$reason = signal.reason) === null || _signal$reason === void 0 ? void 0 : _signal$reason.name) === "TimeoutError" ? "sdk/timeout" : "sdk/cancelled" : "sdk/transport-error" }, {
456
+ message: signal.aborted ? "Request aborted" : "Request failed",
457
+ cause
458
+ });
459
+ }
460
+ });
461
+ return function(_x, _x2) {
462
+ return _ref.apply(this, arguments);
463
+ };
464
+ }();
114
465
  const createApi = (options) => {
115
466
  return new api_def.Api({
116
467
  name: "Calm Lens",
@@ -124,13 +475,24 @@ const createApi = (options) => {
124
475
  if (context.error) throw normalizeApiError(context.error);
125
476
  } }
126
477
  ],
127
- requestBackend: options.requestBackend
478
+ requestBackend: options.requestBackend ? Object.assign(Object.create(options.requestBackend), "fetch" in options.requestBackend && typeof options.requestBackend.fetch === "function" ? { fetch: safeFetch(options.requestBackend.fetch, options) } : {}) : new api_def.FetchRequestBackend(safeFetch(globalThis.fetch, options))
128
479
  });
129
480
  };
130
481
  const isApiErrorPayload = (value) => {
131
482
  return !!value && typeof value === "object" && typeof value.code === "string";
132
483
  };
133
484
  const normalizeApiError = (error) => {
485
+ let cause = error;
486
+ const seen = /* @__PURE__ */ new Set();
487
+ while (cause instanceof Error && !seen.has(cause)) {
488
+ seen.add(cause);
489
+ if (cause instanceof require_CalmLensUtils.CalmLensError) return cause;
490
+ if (cause.name === "AbortError" || cause.name === "TimeoutError") return require_CalmLensUtils.calmLensError({ id: cause.name === "TimeoutError" ? "sdk/timeout" : "sdk/cancelled" }, {
491
+ message: "Request aborted",
492
+ cause
493
+ });
494
+ cause = cause.cause;
495
+ }
134
496
  const response = error instanceof Error ? (0, api_def.getErrorResponse)(error) : void 0;
135
497
  if (error instanceof Error && (0, api_def.isRequestError)(error) && isApiErrorPayload(response === null || response === void 0 ? void 0 : response.data)) {
136
498
  const { code, message, details, traceId } = response.data;
@@ -139,13 +501,20 @@ const normalizeApiError = (error) => {
139
501
  defaultMessage: message
140
502
  }, {
141
503
  message,
504
+ status: response === null || response === void 0 ? void 0 : response.status,
505
+ cause: error,
142
506
  details: require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, details), {}, {
143
507
  traceId,
144
508
  network: true
145
509
  })
146
510
  });
147
511
  }
148
- return error;
512
+ if (error instanceof require_CalmLensUtils.CalmLensError) return error;
513
+ return require_CalmLensUtils.calmLensError({ id: response ? response.ok ? "sdk/invalid-response" : "sdk/http-error" : "sdk/transport-error" }, {
514
+ message: response ? `HTTP ${response.status}` : error.message,
515
+ status: response === null || response === void 0 ? void 0 : response.status,
516
+ cause: error
517
+ });
149
518
  };
150
519
  const createEndpoints = (api) => {
151
520
  const getFolders = api.endpoint().paramsOf().responseOf().build({
@@ -218,6 +587,11 @@ const createEndpoints = (api) => {
218
587
  method: "post",
219
588
  path: "/assets/:assetId/move"
220
589
  });
590
+ const retryAsset = api.endpoint().paramsOf().responseOf().build({
591
+ id: "retryAsset",
592
+ method: "post",
593
+ path: "/assets/:assetId/retry"
594
+ });
221
595
  const getEvents = api.endpoint().paramsOf().queryOf().responseOf().build({
222
596
  id: "getEvents",
223
597
  method: "get",
@@ -238,6 +612,7 @@ const createEndpoints = (api) => {
238
612
  postAssetSignedUrl,
239
613
  postAssetPart,
240
614
  moveAsset,
615
+ retryAsset,
241
616
  ensureLens: api.endpoint().bodyOf().paramsOf().responseOf().build({
242
617
  id: "ensureLens",
243
618
  method: "put",
@@ -251,34 +626,40 @@ const createEndpoints = (api) => {
251
626
  getEvents
252
627
  };
253
628
  };
254
- var CalmLensClient = class {
629
+ var CalmLensClient = class CalmLensClient {
255
630
  /**
256
- * Validates a webhook signature to ensure the webhook payload is authentic.
631
+ * Verifies that a webhook delivery came from CalmLens: checks the `v1=` HMAC-SHA256 in
632
+ * `x-calmlens-signature` over `"<x-calmlens-timestamp>.<raw body>"` and rejects timestamps
633
+ * more than `toleranceSeconds` (default 300) from now, which stops replayed deliveries.
257
634
  *
258
- * @param payload - The webhook payload (string or object)
259
- * @param signatureHex - The signature from the 'x-calmlens-signature' header
260
- * @param secret - The webhook secret used to sign the payload
261
- * @returns Promise<boolean> - True if the signature is valid, false otherwise
635
+ * @param options.payload - The raw request body, exactly as received (verify before parsing)
636
+ * @param options.signature - The 'x-calmlens-signature' header value
637
+ * @param options.timestamp - The 'x-calmlens-timestamp' header value
638
+ * @param options.secret - The connector's signing secret
639
+ * @param options.toleranceSeconds - Allowed clock distance in seconds (default 300)
640
+ * @param options.now - Override the current time (Date or epoch milliseconds), for tests
641
+ * @returns Promise<boolean> - True if the signature is valid and fresh, false otherwise
262
642
  *
263
643
  * @example
264
644
  * ```javascript
265
- * // In your webhook handler
266
- * const signature = req.headers['x-calmlens-signature'];
267
- * const payload = req.body;
645
+ * // In your webhook handler (e.g. a Fetch API Request)
646
+ * const payload = await request.text();
268
647
  * const isValid = await CalmLensClient.verifyWebhookSignature({
269
648
  * payload,
270
- * signatureHex: signature,
649
+ * signature: request.headers.get('x-calmlens-signature'),
650
+ * timestamp: request.headers.get('x-calmlens-timestamp'),
271
651
  * secret: WEBHOOK_SECRET,
272
652
  * });
273
653
  *
274
654
  * if (!isValid) {
275
- * return res.status(401).send('Unauthorized');
655
+ * return new Response('Unauthorized', { status: 401 });
276
656
  * }
657
+ * const event = JSON.parse(payload); // { id, type, createdAt, projectId, data }
277
658
  * ```
278
659
  */
279
660
  static verifyWebhookSignature(options) {
280
661
  return require_CalmLensUtils._asyncToGenerator(function* () {
281
- return require_CalmLensUtils.verifyWebhookSignature(options);
662
+ return verifyWebhookSignature(options);
282
663
  })();
283
664
  }
284
665
  constructor(options) {
@@ -288,19 +669,28 @@ var CalmLensClient = class {
288
669
  this.pendingEnsureLenses = /* @__PURE__ */ new Map();
289
670
  this.multipartImageUploadSizes = /* @__PURE__ */ new Map();
290
671
  this.multipartUploadQueues = /* @__PURE__ */ new Map();
291
- if (!options.apiKey) throw new Error("API key is required");
292
- if (!options.projectId) throw new Error("Project ID is required");
672
+ if (!options.apiKey) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "API key is required" });
673
+ if (!options.projectId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Project ID is required" });
674
+ if (options.timeoutMs !== void 0 && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0)) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "timeoutMs must be a positive integer" });
675
+ this.options = require_CalmLensUtils._objectSpread2({}, options);
293
676
  this.options.baseUrl = (_this$options$baseUrl = this.options.baseUrl) !== null && _this$options$baseUrl !== void 0 ? _this$options$baseUrl : `https://api.${require_CalmLensUtils.DOMAIN}/v1`;
294
677
  this.options.cdnBaseUrl = (_this$options$cdnBase = this.options.cdnBaseUrl) !== null && _this$options$cdnBase !== void 0 ? _this$options$cdnBase : `https://cdn.${require_CalmLensUtils.DOMAIN}/v1`;
295
678
  this.api = createApi(this.options);
296
679
  this.endpoints = createEndpoints(this.api);
297
680
  }
681
+ /** Scope cancellation/timeout to an operation without changing this client's defaults. */
682
+ withRequestOptions(options) {
683
+ const client = new CalmLensClient(require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, this.options), options));
684
+ client.multipartUploadQueues = this.multipartUploadQueues;
685
+ client.multipartImageUploadSizes = this.multipartImageUploadSizes;
686
+ return client;
687
+ }
298
688
  getUploadFetch() {
299
- var _this$options$request, _ref, _this$options$uploadF;
689
+ var _this$options$request, _ref2, _this$options$uploadF;
300
690
  const requestBackendFetch = (_this$options$request = this.options.requestBackend) === null || _this$options$request === void 0 ? void 0 : _this$options$request.fetch;
301
- const fetchImpl = (_ref = (_this$options$uploadF = this.options.uploadFetch) !== null && _this$options$uploadF !== void 0 ? _this$options$uploadF : requestBackendFetch) !== null && _ref !== void 0 ? _ref : globalThis.fetch;
691
+ const fetchImpl = (_ref2 = (_this$options$uploadF = this.options.uploadFetch) !== null && _this$options$uploadF !== void 0 ? _this$options$uploadF : requestBackendFetch) !== null && _ref2 !== void 0 ? _ref2 : globalThis.fetch;
302
692
  if (!fetchImpl) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.SDK_ERRORS.NO_CDN_FETCH);
303
- return fetchImpl;
693
+ return safeFetch(fetchImpl, this.options);
304
694
  }
305
695
  submitRawAssetUpload(options, queue) {
306
696
  var _this = this;
@@ -385,20 +775,43 @@ var CalmLensClient = class {
385
775
  }
386
776
  parseRawUploadResponse(response) {
387
777
  return require_CalmLensUtils._asyncToGenerator(function* () {
388
- const data = yield response.json().catch(() => void 0);
778
+ let data;
779
+ try {
780
+ data = yield response.json();
781
+ } catch (cause) {
782
+ throw require_CalmLensUtils.calmLensError({ id: cause instanceof Error && ["TimeoutError", "AbortError"].includes(cause.name) ? cause.name === "TimeoutError" ? "sdk/timeout" : "sdk/cancelled" : response.ok ? "sdk/invalid-response" : "sdk/http-error" }, {
783
+ message: `Invalid JSON response (HTTP ${response.status})`,
784
+ status: response.status,
785
+ cause
786
+ });
787
+ }
389
788
  if (!response.ok) {
390
789
  if (isApiErrorPayload(data)) throw require_CalmLensUtils.calmLensError({
391
790
  id: data.code,
392
791
  defaultMessage: data.message
393
792
  }, {
394
793
  message: data.message,
794
+ status: response.status,
395
795
  details: require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, data.details), {}, {
396
796
  traceId: data.traceId,
397
797
  network: true
398
798
  })
399
799
  });
400
- throw new Error(`CalmLens upload failed with status ${response.status}`);
800
+ throw require_CalmLensUtils.calmLensError({ id: "sdk/http-error" }, {
801
+ message: `HTTP ${response.status}`,
802
+ status: response.status
803
+ });
401
804
  }
805
+ if (!data || typeof data !== "object" || !("id" in data) || typeof data.id !== "string" || !data.id || !("status" in data) || ![
806
+ "uploading",
807
+ "pending",
808
+ "approved",
809
+ "rejected",
810
+ "error"
811
+ ].includes(String(data.status))) throw require_CalmLensUtils.calmLensError({ id: "sdk/invalid-response" }, {
812
+ message: "Expected an asset response",
813
+ status: response.status
814
+ });
402
815
  return data;
403
816
  })();
404
817
  }
@@ -409,10 +822,10 @@ var CalmLensClient = class {
409
822
  * Create a CDN URL for asset content or previews.
410
823
  * Private assets require an authenticated request or signed URL.
411
824
  */
412
- getAssetUrl: (_ref2) => {
825
+ getAssetUrl: (_ref3) => {
413
826
  var _options$resource;
414
- let { assetIdentifier } = _ref2, options = require_CalmLensUtils._objectWithoutProperties(_ref2, _excluded3);
415
- if (!assetIdentifier) throw new Error("Asset identifier is required");
827
+ let { assetIdentifier } = _ref3, options = require_CalmLensUtils._objectWithoutProperties(_ref3, _excluded3);
828
+ if (!assetIdentifier) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset identifier is required" });
416
829
  const resource = (_options$resource = options.resource) !== null && _options$resource !== void 0 ? _options$resource : "content";
417
830
  const url = `${this.options.cdnBaseUrl.replace(/\/$/, "")}/assets/${encodeURIComponent(this.options.projectId)}/${encodeURIComponent(assetIdentifier)}/${resource}`;
418
831
  return appendCdnSelector(url, options);
@@ -422,33 +835,27 @@ var CalmLensClient = class {
422
835
  * Private assets are authenticated with the client's API key.
423
836
  */
424
837
  serve: function() {
425
- var _ref4 = require_CalmLensUtils._asyncToGenerator(function* (_ref3) {
838
+ var _ref5 = require_CalmLensUtils._asyncToGenerator(function* (_ref4) {
426
839
  var _this$options$cdnFetc;
427
- let { assetIdentifier, init } = _ref3, urlOptions = require_CalmLensUtils._objectWithoutProperties(_ref3, _excluded4);
840
+ let { assetIdentifier, init } = _ref4, urlOptions = require_CalmLensUtils._objectWithoutProperties(_ref4, _excluded4);
428
841
  const fetchImpl = (_this$options$cdnFetc = _this3.options.cdnFetch) !== null && _this$options$cdnFetc !== void 0 ? _this$options$cdnFetc : globalThis.fetch;
429
842
  if (!fetchImpl) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.SDK_ERRORS.NO_CDN_FETCH);
430
- return fetchImpl(_this3.cdn.getAssetUrl(require_CalmLensUtils._objectSpread2({ assetIdentifier }, urlOptions)), withApiKeyHeader(init, _this3.options.apiKey));
843
+ return safeFetch(fetchImpl, _this3.options)(_this3.cdn.getAssetUrl(require_CalmLensUtils._objectSpread2({ assetIdentifier }, urlOptions)), withApiKeyHeader(init, _this3.options.apiKey));
431
844
  });
432
- return function serve(_x) {
433
- return _ref4.apply(this, arguments);
845
+ return function serve(_x3) {
846
+ return _ref5.apply(this, arguments);
434
847
  };
435
848
  }()
436
849
  };
437
850
  }
438
851
  get text() {
439
852
  var _this4 = this;
440
- return {
441
- /**
442
- * Moderate a short piece of text, such as a comment, caption or bio, and wait for the
443
- * decision. Check `status` (`"approved"` or `"rejected"`) and `report.flagged`.
444
- * The text is not retained after classification unless `processingOptions` says so.
445
- */
446
- moderate: function() {
447
- var _ref5 = require_CalmLensUtils._asyncToGenerator(function* (options) {
448
- return _this4.assets.analyze(require_CalmLensUtils.toTextAssetOptions(options));
853
+ return { moderate: function() {
854
+ var _ref6 = require_CalmLensUtils._asyncToGenerator(function* (options) {
855
+ return _this4.assets.moderate(require_CalmLensUtils.toTextAssetOptions(options));
449
856
  });
450
- return function moderate(_x2) {
451
- return _ref5.apply(this, arguments);
857
+ return function moderate(_x4) {
858
+ return _ref6.apply(this, arguments);
452
859
  };
453
860
  }() };
454
861
  }
@@ -461,15 +868,15 @@ moderate: function() {
461
868
  * @returns Promise with paginated assets
462
869
  */
463
870
  list: function() {
464
- var _ref6 = require_CalmLensUtils._asyncToGenerator(function* (options) {
871
+ var _ref7 = require_CalmLensUtils._asyncToGenerator(function* (options) {
465
872
  var _options$pageIndex;
466
873
  return (yield _this5.endpoints.getAssetsPage.submit({
467
874
  params: { projectId: _this5.options.projectId },
468
875
  query: require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, options), {}, { pageIndex: (_options$pageIndex = options.pageIndex) !== null && _options$pageIndex !== void 0 ? _options$pageIndex : 0 })
469
876
  })).data;
470
877
  });
471
- return function list(_x3) {
472
- return _ref6.apply(this, arguments);
878
+ return function list(_x5) {
879
+ return _ref7.apply(this, arguments);
473
880
  };
474
881
  }(),
475
882
  /**
@@ -478,25 +885,25 @@ moderate: function() {
478
885
  * @returns Promise with asset data
479
886
  */
480
887
  retrieve: function() {
481
- var _ref7 = require_CalmLensUtils._asyncToGenerator(function* ({ assetId }) {
482
- if (!assetId) throw new Error("Asset ID is required");
888
+ var _ref8 = require_CalmLensUtils._asyncToGenerator(function* ({ assetId }) {
889
+ if (!assetId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
483
890
  return (yield _this5.endpoints.getAsset.submit({ params: { assetId } })).data;
484
891
  });
485
- return function retrieve(_x4) {
486
- return _ref7.apply(this, arguments);
892
+ return function retrieve(_x6) {
893
+ return _ref8.apply(this, arguments);
487
894
  };
488
895
  }(),
489
896
  update: function() {
490
- var _ref9 = require_CalmLensUtils._asyncToGenerator(function* (_ref8) {
491
- let { assetId } = _ref8, body = require_CalmLensUtils._objectWithoutProperties(_ref8, _excluded5);
492
- if (!assetId) throw new Error("Asset ID is required");
897
+ var _ref10 = require_CalmLensUtils._asyncToGenerator(function* (_ref9) {
898
+ let { assetId } = _ref9, body = require_CalmLensUtils._objectWithoutProperties(_ref9, _excluded5);
899
+ if (!assetId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
493
900
  return (yield _this5.endpoints.patchAsset.submit({
494
901
  params: { assetId },
495
902
  body
496
903
  })).data;
497
904
  });
498
- return function update(_x5) {
499
- return _ref9.apply(this, arguments);
905
+ return function update(_x7) {
906
+ return _ref10.apply(this, arguments);
500
907
  };
501
908
  }(),
502
909
  /**
@@ -506,17 +913,17 @@ moderate: function() {
506
913
  * @returns Promise with paginated child assets
507
914
  */
508
915
  listChildren: function() {
509
- var _ref11 = require_CalmLensUtils._asyncToGenerator(function* (_ref10) {
916
+ var _ref12 = require_CalmLensUtils._asyncToGenerator(function* (_ref11) {
510
917
  var _options$pageIndex2;
511
- let { assetId } = _ref10, options = require_CalmLensUtils._objectWithoutProperties(_ref10, _excluded6);
512
- if (!assetId) throw new Error("Asset ID is required");
918
+ let { assetId } = _ref11, options = require_CalmLensUtils._objectWithoutProperties(_ref11, _excluded6);
919
+ if (!assetId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
513
920
  return (yield _this5.endpoints.getAssetChildren.submit({
514
921
  params: { assetId },
515
922
  query: require_CalmLensUtils._objectSpread2(require_CalmLensUtils._objectSpread2({}, options), {}, { pageIndex: (_options$pageIndex2 = options.pageIndex) !== null && _options$pageIndex2 !== void 0 ? _options$pageIndex2 : 0 })
516
923
  })).data;
517
924
  });
518
- return function listChildren(_x6) {
519
- return _ref11.apply(this, arguments);
925
+ return function listChildren(_x8) {
926
+ return _ref12.apply(this, arguments);
520
927
  };
521
928
  }(),
522
929
  /**
@@ -526,7 +933,7 @@ moderate: function() {
526
933
  * @returns Promise with created asset
527
934
  */
528
935
  create: function() {
529
- var _ref12 = require_CalmLensUtils._asyncToGenerator(function* (options) {
936
+ var _ref13 = require_CalmLensUtils._asyncToGenerator(function* (options) {
530
937
  const body = prepareSubmitAssetOptions(options);
531
938
  if ("content" in body || "part" in body) return yield _this5.submitRawAssetUpload(body, true);
532
939
  return (yield _this5.endpoints.postUploadAsset.submit({
@@ -535,19 +942,20 @@ moderate: function() {
535
942
  query: { queue: true }
536
943
  })).data;
537
944
  });
538
- return function create(_x7) {
539
- return _ref12.apply(this, arguments);
945
+ return function create(_x9) {
946
+ return _ref13.apply(this, arguments);
540
947
  };
541
948
  }(),
542
949
  /**
543
- * Submit a new asset and analyze it synchronously
950
+ * Submit a new asset and moderate it synchronously
544
951
  * The asset will be classified immediately before the response is returned.
545
952
  * This may take longer but ensures the asset is fully processed.
546
953
  * @param options - Asset submission options
547
954
  * @returns Promise with created and analyzed asset
548
955
  */
549
- analyze: function() {
550
- var _ref13 = require_CalmLensUtils._asyncToGenerator(function* (options) {
956
+ moderate: function() {
957
+ var _ref14 = require_CalmLensUtils._asyncToGenerator(function* (options) {
958
+ if ("content" in options && "plainText" in options.content && (typeof options.content.plainText !== "string" || !options.content.plainText.trim())) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Text to moderate must be a non-empty string" });
551
959
  const body = prepareSubmitAssetOptions(options);
552
960
  if ("content" in body || "part" in body) return yield _this5.submitRawAssetUpload(body, false);
553
961
  return (yield _this5.endpoints.postUploadAsset.submit({
@@ -556,8 +964,8 @@ moderate: function() {
556
964
  query: { queue: false }
557
965
  })).data;
558
966
  });
559
- return function analyze(_x8) {
560
- return _ref13.apply(this, arguments);
967
+ return function moderate(_x10) {
968
+ return _ref14.apply(this, arguments);
561
969
  };
562
970
  }(),
563
971
  /**
@@ -567,10 +975,10 @@ moderate: function() {
567
975
  * @returns Promise with asset data
568
976
  */
569
977
  uploadPart: function() {
570
- var _ref14 = require_CalmLensUtils._asyncToGenerator(function* ({ assetId, part }) {
978
+ var _ref15 = require_CalmLensUtils._asyncToGenerator(function* ({ assetId, part }) {
571
979
  var _part$sizeInBytes3, _this$multipartUpload;
572
- if (!assetId) throw new Error("Asset ID is required");
573
- if (!part) throw new Error("Part options are required");
980
+ if (!assetId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
981
+ if (!part) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Part options are required" });
574
982
  const validation = require_CalmLensUtils.validateAssetPayload(part, {
575
983
  multipart: true,
576
984
  isFinal: part.isFinal
@@ -580,13 +988,13 @@ moderate: function() {
580
988
  const partSizeInBytes = (_part$sizeInBytes3 = part.sizeInBytes) !== null && _part$sizeInBytes3 !== void 0 ? _part$sizeInBytes3 : require_CalmLensUtils.getAssetPayloadByteLength(part);
581
989
  if (existingImageSizeInBytes !== void 0 && partSizeInBytes !== void 0) {
582
990
  const totalSizeInBytes = existingImageSizeInBytes + partSizeInBytes;
583
- if (totalSizeInBytes > 20971520) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
584
- if (part.isFinal && totalSizeInBytes < 10485760) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
991
+ if (totalSizeInBytes > require_CalmLensUtils.MAX_IMAGE_UPLOAD_BYTES) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
992
+ if (part.isFinal && totalSizeInBytes < require_CalmLensUtils.MIN_MULTIPART_IMAGE_UPLOAD_BYTES) throw require_CalmLensUtils.calmLensError(require_CalmLensUtils.PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
585
993
  }
586
994
  return yield _this5.submitRawAssetPart(assetId, part, (_this$multipartUpload = _this5.multipartUploadQueues.get(assetId)) !== null && _this$multipartUpload !== void 0 ? _this$multipartUpload : false);
587
995
  });
588
- return function uploadPart(_x9) {
589
- return _ref14.apply(this, arguments);
996
+ return function uploadPart(_x11) {
997
+ return _ref15.apply(this, arguments);
590
998
  };
591
999
  }(),
592
1000
  /**
@@ -595,11 +1003,11 @@ moderate: function() {
595
1003
  * auth cookies or API keys to the CDN on every media request.
596
1004
  */
597
1005
  createSignedUrl: function() {
598
- var _ref16 = require_CalmLensUtils._asyncToGenerator(function* (_ref15) {
1006
+ var _ref17 = require_CalmLensUtils._asyncToGenerator(function* (_ref16) {
599
1007
  var _options$resource2, _options$expiresInSec;
600
- let { assetId } = _ref15, options = require_CalmLensUtils._objectWithoutProperties(_ref15, _excluded7);
601
- if (!assetId) throw new Error("Asset ID is required");
602
- if (options.lens && options.transform) throw new Error("Specify either a lens or a transform, not both");
1008
+ let { assetId } = _ref16, options = require_CalmLensUtils._objectWithoutProperties(_ref16, _excluded7);
1009
+ if (!assetId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
1010
+ if (options.lens && options.transform) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Specify either a lens or a transform, not both" });
603
1011
  return (yield _this5.endpoints.postAssetSignedUrl.submit({
604
1012
  body: {
605
1013
  resource: (_options$resource2 = options.resource) !== null && _options$resource2 !== void 0 ? _options$resource2 : "content",
@@ -610,20 +1018,33 @@ moderate: function() {
610
1018
  params: { assetId }
611
1019
  })).data;
612
1020
  });
613
- return function createSignedUrl(_x10) {
614
- return _ref16.apply(this, arguments);
1021
+ return function createSignedUrl(_x12) {
1022
+ return _ref17.apply(this, arguments);
615
1023
  };
616
1024
  }(),
617
1025
  move: function() {
618
- var _ref17 = require_CalmLensUtils._asyncToGenerator(function* ({ assetId, folderId }) {
619
- if (!assetId) throw new Error("Asset ID is required");
1026
+ var _ref18 = require_CalmLensUtils._asyncToGenerator(function* ({ assetId, folderId }) {
1027
+ if (!assetId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
620
1028
  return (yield _this5.endpoints.moveAsset.submit({
621
1029
  params: { assetId },
622
1030
  body: { folderId }
623
1031
  })).data;
624
1032
  });
625
- return function move(_x11) {
626
- return _ref17.apply(this, arguments);
1033
+ return function move(_x13) {
1034
+ return _ref18.apply(this, arguments);
1035
+ };
1036
+ }(),
1037
+ /**
1038
+ * Processes an asset that failed (status `error`) again. It returns to `pending` and is
1039
+ * moderated like a new upload; its content must still be stored.
1040
+ */
1041
+ retry: function() {
1042
+ var _ref19 = require_CalmLensUtils._asyncToGenerator(function* ({ assetId }) {
1043
+ if (!assetId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
1044
+ return (yield _this5.endpoints.retryAsset.submit({ params: { assetId } })).data;
1045
+ });
1046
+ return function retry(_x14) {
1047
+ return _ref19.apply(this, arguments);
627
1048
  };
628
1049
  }()
629
1050
  };
@@ -633,17 +1054,18 @@ moderate: function() {
633
1054
  return {
634
1055
  /**
635
1056
  * List project events after a cursor, oldest first. Call without `after` to get a cursor
636
- * for "now", then poll with the returned `cursor`. Event bodies match webhook deliveries.
1057
+ * for "now", then poll with the returned `cursor`. Webhook deliveries carry the same events
1058
+ * reshaped as `{ id, type, createdAt, projectId, data }`.
637
1059
  */
638
1060
  list: function() {
639
- var _ref18 = require_CalmLensUtils._asyncToGenerator(function* (options = {}) {
1061
+ var _ref20 = require_CalmLensUtils._asyncToGenerator(function* (options = {}) {
640
1062
  return (yield _this6.endpoints.getEvents.submit({
641
1063
  params: { projectId: _this6.options.projectId },
642
1064
  query: options
643
1065
  })).data;
644
1066
  });
645
1067
  return function list() {
646
- return _ref18.apply(this, arguments);
1068
+ return _ref20.apply(this, arguments);
647
1069
  };
648
1070
  }() };
649
1071
  }
@@ -651,65 +1073,65 @@ list: function() {
651
1073
  var _this7 = this;
652
1074
  return {
653
1075
  list: function() {
654
- var _ref19 = require_CalmLensUtils._asyncToGenerator(function* () {
1076
+ var _ref21 = require_CalmLensUtils._asyncToGenerator(function* () {
655
1077
  return (yield _this7.endpoints.getFolders.submit({ params: { projectId: _this7.options.projectId } })).data.folders;
656
1078
  });
657
1079
  return function list() {
658
- return _ref19.apply(this, arguments);
1080
+ return _ref21.apply(this, arguments);
659
1081
  };
660
1082
  }(),
661
1083
  retrieve: function() {
662
- var _ref20 = require_CalmLensUtils._asyncToGenerator(function* ({ folderId }) {
663
- if (!folderId) throw new Error("Folder ID is required");
1084
+ var _ref22 = require_CalmLensUtils._asyncToGenerator(function* ({ folderId }) {
1085
+ if (!folderId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
664
1086
  return (yield _this7.endpoints.getFolder.submit({ params: { folderId } })).data;
665
1087
  });
666
- return function retrieve(_x12) {
667
- return _ref20.apply(this, arguments);
1088
+ return function retrieve(_x15) {
1089
+ return _ref22.apply(this, arguments);
668
1090
  };
669
1091
  }(),
670
1092
  create: function() {
671
- var _ref21 = require_CalmLensUtils._asyncToGenerator(function* (options) {
1093
+ var _ref23 = require_CalmLensUtils._asyncToGenerator(function* (options) {
672
1094
  return (yield _this7.endpoints.postFolder.submit({
673
1095
  params: { projectId: _this7.options.projectId },
674
1096
  body: options
675
1097
  })).data;
676
1098
  });
677
- return function create(_x13) {
678
- return _ref21.apply(this, arguments);
1099
+ return function create(_x16) {
1100
+ return _ref23.apply(this, arguments);
679
1101
  };
680
1102
  }(),
681
1103
  update: function() {
682
- var _ref23 = require_CalmLensUtils._asyncToGenerator(function* (_ref22) {
683
- let { folderId } = _ref22, body = require_CalmLensUtils._objectWithoutProperties(_ref22, _excluded8);
684
- if (!folderId) throw new Error("Folder ID is required");
1104
+ var _ref25 = require_CalmLensUtils._asyncToGenerator(function* (_ref24) {
1105
+ let { folderId } = _ref24, body = require_CalmLensUtils._objectWithoutProperties(_ref24, _excluded8);
1106
+ if (!folderId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
685
1107
  return (yield _this7.endpoints.patchFolder.submit({
686
1108
  params: { folderId },
687
1109
  body
688
1110
  })).data;
689
1111
  });
690
- return function update(_x14) {
691
- return _ref23.apply(this, arguments);
1112
+ return function update(_x17) {
1113
+ return _ref25.apply(this, arguments);
692
1114
  };
693
1115
  }(),
694
1116
  delete: function() {
695
- var _ref24 = require_CalmLensUtils._asyncToGenerator(function* ({ folderId }) {
696
- if (!folderId) throw new Error("Folder ID is required");
1117
+ var _ref26 = require_CalmLensUtils._asyncToGenerator(function* ({ folderId }) {
1118
+ if (!folderId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
697
1119
  yield _this7.endpoints.deleteFolder.submit({ params: { folderId } });
698
1120
  });
699
- return function _delete(_x15) {
700
- return _ref24.apply(this, arguments);
1121
+ return function _delete(_x18) {
1122
+ return _ref26.apply(this, arguments);
701
1123
  };
702
1124
  }(),
703
1125
  move: function() {
704
- var _ref25 = require_CalmLensUtils._asyncToGenerator(function* ({ folderId, parentId }) {
705
- if (!folderId) throw new Error("Folder ID is required");
1126
+ var _ref27 = require_CalmLensUtils._asyncToGenerator(function* ({ folderId, parentId }) {
1127
+ if (!folderId) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
706
1128
  return (yield _this7.endpoints.moveFolder.submit({
707
1129
  params: { folderId },
708
1130
  body: { parentId }
709
1131
  })).data;
710
1132
  });
711
- return function move(_x16) {
712
- return _ref25.apply(this, arguments);
1133
+ return function move(_x19) {
1134
+ return _ref27.apply(this, arguments);
713
1135
  };
714
1136
  }()
715
1137
  };
@@ -721,7 +1143,7 @@ list: function() {
721
1143
  ensureLens(options) {
722
1144
  var _this8 = this;
723
1145
  return require_CalmLensUtils._asyncToGenerator(function* () {
724
- if (!options.identifier) throw new Error("Lens identifier is required");
1146
+ if (!options.identifier) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Lens identifier is required" });
725
1147
  const [lens] = yield _this8.ensureLenses({ lenses: [options] });
726
1148
  return lens;
727
1149
  })();
@@ -733,8 +1155,8 @@ list: function() {
733
1155
  ensureLenses({ lenses }) {
734
1156
  var _this9 = this;
735
1157
  return require_CalmLensUtils._asyncToGenerator(function* () {
736
- if (lenses.length === 0) throw new Error("At least one lens is required");
737
- if (lenses.some((option) => !option.identifier)) throw new Error("Lens identifier is required");
1158
+ if (lenses.length === 0) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "At least one lens is required" });
1159
+ if (lenses.some((option) => !option.identifier)) throw require_CalmLensUtils.calmLensError({ id: "upload/invalid-payload" }, { message: "Lens identifier is required" });
738
1160
  const missingOptions = [];
739
1161
  const missingKeys = /* @__PURE__ */ new Set();
740
1162
  for (const option of lenses) {
@@ -765,7 +1187,7 @@ list: function() {
765
1187
  });
766
1188
  for (const [index, lens] of result.data.lenses.entries()) {
767
1189
  const optionsForLens = options[index];
768
- if (!optionsForLens) throw new Error("CalmLens returned an unexpected lens response");
1190
+ if (!optionsForLens) throw require_CalmLensUtils.calmLensError({ id: "sdk/invalid-response" }, { message: "CalmLens returned an unexpected lens response" });
769
1191
  for (const [cacheKey, cachedLens] of _this10.ensuredLenses) if (cachedLens.identifier === optionsForLens.identifier) _this10.ensuredLenses.delete(cacheKey);
770
1192
  _this10.ensuredLenses.set(getEnsureLensCacheKey(optionsForLens), lens);
771
1193
  }
@@ -775,4 +1197,10 @@ list: function() {
775
1197
  //#endregion
776
1198
  exports.CalmLensClient = CalmLensClient;
777
1199
  exports.CalmLensError = require_CalmLensUtils.CalmLensError;
778
- exports.verifyWebhookSignature = require_CalmLensUtils.verifyWebhookSignature;
1200
+ exports.MEDIA_TEST_SIGNALS = MEDIA_TEST_SIGNALS;
1201
+ exports.WEBHOOK_DELIVERY_HEADER = WEBHOOK_DELIVERY_HEADER;
1202
+ exports.WEBHOOK_SIGNATURE_HEADER = WEBHOOK_SIGNATURE_HEADER;
1203
+ exports.WEBHOOK_SIGNATURE_TOLERANCE_SECONDS = WEBHOOK_SIGNATURE_TOLERANCE_SECONDS;
1204
+ exports.WEBHOOK_TIMESTAMP_HEADER = WEBHOOK_TIMESTAMP_HEADER;
1205
+ exports.generateMediaTestCode = generateMediaTestCode;
1206
+ exports.verifyWebhookSignature = verifyWebhookSignature;