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/README.md +72 -39
- package/bin/calmlens.js +240 -79
- package/cjs/CalmLensTypes-DG_kHVqY.d.ts +3521 -0
- package/cjs/{CalmLensUtils-DocJkqQj.js → CalmLensUtils-0QaxbI3A.js} +105 -93
- package/cjs/index.d.ts +2607 -24
- package/cjs/index.js +548 -120
- package/cjs/testing.d.ts +3 -2
- package/cjs/testing.js +39 -45
- package/esm/CalmLensTypes-DG_kHVqY.d.ts +3521 -0
- package/esm/{CalmLensUtils--N_91gHC.js → CalmLensUtils-BQEgxGWk.js} +78 -88
- package/esm/index.d.ts +2607 -24
- package/esm/index.js +541 -120
- package/esm/testing.d.ts +3 -2
- package/esm/testing.js +38 -22
- package/package.json +2 -2
- package/cjs/CalmLensTypes-Bnq4u8HJ.d.ts +0 -1758
- package/esm/CalmLensTypes-Bnq4u8HJ.d.ts +0 -1758
package/bin/calmlens.js
CHANGED
|
@@ -107,7 +107,7 @@ const PUBLIC_ERROR_CODES = {
|
|
|
107
107
|
}),
|
|
108
108
|
FILE_TOO_LARGE: new sendable_error.ErrorCode({
|
|
109
109
|
id: "upload/file-too-large",
|
|
110
|
-
defaultMessage: "File size exceeds limit. Maximum
|
|
110
|
+
defaultMessage: "File size exceeds limit. Maximum direct image size is 10MB, audio/video size is 50MiB, and other files is 5GB.",
|
|
111
111
|
status: 400
|
|
112
112
|
}),
|
|
113
113
|
IMAGE_REQUIRES_MULTIPART_UPLOAD: new sendable_error.ErrorCode({
|
|
@@ -190,6 +190,16 @@ const PUBLIC_ERROR_CODES = {
|
|
|
190
190
|
defaultMessage: "Asset access is restricted by a safety hold.",
|
|
191
191
|
status: 423
|
|
192
192
|
}),
|
|
193
|
+
ASSET_NOT_RETRYABLE: new sendable_error.ErrorCode({
|
|
194
|
+
id: "asset/not-retryable",
|
|
195
|
+
defaultMessage: "Only assets that failed to process (status error) can be retried.",
|
|
196
|
+
status: 409
|
|
197
|
+
}),
|
|
198
|
+
ASSET_CONTENT_UNAVAILABLE: new sendable_error.ErrorCode({
|
|
199
|
+
id: "asset/content-unavailable",
|
|
200
|
+
defaultMessage: "This asset's content is no longer stored, so it can't be processed again. Upload it again instead.",
|
|
201
|
+
status: 409
|
|
202
|
+
}),
|
|
193
203
|
SUPPORT_TICKET_NOT_FOUND: new sendable_error.ErrorCode({
|
|
194
204
|
id: "support/ticket-not-found",
|
|
195
205
|
defaultMessage: "Support ticket not found.",
|
|
@@ -227,6 +237,8 @@ const PUBLIC_ERROR_CODES = {
|
|
|
227
237
|
})
|
|
228
238
|
};
|
|
229
239
|
PUBLIC_ERROR_CODES.MISSING_TOKEN, PUBLIC_ERROR_CODES.INVALID_API_KEY, PUBLIC_ERROR_CODES.API_KEY_PROJECT_MISMATCH;
|
|
240
|
+
const MAX_IMAGE_UPLOAD_BYTES = /* @__PURE__ */ (() => 20971520)();
|
|
241
|
+
const MIN_MULTIPART_IMAGE_UPLOAD_BYTES = /* @__PURE__ */ (() => 10485760)();
|
|
230
242
|
const REJECTED_UPLOAD_MIME_TYPE_SET = /* @__PURE__ */ new Set([
|
|
231
243
|
"application/octet-stream",
|
|
232
244
|
"multipart/form-data",
|
|
@@ -249,18 +261,18 @@ var CalmLensError = class extends Error {
|
|
|
249
261
|
constructor(errorCode, options) {
|
|
250
262
|
const code = "getId" in errorCode ? errorCode.getId() : errorCode.id;
|
|
251
263
|
const defaultMessage = "getDefaultMessage" in errorCode ? errorCode.getDefaultMessage() : errorCode.defaultMessage;
|
|
252
|
-
super(`[calmlens] ${options?.message ?? defaultMessage ?? code}
|
|
264
|
+
super(`[calmlens] ${options?.message ?? defaultMessage ?? code}`, { cause: options?.cause });
|
|
253
265
|
this.name = "CalmLensError";
|
|
254
266
|
this.code = code;
|
|
255
267
|
this.details = options?.details;
|
|
268
|
+
this.status = options?.status;
|
|
256
269
|
}
|
|
257
270
|
};
|
|
258
271
|
const calmLensError = (errorCode, options) => new CalmLensError(errorCode, options);
|
|
259
272
|
//#endregion
|
|
260
273
|
//#region src/client/CalmLensUtils.ts
|
|
261
|
-
/** Converts `text.moderate()` options into a plain-text asset submission. */
|
|
262
274
|
const toTextAssetOptions = ({ text, name, ...options }) => {
|
|
263
|
-
if (typeof text !== "string" || text.trim()
|
|
275
|
+
if (typeof text !== "string" || !text.trim()) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Text to moderate must be a non-empty string" });
|
|
264
276
|
return {
|
|
265
277
|
...options,
|
|
266
278
|
name: name ?? "text",
|
|
@@ -270,19 +282,72 @@ const toTextAssetOptions = ({ text, name, ...options }) => {
|
|
|
270
282
|
}
|
|
271
283
|
};
|
|
272
284
|
};
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
285
|
+
//#endregion
|
|
286
|
+
//#region src/client/CalmLensWebhooks.ts
|
|
287
|
+
const WEBHOOK_DELIVERY_HEADER = "x-calmlens-delivery";
|
|
288
|
+
const WEBHOOK_TIMESTAMP_HEADER = "x-calmlens-timestamp";
|
|
289
|
+
const WEBHOOK_SIGNATURE_HEADER = "x-calmlens-signature";
|
|
290
|
+
/** The JSON body of a webhook delivery for a stored event. */
|
|
291
|
+
const toWebhookEventPayload = (event) => ({
|
|
292
|
+
id: event.id,
|
|
293
|
+
type: event.type,
|
|
294
|
+
createdAt: event.createdAt,
|
|
295
|
+
projectId: event.projectId,
|
|
296
|
+
data: {
|
|
297
|
+
severity: event.severity,
|
|
298
|
+
title: event.title,
|
|
299
|
+
description: event.description ?? null,
|
|
300
|
+
assetId: event.assetId ?? null,
|
|
301
|
+
asset: event.asset ?? null,
|
|
302
|
+
facts: event.facts
|
|
303
|
+
}
|
|
304
|
+
});
|
|
305
|
+
const encoder = new TextEncoder();
|
|
306
|
+
const hmacSha256Hex = async (secret, message) => {
|
|
276
307
|
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
277
308
|
name: "HMAC",
|
|
278
309
|
hash: "SHA-256"
|
|
279
310
|
}, false, ["sign"]);
|
|
280
|
-
const
|
|
281
|
-
|
|
282
|
-
|
|
311
|
+
const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(message));
|
|
312
|
+
return Array.from(new Uint8Array(signature), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
313
|
+
};
|
|
314
|
+
/** Constant-time comparison of two strings of the same length. */
|
|
315
|
+
const timingSafeEqual = (a, b) => {
|
|
316
|
+
if (a.length !== b.length) return false;
|
|
283
317
|
let diff = 0;
|
|
284
|
-
for (let i = 0; i <
|
|
318
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
285
319
|
return diff === 0;
|
|
320
|
+
};
|
|
321
|
+
/** `v1=<hex HMAC-SHA256 of "<timestamp>.<body>">`, the `x-calmlens-signature` header value. */
|
|
322
|
+
const createWebhookSignatureHeader = async (secret, timestamp, body) => `v1=${await hmacSha256Hex(secret, `${timestamp}.${body}`)}`;
|
|
323
|
+
/** Headers for one signed delivery of `body`. */
|
|
324
|
+
const createWebhookHeaders = async (options) => {
|
|
325
|
+
const timestamp = options.timestampSeconds ?? Math.floor(Date.now() / 1e3);
|
|
326
|
+
return {
|
|
327
|
+
"content-type": "application/json",
|
|
328
|
+
[WEBHOOK_DELIVERY_HEADER]: options.deliveryId,
|
|
329
|
+
[WEBHOOK_TIMESTAMP_HEADER]: String(timestamp),
|
|
330
|
+
[WEBHOOK_SIGNATURE_HEADER]: await createWebhookSignatureHeader(options.secret, timestamp, options.body)
|
|
331
|
+
};
|
|
332
|
+
};
|
|
333
|
+
/**
|
|
334
|
+
* Verifies a webhook delivery: `x-calmlens-signature` must contain a `v1=` HMAC-SHA256 of
|
|
335
|
+
* `"<x-calmlens-timestamp>.<raw body>"`, and the timestamp must be within `toleranceSeconds`
|
|
336
|
+
* (default 300) of now. Returns `false` for anything missing or malformed.
|
|
337
|
+
*/
|
|
338
|
+
async function verifyWebhookSignature({ payload, signature, timestamp, secret, toleranceSeconds = 300, now }) {
|
|
339
|
+
if (!secret || !signature || timestamp === null || timestamp === void 0) return false;
|
|
340
|
+
const timestampText = String(timestamp).trim();
|
|
341
|
+
if (!/^\d+$/.test(timestampText)) return false;
|
|
342
|
+
const nowMs = now === void 0 ? Date.now() : now instanceof Date ? now.getTime() : now;
|
|
343
|
+
if (Math.abs(Math.floor(nowMs / 1e3) - Number(timestampText)) > toleranceSeconds) return false;
|
|
344
|
+
const candidates = signature.split(",").map((part) => part.trim()).filter((part) => part.startsWith("v1=")).map((part) => part.slice(3).toLowerCase());
|
|
345
|
+
if (candidates.length === 0) return false;
|
|
346
|
+
const body = typeof payload === "string" ? payload : JSON.stringify(payload);
|
|
347
|
+
const expected = await hmacSha256Hex(secret, `${timestampText}.${body}`);
|
|
348
|
+
let matched = false;
|
|
349
|
+
for (const candidate of candidates) if (timingSafeEqual(expected, candidate)) matched = true;
|
|
350
|
+
return matched;
|
|
286
351
|
}
|
|
287
352
|
//#endregion
|
|
288
353
|
//#region src/client/CalmLensClient.ts
|
|
@@ -337,7 +402,7 @@ const normalizeAssetOptionsForRequest = (options) => {
|
|
|
337
402
|
const toRawUploadBody = (payload) => {
|
|
338
403
|
const data = assetToData(normalizePayloadForRequest(payload));
|
|
339
404
|
if (data instanceof Response) {
|
|
340
|
-
if (!data.body) throw
|
|
405
|
+
if (!data.body) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Response upload data must have a body" });
|
|
341
406
|
return data.body;
|
|
342
407
|
}
|
|
343
408
|
if (data instanceof ArrayBuffer || data instanceof Blob) return data;
|
|
@@ -355,8 +420,8 @@ const assertValidUploadMimeType = (mimeType) => {
|
|
|
355
420
|
};
|
|
356
421
|
const isImageMimeType = (mimeType) => mimeType.toLowerCase().startsWith("image/");
|
|
357
422
|
const prepareSubmitAssetOptions = (options) => {
|
|
358
|
-
if (!("content" in options) && !("url" in options) && !("part" in options)) throw
|
|
359
|
-
if (!options.name) throw
|
|
423
|
+
if (!("content" in options) && !("url" in options) && !("part" in options)) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Either file content, URL, or multipart part is required" });
|
|
424
|
+
if (!options.name) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset name is required" });
|
|
360
425
|
if (!("part" in options) && "isFinal" in options) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "isFinal is only valid for multipart uploads" });
|
|
361
426
|
if ("part" in options && options.part.partNumber && options.part.partNumber > 1) throw calmLensError(PUBLIC_ERROR_CODES.USE_UPLOAD_PART);
|
|
362
427
|
if ("content" in options) {
|
|
@@ -370,8 +435,8 @@ const prepareSubmitAssetOptions = (options) => {
|
|
|
370
435
|
assertValidUploadMimeType(options.part.type);
|
|
371
436
|
const partSizeInBytes = options.part.sizeInBytes ?? getAssetPayloadByteLength(options.part);
|
|
372
437
|
if (isImageMimeType(options.part.type) && partSizeInBytes !== void 0) {
|
|
373
|
-
if (partSizeInBytes >
|
|
374
|
-
if (options.part.isFinal && partSizeInBytes <
|
|
438
|
+
if (partSizeInBytes > MAX_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
|
|
439
|
+
if (options.part.isFinal && partSizeInBytes < MIN_MULTIPART_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
|
|
375
440
|
}
|
|
376
441
|
const validation = validateAssetPayload(options.part, {
|
|
377
442
|
multipart: true,
|
|
@@ -382,7 +447,7 @@ const prepareSubmitAssetOptions = (options) => {
|
|
|
382
447
|
return options;
|
|
383
448
|
};
|
|
384
449
|
const appendCdnSelector = (url, options) => {
|
|
385
|
-
if (options.lens && options.transform) throw
|
|
450
|
+
if (options.lens && options.transform) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Specify either a lens or a transform, not both" });
|
|
386
451
|
if (options.lens) return `${url}/@${encodeURIComponent(options.lens)}`;
|
|
387
452
|
if (!options.transform) return url;
|
|
388
453
|
return `${url}/${encodeURI(options.transform.replace(/^\/+/, ""))}`;
|
|
@@ -401,9 +466,34 @@ const withApiKeyHeader = (init, apiKey) => {
|
|
|
401
466
|
headers.set("X-Api-Key", apiKey);
|
|
402
467
|
return {
|
|
403
468
|
...init,
|
|
469
|
+
redirect: "error",
|
|
404
470
|
headers: Object.fromEntries(headers.entries())
|
|
405
471
|
};
|
|
406
472
|
};
|
|
473
|
+
const requestSignal = (options, signal) => {
|
|
474
|
+
const signals = [
|
|
475
|
+
options.signal,
|
|
476
|
+
signal,
|
|
477
|
+
AbortSignal.timeout(options.timeoutMs ?? 12e4)
|
|
478
|
+
].filter((value) => value != null);
|
|
479
|
+
return AbortSignal.any(signals);
|
|
480
|
+
};
|
|
481
|
+
const safeFetch = (fetchImpl, options) => (async (input, init) => {
|
|
482
|
+
const signal = requestSignal(options, init?.signal ?? (input instanceof Request ? input.signal : void 0));
|
|
483
|
+
try {
|
|
484
|
+
signal.throwIfAborted();
|
|
485
|
+
return await fetchImpl(input, {
|
|
486
|
+
...init,
|
|
487
|
+
redirect: "error",
|
|
488
|
+
signal
|
|
489
|
+
});
|
|
490
|
+
} catch (cause) {
|
|
491
|
+
throw calmLensError({ id: signal.aborted ? signal.reason?.name === "TimeoutError" ? "sdk/timeout" : "sdk/cancelled" : "sdk/transport-error" }, {
|
|
492
|
+
message: signal.aborted ? "Request aborted" : "Request failed",
|
|
493
|
+
cause
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
});
|
|
407
497
|
const createApi = (options) => {
|
|
408
498
|
return new api_def.Api({
|
|
409
499
|
name: "Calm Lens",
|
|
@@ -417,13 +507,24 @@ const createApi = (options) => {
|
|
|
417
507
|
if (context.error) throw normalizeApiError(context.error);
|
|
418
508
|
} }
|
|
419
509
|
],
|
|
420
|
-
requestBackend: options.requestBackend
|
|
510
|
+
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))
|
|
421
511
|
});
|
|
422
512
|
};
|
|
423
513
|
const isApiErrorPayload = (value) => {
|
|
424
514
|
return !!value && typeof value === "object" && typeof value.code === "string";
|
|
425
515
|
};
|
|
426
516
|
const normalizeApiError = (error) => {
|
|
517
|
+
let cause = error;
|
|
518
|
+
const seen = /* @__PURE__ */ new Set();
|
|
519
|
+
while (cause instanceof Error && !seen.has(cause)) {
|
|
520
|
+
seen.add(cause);
|
|
521
|
+
if (cause instanceof CalmLensError) return cause;
|
|
522
|
+
if (cause.name === "AbortError" || cause.name === "TimeoutError") return calmLensError({ id: cause.name === "TimeoutError" ? "sdk/timeout" : "sdk/cancelled" }, {
|
|
523
|
+
message: "Request aborted",
|
|
524
|
+
cause
|
|
525
|
+
});
|
|
526
|
+
cause = cause.cause;
|
|
527
|
+
}
|
|
427
528
|
const response = error instanceof Error ? (0, api_def.getErrorResponse)(error) : void 0;
|
|
428
529
|
if (error instanceof Error && (0, api_def.isRequestError)(error) && isApiErrorPayload(response?.data)) {
|
|
429
530
|
const { code, message, details, traceId } = response.data;
|
|
@@ -432,6 +533,8 @@ const normalizeApiError = (error) => {
|
|
|
432
533
|
defaultMessage: message
|
|
433
534
|
}, {
|
|
434
535
|
message,
|
|
536
|
+
status: response?.status,
|
|
537
|
+
cause: error,
|
|
435
538
|
details: {
|
|
436
539
|
...details,
|
|
437
540
|
traceId,
|
|
@@ -439,7 +542,12 @@ const normalizeApiError = (error) => {
|
|
|
439
542
|
}
|
|
440
543
|
});
|
|
441
544
|
}
|
|
442
|
-
return error;
|
|
545
|
+
if (error instanceof CalmLensError) return error;
|
|
546
|
+
return calmLensError({ id: response ? response.ok ? "sdk/invalid-response" : "sdk/http-error" : "sdk/transport-error" }, {
|
|
547
|
+
message: response ? `HTTP ${response.status}` : error.message,
|
|
548
|
+
status: response?.status,
|
|
549
|
+
cause: error
|
|
550
|
+
});
|
|
443
551
|
};
|
|
444
552
|
const createEndpoints = (api) => {
|
|
445
553
|
const getFolders = api.endpoint().paramsOf().responseOf().build({
|
|
@@ -512,6 +620,11 @@ const createEndpoints = (api) => {
|
|
|
512
620
|
method: "post",
|
|
513
621
|
path: "/assets/:assetId/move"
|
|
514
622
|
});
|
|
623
|
+
const retryAsset = api.endpoint().paramsOf().responseOf().build({
|
|
624
|
+
id: "retryAsset",
|
|
625
|
+
method: "post",
|
|
626
|
+
path: "/assets/:assetId/retry"
|
|
627
|
+
});
|
|
515
628
|
const getEvents = api.endpoint().paramsOf().queryOf().responseOf().build({
|
|
516
629
|
id: "getEvents",
|
|
517
630
|
method: "get",
|
|
@@ -532,6 +645,7 @@ const createEndpoints = (api) => {
|
|
|
532
645
|
postAssetSignedUrl,
|
|
533
646
|
postAssetPart,
|
|
534
647
|
moveAsset,
|
|
648
|
+
retryAsset,
|
|
535
649
|
ensureLens: api.endpoint().bodyOf().paramsOf().responseOf().build({
|
|
536
650
|
id: "ensureLens",
|
|
537
651
|
method: "put",
|
|
@@ -545,29 +659,35 @@ const createEndpoints = (api) => {
|
|
|
545
659
|
getEvents
|
|
546
660
|
};
|
|
547
661
|
};
|
|
548
|
-
var CalmLensClient = class {
|
|
662
|
+
var CalmLensClient = class CalmLensClient {
|
|
549
663
|
/**
|
|
550
|
-
*
|
|
664
|
+
* Verifies that a webhook delivery came from CalmLens: checks the `v1=` HMAC-SHA256 in
|
|
665
|
+
* `x-calmlens-signature` over `"<x-calmlens-timestamp>.<raw body>"` and rejects timestamps
|
|
666
|
+
* more than `toleranceSeconds` (default 300) from now, which stops replayed deliveries.
|
|
551
667
|
*
|
|
552
|
-
* @param payload - The
|
|
553
|
-
* @param
|
|
554
|
-
* @param
|
|
555
|
-
* @
|
|
668
|
+
* @param options.payload - The raw request body, exactly as received (verify before parsing)
|
|
669
|
+
* @param options.signature - The 'x-calmlens-signature' header value
|
|
670
|
+
* @param options.timestamp - The 'x-calmlens-timestamp' header value
|
|
671
|
+
* @param options.secret - The connector's signing secret
|
|
672
|
+
* @param options.toleranceSeconds - Allowed clock distance in seconds (default 300)
|
|
673
|
+
* @param options.now - Override the current time (Date or epoch milliseconds), for tests
|
|
674
|
+
* @returns Promise<boolean> - True if the signature is valid and fresh, false otherwise
|
|
556
675
|
*
|
|
557
676
|
* @example
|
|
558
677
|
* ```javascript
|
|
559
|
-
* // In your webhook handler
|
|
560
|
-
* const
|
|
561
|
-
* const payload = req.body;
|
|
678
|
+
* // In your webhook handler (e.g. a Fetch API Request)
|
|
679
|
+
* const payload = await request.text();
|
|
562
680
|
* const isValid = await CalmLensClient.verifyWebhookSignature({
|
|
563
681
|
* payload,
|
|
564
|
-
*
|
|
682
|
+
* signature: request.headers.get('x-calmlens-signature'),
|
|
683
|
+
* timestamp: request.headers.get('x-calmlens-timestamp'),
|
|
565
684
|
* secret: WEBHOOK_SECRET,
|
|
566
685
|
* });
|
|
567
686
|
*
|
|
568
687
|
* if (!isValid) {
|
|
569
|
-
* return
|
|
688
|
+
* return new Response('Unauthorized', { status: 401 });
|
|
570
689
|
* }
|
|
690
|
+
* const event = JSON.parse(payload); // { id, type, createdAt, projectId, data }
|
|
571
691
|
* ```
|
|
572
692
|
*/
|
|
573
693
|
static async verifyWebhookSignature(options) {
|
|
@@ -579,18 +699,30 @@ var CalmLensClient = class {
|
|
|
579
699
|
this.pendingEnsureLenses = /* @__PURE__ */ new Map();
|
|
580
700
|
this.multipartImageUploadSizes = /* @__PURE__ */ new Map();
|
|
581
701
|
this.multipartUploadQueues = /* @__PURE__ */ new Map();
|
|
582
|
-
if (!options.apiKey) throw
|
|
583
|
-
if (!options.projectId) throw
|
|
702
|
+
if (!options.apiKey) throw calmLensError({ id: "upload/invalid-payload" }, { message: "API key is required" });
|
|
703
|
+
if (!options.projectId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Project ID is required" });
|
|
704
|
+
if (options.timeoutMs !== void 0 && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0)) throw calmLensError({ id: "upload/invalid-payload" }, { message: "timeoutMs must be a positive integer" });
|
|
705
|
+
this.options = { ...options };
|
|
584
706
|
this.options.baseUrl = this.options.baseUrl ?? `https://api.calmlens.com/v1`;
|
|
585
707
|
this.options.cdnBaseUrl = this.options.cdnBaseUrl ?? `https://cdn.calmlens.com/v1`;
|
|
586
708
|
this.api = createApi(this.options);
|
|
587
709
|
this.endpoints = createEndpoints(this.api);
|
|
588
710
|
}
|
|
711
|
+
/** Scope cancellation/timeout to an operation without changing this client's defaults. */
|
|
712
|
+
withRequestOptions(options) {
|
|
713
|
+
const client = new CalmLensClient({
|
|
714
|
+
...this.options,
|
|
715
|
+
...options
|
|
716
|
+
});
|
|
717
|
+
client.multipartUploadQueues = this.multipartUploadQueues;
|
|
718
|
+
client.multipartImageUploadSizes = this.multipartImageUploadSizes;
|
|
719
|
+
return client;
|
|
720
|
+
}
|
|
589
721
|
getUploadFetch() {
|
|
590
722
|
const requestBackendFetch = this.options.requestBackend?.fetch;
|
|
591
723
|
const fetchImpl = this.options.uploadFetch ?? requestBackendFetch ?? globalThis.fetch;
|
|
592
724
|
if (!fetchImpl) throw calmLensError(SDK_ERRORS.NO_CDN_FETCH);
|
|
593
|
-
return fetchImpl;
|
|
725
|
+
return safeFetch(fetchImpl, this.options);
|
|
594
726
|
}
|
|
595
727
|
async submitRawAssetUpload(options, queue) {
|
|
596
728
|
const query = new URLSearchParams();
|
|
@@ -660,21 +792,44 @@ var CalmLensClient = class {
|
|
|
660
792
|
return asset;
|
|
661
793
|
}
|
|
662
794
|
async parseRawUploadResponse(response) {
|
|
663
|
-
|
|
795
|
+
let data;
|
|
796
|
+
try {
|
|
797
|
+
data = await response.json();
|
|
798
|
+
} catch (cause) {
|
|
799
|
+
throw 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" }, {
|
|
800
|
+
message: `Invalid JSON response (HTTP ${response.status})`,
|
|
801
|
+
status: response.status,
|
|
802
|
+
cause
|
|
803
|
+
});
|
|
804
|
+
}
|
|
664
805
|
if (!response.ok) {
|
|
665
806
|
if (isApiErrorPayload(data)) throw calmLensError({
|
|
666
807
|
id: data.code,
|
|
667
808
|
defaultMessage: data.message
|
|
668
809
|
}, {
|
|
669
810
|
message: data.message,
|
|
811
|
+
status: response.status,
|
|
670
812
|
details: {
|
|
671
813
|
...data.details,
|
|
672
814
|
traceId: data.traceId,
|
|
673
815
|
network: true
|
|
674
816
|
}
|
|
675
817
|
});
|
|
676
|
-
throw
|
|
818
|
+
throw calmLensError({ id: "sdk/http-error" }, {
|
|
819
|
+
message: `HTTP ${response.status}`,
|
|
820
|
+
status: response.status
|
|
821
|
+
});
|
|
677
822
|
}
|
|
823
|
+
if (!data || typeof data !== "object" || !("id" in data) || typeof data.id !== "string" || !data.id || !("status" in data) || ![
|
|
824
|
+
"uploading",
|
|
825
|
+
"pending",
|
|
826
|
+
"approved",
|
|
827
|
+
"rejected",
|
|
828
|
+
"error"
|
|
829
|
+
].includes(String(data.status))) throw calmLensError({ id: "sdk/invalid-response" }, {
|
|
830
|
+
message: "Expected an asset response",
|
|
831
|
+
status: response.status
|
|
832
|
+
});
|
|
678
833
|
return data;
|
|
679
834
|
}
|
|
680
835
|
get cdn() {
|
|
@@ -684,7 +839,7 @@ var CalmLensClient = class {
|
|
|
684
839
|
* Private assets require an authenticated request or signed URL.
|
|
685
840
|
*/
|
|
686
841
|
getAssetUrl: ({ assetIdentifier, ...options }) => {
|
|
687
|
-
if (!assetIdentifier) throw
|
|
842
|
+
if (!assetIdentifier) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset identifier is required" });
|
|
688
843
|
const resource = options.resource ?? "content";
|
|
689
844
|
const url = `${this.options.cdnBaseUrl.replace(/\/$/, "")}/assets/${encodeURIComponent(this.options.projectId)}/${encodeURIComponent(assetIdentifier)}/${resource}`;
|
|
690
845
|
return appendCdnSelector(url, options);
|
|
@@ -696,7 +851,7 @@ var CalmLensClient = class {
|
|
|
696
851
|
serve: async ({ assetIdentifier, init, ...urlOptions }) => {
|
|
697
852
|
const fetchImpl = this.options.cdnFetch ?? globalThis.fetch;
|
|
698
853
|
if (!fetchImpl) throw calmLensError(SDK_ERRORS.NO_CDN_FETCH);
|
|
699
|
-
return fetchImpl(this.cdn.getAssetUrl({
|
|
854
|
+
return safeFetch(fetchImpl, this.options)(this.cdn.getAssetUrl({
|
|
700
855
|
assetIdentifier,
|
|
701
856
|
...urlOptions
|
|
702
857
|
}), withApiKeyHeader(init, this.options.apiKey));
|
|
@@ -704,13 +859,7 @@ var CalmLensClient = class {
|
|
|
704
859
|
};
|
|
705
860
|
}
|
|
706
861
|
get text() {
|
|
707
|
-
return {
|
|
708
|
-
/**
|
|
709
|
-
* Moderate a short piece of text, such as a comment, caption or bio, and wait for the
|
|
710
|
-
* decision. Check `status` (`"approved"` or `"rejected"`) and `report.flagged`.
|
|
711
|
-
* The text is not retained after classification unless `processingOptions` says so.
|
|
712
|
-
*/
|
|
713
|
-
moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
862
|
+
return { moderate: async (options) => this.assets.moderate(toTextAssetOptions(options)) };
|
|
714
863
|
}
|
|
715
864
|
get assets() {
|
|
716
865
|
return {
|
|
@@ -734,11 +883,11 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
734
883
|
* @returns Promise with asset data
|
|
735
884
|
*/
|
|
736
885
|
retrieve: async ({ assetId }) => {
|
|
737
|
-
if (!assetId) throw
|
|
886
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
738
887
|
return (await this.endpoints.getAsset.submit({ params: { assetId } })).data;
|
|
739
888
|
},
|
|
740
889
|
update: async ({ assetId, ...body }) => {
|
|
741
|
-
if (!assetId) throw
|
|
890
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
742
891
|
return (await this.endpoints.patchAsset.submit({
|
|
743
892
|
params: { assetId },
|
|
744
893
|
body
|
|
@@ -751,7 +900,7 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
751
900
|
* @returns Promise with paginated child assets
|
|
752
901
|
*/
|
|
753
902
|
listChildren: async ({ assetId, ...options }) => {
|
|
754
|
-
if (!assetId) throw
|
|
903
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
755
904
|
return (await this.endpoints.getAssetChildren.submit({
|
|
756
905
|
params: { assetId },
|
|
757
906
|
query: {
|
|
@@ -776,13 +925,14 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
776
925
|
})).data;
|
|
777
926
|
},
|
|
778
927
|
/**
|
|
779
|
-
* Submit a new asset and
|
|
928
|
+
* Submit a new asset and moderate it synchronously
|
|
780
929
|
* The asset will be classified immediately before the response is returned.
|
|
781
930
|
* This may take longer but ensures the asset is fully processed.
|
|
782
931
|
* @param options - Asset submission options
|
|
783
932
|
* @returns Promise with created and analyzed asset
|
|
784
933
|
*/
|
|
785
|
-
|
|
934
|
+
moderate: async (options) => {
|
|
935
|
+
if ("content" in options && "plainText" in options.content && (typeof options.content.plainText !== "string" || !options.content.plainText.trim())) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Text to moderate must be a non-empty string" });
|
|
786
936
|
const body = prepareSubmitAssetOptions(options);
|
|
787
937
|
if ("content" in body || "part" in body) return await this.submitRawAssetUpload(body, false);
|
|
788
938
|
return (await this.endpoints.postUploadAsset.submit({
|
|
@@ -798,8 +948,8 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
798
948
|
* @returns Promise with asset data
|
|
799
949
|
*/
|
|
800
950
|
uploadPart: async ({ assetId, part }) => {
|
|
801
|
-
if (!assetId) throw
|
|
802
|
-
if (!part) throw
|
|
951
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
952
|
+
if (!part) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Part options are required" });
|
|
803
953
|
const validation = validateAssetPayload(part, {
|
|
804
954
|
multipart: true,
|
|
805
955
|
isFinal: part.isFinal
|
|
@@ -809,8 +959,8 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
809
959
|
const partSizeInBytes = part.sizeInBytes ?? getAssetPayloadByteLength(part);
|
|
810
960
|
if (existingImageSizeInBytes !== void 0 && partSizeInBytes !== void 0) {
|
|
811
961
|
const totalSizeInBytes = existingImageSizeInBytes + partSizeInBytes;
|
|
812
|
-
if (totalSizeInBytes >
|
|
813
|
-
if (part.isFinal && totalSizeInBytes <
|
|
962
|
+
if (totalSizeInBytes > MAX_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
|
|
963
|
+
if (part.isFinal && totalSizeInBytes < MIN_MULTIPART_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
|
|
814
964
|
}
|
|
815
965
|
return await this.submitRawAssetPart(assetId, part, this.multipartUploadQueues.get(assetId) ?? false);
|
|
816
966
|
},
|
|
@@ -820,8 +970,8 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
820
970
|
* auth cookies or API keys to the CDN on every media request.
|
|
821
971
|
*/
|
|
822
972
|
createSignedUrl: async ({ assetId, ...options }) => {
|
|
823
|
-
if (!assetId) throw
|
|
824
|
-
if (options.lens && options.transform) throw
|
|
973
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
974
|
+
if (options.lens && options.transform) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Specify either a lens or a transform, not both" });
|
|
825
975
|
return (await this.endpoints.postAssetSignedUrl.submit({
|
|
826
976
|
body: {
|
|
827
977
|
resource: options.resource ?? "content",
|
|
@@ -833,11 +983,19 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
833
983
|
})).data;
|
|
834
984
|
},
|
|
835
985
|
move: async ({ assetId, folderId }) => {
|
|
836
|
-
if (!assetId) throw
|
|
986
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
837
987
|
return (await this.endpoints.moveAsset.submit({
|
|
838
988
|
params: { assetId },
|
|
839
989
|
body: { folderId }
|
|
840
990
|
})).data;
|
|
991
|
+
},
|
|
992
|
+
/**
|
|
993
|
+
* Processes an asset that failed (status `error`) again. It returns to `pending` and is
|
|
994
|
+
* moderated like a new upload; its content must still be stored.
|
|
995
|
+
*/
|
|
996
|
+
retry: async ({ assetId }) => {
|
|
997
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
998
|
+
return (await this.endpoints.retryAsset.submit({ params: { assetId } })).data;
|
|
841
999
|
}
|
|
842
1000
|
};
|
|
843
1001
|
}
|
|
@@ -845,7 +1003,8 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
845
1003
|
return {
|
|
846
1004
|
/**
|
|
847
1005
|
* List project events after a cursor, oldest first. Call without `after` to get a cursor
|
|
848
|
-
* for "now", then poll with the returned `cursor`.
|
|
1006
|
+
* for "now", then poll with the returned `cursor`. Webhook deliveries carry the same events
|
|
1007
|
+
* reshaped as `{ id, type, createdAt, projectId, data }`.
|
|
849
1008
|
*/
|
|
850
1009
|
list: async (options = {}) => {
|
|
851
1010
|
return (await this.endpoints.getEvents.submit({
|
|
@@ -860,7 +1019,7 @@ list: async (options = {}) => {
|
|
|
860
1019
|
return (await this.endpoints.getFolders.submit({ params: { projectId: this.options.projectId } })).data.folders;
|
|
861
1020
|
},
|
|
862
1021
|
retrieve: async ({ folderId }) => {
|
|
863
|
-
if (!folderId) throw
|
|
1022
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
864
1023
|
return (await this.endpoints.getFolder.submit({ params: { folderId } })).data;
|
|
865
1024
|
},
|
|
866
1025
|
create: async (options) => {
|
|
@@ -870,18 +1029,18 @@ list: async (options = {}) => {
|
|
|
870
1029
|
})).data;
|
|
871
1030
|
},
|
|
872
1031
|
update: async ({ folderId, ...body }) => {
|
|
873
|
-
if (!folderId) throw
|
|
1032
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
874
1033
|
return (await this.endpoints.patchFolder.submit({
|
|
875
1034
|
params: { folderId },
|
|
876
1035
|
body
|
|
877
1036
|
})).data;
|
|
878
1037
|
},
|
|
879
1038
|
delete: async ({ folderId }) => {
|
|
880
|
-
if (!folderId) throw
|
|
1039
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
881
1040
|
await this.endpoints.deleteFolder.submit({ params: { folderId } });
|
|
882
1041
|
},
|
|
883
1042
|
move: async ({ folderId, parentId }) => {
|
|
884
|
-
if (!folderId) throw
|
|
1043
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
885
1044
|
return (await this.endpoints.moveFolder.submit({
|
|
886
1045
|
params: { folderId },
|
|
887
1046
|
body: { parentId }
|
|
@@ -894,7 +1053,7 @@ list: async (options = {}) => {
|
|
|
894
1053
|
* Supplying the same definition and version is idempotent.
|
|
895
1054
|
*/
|
|
896
1055
|
async ensureLens(options) {
|
|
897
|
-
if (!options.identifier) throw
|
|
1056
|
+
if (!options.identifier) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Lens identifier is required" });
|
|
898
1057
|
const [lens] = await this.ensureLenses({ lenses: [options] });
|
|
899
1058
|
return lens;
|
|
900
1059
|
}
|
|
@@ -903,8 +1062,8 @@ list: async (options = {}) => {
|
|
|
903
1062
|
* Each lens follows the same versioning and idempotency rules as ensureLens().
|
|
904
1063
|
*/
|
|
905
1064
|
async ensureLenses({ lenses }) {
|
|
906
|
-
if (lenses.length === 0) throw
|
|
907
|
-
if (lenses.some((option) => !option.identifier)) throw
|
|
1065
|
+
if (lenses.length === 0) throw calmLensError({ id: "upload/invalid-payload" }, { message: "At least one lens is required" });
|
|
1066
|
+
if (lenses.some((option) => !option.identifier)) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Lens identifier is required" });
|
|
908
1067
|
const missingOptions = [];
|
|
909
1068
|
const missingKeys = /* @__PURE__ */ new Set();
|
|
910
1069
|
for (const option of lenses) {
|
|
@@ -932,7 +1091,7 @@ list: async (options = {}) => {
|
|
|
932
1091
|
});
|
|
933
1092
|
for (const [index, lens] of result.data.lenses.entries()) {
|
|
934
1093
|
const optionsForLens = options[index];
|
|
935
|
-
if (!optionsForLens) throw
|
|
1094
|
+
if (!optionsForLens) throw calmLensError({ id: "sdk/invalid-response" }, { message: "CalmLens returned an unexpected lens response" });
|
|
936
1095
|
for (const [cacheKey, cachedLens] of this.ensuredLenses) if (cachedLens.identifier === optionsForLens.identifier) this.ensuredLenses.delete(cacheKey);
|
|
937
1096
|
this.ensuredLenses.set(getEnsureLensCacheKey(optionsForLens), lens);
|
|
938
1097
|
}
|
|
@@ -950,20 +1109,18 @@ const FATAL_ERROR_CODES = new Set([
|
|
|
950
1109
|
PUBLIC_ERROR_CODES.PROJECT_NOT_FOUND
|
|
951
1110
|
].map((code) => code.getId()));
|
|
952
1111
|
const createLocalSigningSecret = () => `whsec_local_${(0, node_crypto.randomBytes)(24).toString("hex")}`;
|
|
953
|
-
/** HMAC-SHA256 of the exact body, as lowercase hex: the same scheme as real deliveries. */
|
|
954
|
-
const signWebhookBody = (secret, body) => (0, node_crypto.createHmac)("sha256", secret).update(body).digest("hex");
|
|
955
1112
|
const forwardEvent = async (event, options) => {
|
|
956
|
-
const body = JSON.stringify(event);
|
|
1113
|
+
const body = JSON.stringify(toWebhookEventPayload(event));
|
|
957
1114
|
const startedAt = Date.now();
|
|
958
1115
|
try {
|
|
1116
|
+
const headers = await createWebhookHeaders({
|
|
1117
|
+
secret: options.secret,
|
|
1118
|
+
body,
|
|
1119
|
+
deliveryId: `cli_${(0, node_crypto.randomUUID)()}`
|
|
1120
|
+
});
|
|
959
1121
|
const response = await (options.fetchImpl ?? fetch)(options.forwardTo, {
|
|
960
1122
|
method: "POST",
|
|
961
|
-
headers
|
|
962
|
-
"content-type": "application/json",
|
|
963
|
-
"x-calmlens-delivery": `cli_${(0, node_crypto.randomUUID)()}`,
|
|
964
|
-
"x-calmlens-delivery-attempt": "1",
|
|
965
|
-
"x-calmlens-signature": signWebhookBody(options.secret, body)
|
|
966
|
-
},
|
|
1123
|
+
headers,
|
|
967
1124
|
body,
|
|
968
1125
|
signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS)
|
|
969
1126
|
});
|
|
@@ -1040,8 +1197,9 @@ Usage:
|
|
|
1040
1197
|
Run it with \`npx calmlens\`, or install it with \`npm install -g calmlens\`.
|
|
1041
1198
|
|
|
1042
1199
|
Commands:
|
|
1043
|
-
listen Forward your project's events to a local webhook handler
|
|
1044
|
-
|
|
1200
|
+
listen Forward your project's events to a local webhook handler with the same body
|
|
1201
|
+
({ id, type, createdAt, projectId, data }) and headers (x-calmlens-timestamp,
|
|
1202
|
+
x-calmlens-signature: v1=...) as real deliveries. No public URL needed.
|
|
1045
1203
|
trigger Moderate a harmless test comment so CalmLens creates real events. Each trigger
|
|
1046
1204
|
counts as one upload.
|
|
1047
1205
|
|
|
@@ -1146,9 +1304,12 @@ const main = async () => {
|
|
|
1146
1304
|
if (!TRIGGER_KINDS.includes(kind)) fail(`Unknown trigger "${kind}". Use one of: ${TRIGGER_KINDS.join(", ")}.`);
|
|
1147
1305
|
const text = kind === "clean" ? "Hello from the CalmLens CLI" : `<!calmlens-test ${projectId.slice(-8)} ${kind}>`;
|
|
1148
1306
|
try {
|
|
1149
|
-
const asset = await client.
|
|
1150
|
-
|
|
1151
|
-
|
|
1307
|
+
const asset = await client.assets.moderate({
|
|
1308
|
+
name: `cli-trigger-${kind}`,
|
|
1309
|
+
content: {
|
|
1310
|
+
plainText: text,
|
|
1311
|
+
type: "text/plain"
|
|
1312
|
+
}
|
|
1152
1313
|
});
|
|
1153
1314
|
process.stdout.write(`Created asset ${asset.id}: status ${asset.status}${asset.report?.flagged ? ", flagged" : ""}.\n`);
|
|
1154
1315
|
} catch (error) {
|