calmlens 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +3 -2
  2. package/bin/calmlens.js +594 -88
  3. package/{esm/BrowserUpload-D-NnAN7g.d.ts → cjs/BrowserUpload-B2kmc3Y_.d.ts} +2 -2
  4. package/cjs/{BrowserUpload-CeSwiMo5.js → BrowserUpload-B5IJpb8m.js} +1 -1
  5. package/{esm/CalmLensAppClient-gG16T2py.d.ts → cjs/CalmLensAppClient-CMVh0y5w.d.ts} +1 -1
  6. package/cjs/{CalmLensAppClient-0UVCuNqW.js → CalmLensAppClient-DWClthAd.js} +3 -3
  7. package/cjs/{CalmLensOptionKeys-CYY6elxg.js → CalmLensOptionKeys-DsPvFCox.js} +139 -31
  8. package/cjs/{CalmLensServerClient-nfu6_YEW.js → CalmLensServerClient-B35N3hCo.js} +66 -9
  9. package/cjs/{CalmLensServerClient-BHx3x_nZ.d.ts → CalmLensServerClient-izj412cc.d.ts} +43 -7
  10. package/cjs/{CalmLensTypes-CUB0YYVz.d.ts → CalmLensTypes-SmOCgKI3.d.ts} +858 -70
  11. package/cjs/{Classification-Q5zGpR8l-CEWjnE39.d.ts → Classification-CxRedzgH-C9qlYW_J.d.ts} +35 -0
  12. package/cjs/{Core-Dc3cteU7.js → Core-5Mrihf2l.js} +10 -7
  13. package/{esm/Core-C82YmjjX.d.ts → cjs/Core-Dt_HUNvH.d.ts} +9 -5
  14. package/cjs/{ModerationContextLimits-BxOmeSqq.js → ModerationContextLimits-Bm8DxcJ_.js} +64 -12
  15. package/cjs/{ReactUpload-BK2O3dnK.js → ReactUpload-BJCjlqEb.js} +1 -1
  16. package/cjs/{ReactUpload-DiiXfKvj.d.ts → ReactUpload-Bd7Hea4w.d.ts} +1 -1
  17. package/{esm/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts → cjs/TestTriggers-BJ4B-MXR-D1tGifPU.d.ts} +7 -5
  18. package/cjs/{TestTriggers-BTyXtX0Q-ATuFDhLX.js → TestTriggers-CiFcTHX3-BmfH4J3f.js} +35 -22
  19. package/cjs/{UploadController-DLyiLDTB.js → UploadController-DoD51qnV.js} +2 -2
  20. package/{esm/WebhookPayload-BLT2y_Jy.d.ts → cjs/WebhookPayload-C7KAk3iR.d.ts} +28 -1
  21. package/cjs/app.d.ts +6 -6
  22. package/cjs/app.js +2 -2
  23. package/cjs/elements.d.ts +4 -4
  24. package/cjs/elements.js +4 -4
  25. package/{esm/index-CKRgjV16.d.ts → cjs/index-BJf0y_Uk.d.ts} +3 -3
  26. package/cjs/index.d.ts +5 -5
  27. package/cjs/index.js +1 -1
  28. package/cjs/react-native.d.ts +2 -2
  29. package/cjs/react-native.js +4 -4
  30. package/cjs/react.d.ts +3 -3
  31. package/cjs/react.js +5 -5
  32. package/cjs/server.d.ts +6 -6
  33. package/cjs/server.js +2 -2
  34. package/cjs/test-inputs.d.ts +1 -1
  35. package/cjs/test-inputs.js +13 -13
  36. package/cjs/testing.d.ts +22 -9
  37. package/cjs/testing.js +399 -57
  38. package/cjs/{ui-CTBUxnVp.d.ts → ui-DNXPuzha.d.ts} +2 -2
  39. package/cjs/{ui-CZ8exACq.js → ui-DPLnhovP.js} +3 -3
  40. package/cjs/ui.d.ts +2 -2
  41. package/cjs/ui.js +3 -3
  42. package/cjs/vue.d.ts +5 -5
  43. package/cjs/vue.js +4 -4
  44. package/{cjs/BrowserUpload-D-NnAN7g.d.ts → esm/BrowserUpload-B2kmc3Y_.d.ts} +2 -2
  45. package/esm/{BrowserUpload-i9OhCzMJ.js → BrowserUpload-BheeMat4.js} +1 -1
  46. package/{cjs/CalmLensAppClient-gG16T2py.d.ts → esm/CalmLensAppClient-CMVh0y5w.d.ts} +1 -1
  47. package/esm/{CalmLensAppClient-CK4_Py0c.js → CalmLensAppClient-D51UlnU3.js} +3 -3
  48. package/esm/{CalmLensOptionKeys-BGZlIsT2.js → CalmLensOptionKeys-BmYuSh9G.js} +139 -31
  49. package/esm/{CalmLensServerClient-dAQUcDWb.js → CalmLensServerClient-CJCjmAXh.js} +66 -9
  50. package/esm/{CalmLensServerClient-BHx3x_nZ.d.ts → CalmLensServerClient-izj412cc.d.ts} +43 -7
  51. package/esm/{CalmLensTypes-CUB0YYVz.d.ts → CalmLensTypes-SmOCgKI3.d.ts} +858 -70
  52. package/esm/{Classification-Q5zGpR8l-CEWjnE39.d.ts → Classification-CxRedzgH-C9qlYW_J.d.ts} +35 -0
  53. package/esm/{Core-BxeIud_S.js → Core-5A2CZKsC.js} +10 -7
  54. package/{cjs/Core-C82YmjjX.d.ts → esm/Core-Dt_HUNvH.d.ts} +9 -5
  55. package/esm/{ModerationContextLimits-B6_RalCQ.js → ModerationContextLimits-DeqK3UAt.js} +64 -12
  56. package/esm/{ReactUpload-DiiXfKvj.d.ts → ReactUpload-Bd7Hea4w.d.ts} +1 -1
  57. package/esm/{ReactUpload-DxwVqfX1.js → ReactUpload-OkhH4jXm.js} +1 -1
  58. package/{cjs/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts → esm/TestTriggers-BJ4B-MXR-D1tGifPU.d.ts} +7 -5
  59. package/esm/{TestTriggers-BTyXtX0Q-GRB9jQwo.js → TestTriggers-CiFcTHX3-BK2-sgOC.js} +35 -22
  60. package/esm/{UploadController-D9Z-h00Q.js → UploadController-BssSSy8Y.js} +2 -2
  61. package/{cjs/WebhookPayload-BLT2y_Jy.d.ts → esm/WebhookPayload-C7KAk3iR.d.ts} +28 -1
  62. package/esm/app.d.ts +6 -6
  63. package/esm/app.js +2 -2
  64. package/esm/elements.d.ts +4 -4
  65. package/esm/elements.js +4 -4
  66. package/{cjs/index-CKRgjV16.d.ts → esm/index-BJf0y_Uk.d.ts} +3 -3
  67. package/esm/index.d.ts +5 -5
  68. package/esm/index.js +1 -1
  69. package/esm/react-native.d.ts +2 -2
  70. package/esm/react-native.js +4 -4
  71. package/esm/react.d.ts +3 -3
  72. package/esm/react.js +5 -5
  73. package/esm/server.d.ts +6 -6
  74. package/esm/server.js +2 -2
  75. package/esm/test-inputs.d.ts +1 -1
  76. package/esm/test-inputs.js +1 -1
  77. package/esm/testing.d.ts +22 -9
  78. package/esm/testing.js +393 -51
  79. package/esm/{ui-Cr7s6JHm.js → ui-CZVG46z9.js} +3 -3
  80. package/esm/{ui-CTBUxnVp.d.ts → ui-DNXPuzha.d.ts} +2 -2
  81. package/esm/ui.d.ts +2 -2
  82. package/esm/ui.js +3 -3
  83. package/esm/vue.d.ts +5 -5
  84. package/esm/vue.js +4 -4
  85. package/package.json +2 -2
package/esm/testing.js CHANGED
@@ -1,10 +1,10 @@
1
- import { A as getRejectedUploadMimeTypeError, B as invalidArgument, H as API_ERROR_CODES, N as sleep, O as MAX_IMAGE_UPLOAD_BYTES, R as CalmLensError, S as validateAppClientOptions, T as validateServerClientOptions, U as API_ERROR_DEFINITIONS, V as invalidConfig, _ as randomUuid, f as checkTransformOptions, h as parseTransformSelector, j as normalizeUploadMimeType, m as isAcceptedUploadMimeType, r as selectModerationContextItems, z as SDK_ERROR_CODES } from "./ModerationContextLimits-B6_RalCQ.js";
2
- import { a as WEBHOOK_TIMESTAMP_HEADER, f as signUploadTokenWithApiKey, m as stringifyJsonCanonical, n as WEBHOOK_DELIVERY_HEADER, p as decodeUploadToken, r as WEBHOOK_SIGNATURE_HEADER, t as CalmLensServerClient } from "./CalmLensServerClient-dAQUcDWb.js";
3
- import { a as MOCK_HOOKS, g as validateAssetPayload, h as assetToData, m as assetDataToUint8Array } from "./CalmLensOptionKeys-BGZlIsT2.js";
1
+ import { A as getRejectedUploadMimeTypeError, B as invalidArgument, H as API_ERROR_CODES, N as sleep, O as MAX_IMAGE_UPLOAD_BYTES, R as CalmLensError, S as validateAppClientOptions, T as validateServerClientOptions, U as API_ERROR_DEFINITIONS, V as invalidConfig, _ as randomUuid, f as checkTransformOptions, h as parseTransformSelector, j as normalizeUploadMimeType, m as isAcceptedUploadMimeType, r as selectModerationContextItems, z as SDK_ERROR_CODES } from "./ModerationContextLimits-DeqK3UAt.js";
2
+ import { a as WEBHOOK_TIMESTAMP_HEADER, f as signUploadTokenWithApiKey, m as stringifyJsonCanonical, n as WEBHOOK_DELIVERY_HEADER, p as decodeUploadToken, r as WEBHOOK_SIGNATURE_HEADER, t as CalmLensServerClient } from "./CalmLensServerClient-CJCjmAXh.js";
3
+ import { a as MOCK_HOOKS, g as validateAssetPayload, h as assetToData, m as assetDataToUint8Array } from "./CalmLensOptionKeys-BmYuSh9G.js";
4
4
  import { t as hmacSha256Hex } from "./CryptoUtils-B_x8lMIx-DhuWGzqn.js";
5
- import { t as CalmLensAppClient } from "./CalmLensAppClient-CK4_Py0c.js";
6
- import { a as placeholderHashToDataURL, r as isFileAccepted } from "./UploadController-D9Z-h00Q.js";
7
- import { d as getTestInputTag, m as CLASSIFICATION_CATEGORIES } from "./TestTriggers-BTyXtX0Q-GRB9jQwo.js";
5
+ import { t as CalmLensAppClient } from "./CalmLensAppClient-D51UlnU3.js";
6
+ import { a as placeholderHashToDataURL, r as isFileAccepted } from "./UploadController-BssSSy8Y.js";
7
+ import { d as getTestInputTag, m as CLASSIFICATION_CATEGORIES } from "./TestTriggers-CiFcTHX3-BK2-sgOC.js";
8
8
  import * as zod from "zod";
9
9
  // src/contract/MediaTestTriggers.js
10
10
  const MEDIA_TEST_SIGNALS = [...CLASSIFICATION_CATEGORIES, "violence.graphic"];
@@ -7987,7 +7987,7 @@ const EXAMPLE_IDS = {
7987
7987
  * across the packages that build records from plain strings).
7988
7988
  */
7989
7989
  const idField = (prefix) => zod.string().regex(idPattern(prefix), { message: `Must be a valid ID: "${prefix}_" followed by 20 letters or digits` }).meta({ examples: [EXAMPLE_IDS[prefix]] });
7990
- // src/contract/Permissions-BqpmE0Qa.js
7990
+ // src/contract/Permissions-DPNlE8m-.js
7991
7991
  const ACTION_SCHEMA = zod.enum([
7992
7992
  "assets:read",
7993
7993
  "assets:download",
@@ -8044,10 +8044,13 @@ const GRANT_SCHEMA = zod.object({
8044
8044
  const GRANTS_SCHEMA = zod.array(GRANT_SCHEMA).max(100);
8045
8045
  zod.enum([
8046
8046
  "admin",
8047
+ "configurator",
8047
8048
  "editor",
8048
8049
  "viewer",
8049
8050
  "custom"
8050
8051
  ]);
8052
+ [...ACTION_SCHEMA.options.filter((a) => !isProjectAction(a))];
8053
+ [...ACTION_SCHEMA.options.filter((a) => !isProjectAction(a))];
8051
8054
  const permits = (grants, action, folderId, folders) => grants.some((grant) => {
8052
8055
  if (![action, ...actionsImplying(action)].some((held) => grant.actions.includes(held))) return false;
8053
8056
  if (grant.folderId === null) return true;
@@ -8123,6 +8126,7 @@ const MOCK_QUALIFIERS = {
8123
8126
  "sexual-educational",
8124
8127
  "sexual-discussion",
8125
8128
  "sexual-fictional",
8129
+ "sexual-artistic",
8126
8130
  "sexual-support-prevention"
8127
8131
  ],
8128
8132
  "violence": [
@@ -8283,6 +8287,7 @@ const isScore = (score) => typeof score === "number" && Number.isFinite(score) &
8283
8287
  var MockDecision = class {
8284
8288
  #flags = /* @__PURE__ */ new Map();
8285
8289
  #notEvaluated = /* @__PURE__ */ new Set();
8290
+ #pendingReview;
8286
8291
  constructor(status) {
8287
8292
  if (!OUTCOMES.includes(status)) throw invalidArgument(`status must be one of ${OUTCOMES.join(", ")}`);
8288
8293
  this.status = status;
@@ -8316,15 +8321,32 @@ var MockDecision = class {
8316
8321
  this.#notEvaluated.add(category);
8317
8322
  return this;
8318
8323
  }
8324
+ /**
8325
+ * Leaves the decision waiting for human review, as `classification.moderation.pendingReview`
8326
+ * reports: `sampled`, or `uncertain` with the `uncertainCategories` that made it so. The queue's
8327
+ * decision (`decide` on the mock) clears it; `assets.decide` doesn't, as with the API.
8328
+ */
8329
+ pendingReview(reason, uncertainCategories = []) {
8330
+ if (this.status === "pending" || this.status === "failed") throw invalidArgument(`a ${this.status} decision can't wait for review`);
8331
+ if (reason !== "sampled" && reason !== "uncertain") throw invalidArgument("reason must be sampled or uncertain");
8332
+ if (reason === "sampled" && uncertainCategories.length) throw invalidArgument("a sampled review has no uncertain categories");
8333
+ for (const category of uncertainCategories) this.#checkCategory(category);
8334
+ this.#pendingReview = {
8335
+ reason,
8336
+ uncertainCategories: [...uncertainCategories]
8337
+ };
8338
+ return this;
8339
+ }
8319
8340
  #checkCategory(category) {
8320
8341
  if (!MOCK_CATEGORIES.includes(category)) throw invalidArgument(`${category} is not a CalmLens category`);
8321
8342
  }
8322
8343
  /**
8323
8344
  * The report a decided asset gets, as the API sends it: every category (unflagged ones
8324
8345
  * evaluated with score 0), policy-adjusted results and the automated status and
8325
- * `flaggedCategories`. `undefined` for `pending` and `failed`.
8346
+ * `flaggedCategories`. `requestedAt` is when a pending review joined the queue. `undefined` for
8347
+ * `pending` and `failed`.
8326
8348
  */
8327
- report() {
8349
+ report(requestedAt = 0) {
8328
8350
  const status = this.status;
8329
8351
  if (status === "pending" || status === "failed") return void 0;
8330
8352
  const action = (score) => status !== "allowed" && score >= .5 ? STATUS_ACTION[status] : "allow";
@@ -8350,9 +8372,20 @@ var MockDecision = class {
8350
8372
  return {
8351
8373
  categories: Object.fromEntries(evaluated.map(([category, score]) => [category, {
8352
8374
  score,
8353
- action: action(score)
8375
+ action: action(score),
8376
+ source: { kind: score >= .5 ? "default" : "below-threshold" },
8377
+ settings: {
8378
+ action: status === "allowed" ? "allow" : STATUS_ACTION[status],
8379
+ allowances: [],
8380
+ restrictions: []
8381
+ }
8354
8382
  }])),
8355
8383
  explanationComplete: true,
8384
+ policy: null,
8385
+ pendingReview: this.#pendingReview ? {
8386
+ requestedAt,
8387
+ ...this.#pendingReview
8388
+ } : null,
8356
8389
  source: "policy",
8357
8390
  rule: null,
8358
8391
  automatedStatus: status,
@@ -9143,7 +9176,16 @@ const MOCK_OPERATIONS = [
9143
9176
  "lenses.update",
9144
9177
  "lenses.delete",
9145
9178
  "ensureLens",
9146
- "ensureLenses"
9179
+ "ensureLenses",
9180
+ "uploadPresets.list",
9181
+ "uploadPresets.iterate",
9182
+ "uploadPresets.ensure",
9183
+ "uploadPresets.delete",
9184
+ "projectSettings.get",
9185
+ "projectSettings.update",
9186
+ "metadataFields.list",
9187
+ "metadataFields.ensure",
9188
+ "metadataFields.delete"
9147
9189
  ];
9148
9190
  const MAX_PAGE_SIZE = 100;
9149
9191
  const MAX_DECISION_NOTE_LENGTH = 1499;
@@ -9382,6 +9424,74 @@ const invalidField = (code, path) => new ApiFailure(400, API_ERROR_CODES.INVALID
9382
9424
  message: `Invalid ${path}`,
9383
9425
  code
9384
9426
  }] });
9427
+ /** The asset fields an upload carries in its body; the API refuses them in the query string. */
9428
+ const UPLOAD_OPTION_KEYS = [
9429
+ "name",
9430
+ "description",
9431
+ "processingOptions",
9432
+ "visibility",
9433
+ "metadata",
9434
+ "tags",
9435
+ "authorId",
9436
+ "context",
9437
+ "externalId",
9438
+ "externalUrl",
9439
+ "folderId",
9440
+ "uploadPresetId"
9441
+ ];
9442
+ const indexOfBytes = (haystack, needle, from = 0) => {
9443
+ for (let index = haystack.indexOf(needle[0], from); index !== -1;) {
9444
+ if (index + needle.length > haystack.length) return -1;
9445
+ let offset = 1;
9446
+ while (offset < needle.length && haystack[index + offset] === needle[offset]) offset++;
9447
+ if (offset === needle.length) return index;
9448
+ index = haystack.indexOf(needle[0], index + 1);
9449
+ }
9450
+ return -1;
9451
+ };
9452
+ /**
9453
+ * Reads a raw upload's `multipart/form-data` body like the API: an `options` part, then a `file`
9454
+ * part, then the closing boundary. Anything else is refused.
9455
+ */
9456
+ const readUploadForm = (request) => {
9457
+ const contentType = request.headers.get("content-type") ?? "";
9458
+ if (contentType.split(";")[0].trim().toLowerCase() !== "multipart/form-data") throw new ApiFailure(415, API_ERROR_CODES.UNSUPPORTED_CONTENT_TYPE, "Send a raw upload as multipart/form-data: an options part, then a file part.", { contentType: contentType.split(";")[0].trim() || null });
9459
+ const boundary = /;\s*boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType);
9460
+ const invalid = (message) => fail(API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message });
9461
+ if (!boundary) throw invalid("The multipart/form-data Content-Type needs a boundary");
9462
+ const encoder = new TextEncoder();
9463
+ const delimiter = encoder.encode(`\r\n--${boundary[1] ?? boundary[2]}`);
9464
+ const body = new Uint8Array(2 + request.bytes.length);
9465
+ body.set(encoder.encode("\r\n"));
9466
+ body.set(request.bytes, 2);
9467
+ const parts = [];
9468
+ let at = indexOfBytes(body, delimiter);
9469
+ while (at !== -1) {
9470
+ const start = at + delimiter.length;
9471
+ if (body[start] === 45 && body[start + 1] === 45) break;
9472
+ const headerEnd = indexOfBytes(body, encoder.encode("\r\n\r\n"), start);
9473
+ const next = headerEnd === -1 ? -1 : indexOfBytes(body, delimiter, headerEnd + 4);
9474
+ if (next === -1) throw invalid("The upload body ended before its closing boundary");
9475
+ const headers = new TextDecoder().decode(body.slice(start, headerEnd));
9476
+ const name = /content-disposition:\s*form-data\s*;[^\r\n]*?\bname="([^"]*)"/i.exec(headers)?.[1];
9477
+ parts.push({
9478
+ name,
9479
+ content: body.slice(headerEnd + 4, next)
9480
+ });
9481
+ at = next;
9482
+ }
9483
+ if (at === -1) throw invalid("The upload body ended before its closing boundary");
9484
+ if (parts.length !== 2 || parts[0].name !== "options" || parts[1].name !== "file") throw invalid("The upload form must hold an options part, then a file part");
9485
+ return {
9486
+ options: new TextDecoder().decode(parts[0].content),
9487
+ bytes: parts[1].content
9488
+ };
9489
+ };
9490
+ /** A request that names asset fields in its query, which the API refuses. */
9491
+ const assertNoUploadOptionsInQuery = (query) => {
9492
+ const fields = UPLOAD_OPTION_KEYS.filter((key) => query.has(key));
9493
+ if (fields.length) throw fail(API_ERROR_CODES.UPLOAD_OPTIONS_IN_QUERY, { details: { fields } });
9494
+ };
9385
9495
  /**
9386
9496
  * Refuses `metadata` the API's schema refuses (METADATA_ITEM_SCHEMA): it is `null` or a list of
9387
9497
  * `{ id, value }` objects with a string `id` and any JSON `value`.
@@ -9439,6 +9549,9 @@ const operationsOf = (request) => {
9439
9549
  case "folders": return method === "GET" ? ["folders.list", "folders.iterate"] : ["folders.create"];
9440
9550
  case "hash-lists": return method === "GET" ? ["hashLists.list", "hashLists.iterate"] : ["hashLists.create"];
9441
9551
  case "policy": return method === "GET" ? ["policies.retrieveAssigned"] : ["policies.assign"];
9552
+ case "upload-presets": return method === "GET" ? ["uploadPresets.list", "uploadPresets.iterate"] : ["uploadPresets.ensure"];
9553
+ case "settings": return method === "GET" ? ["projectSettings.get"] : ["projectSettings.update"];
9554
+ case "metadata-fields": return method === "GET" ? ["metadataFields.list"] : ["metadataFields.ensure"];
9442
9555
  case "assets/search": return ["assets.search"];
9443
9556
  case "assets/batch": return ["assets.batch"];
9444
9557
  case "signed-asset-urls": return ["cdn.signAssetUrl"];
@@ -9448,6 +9561,7 @@ const operationsOf = (request) => {
9448
9561
  return isTextUpload(request) ? ["assets.classify", "text.classify"] : ["assets.classify"];
9449
9562
  }
9450
9563
  if (segments[2] === "assets" && segments[4] === "timeline" && segments.length === 5) return ["assets.listTimeline", "assets.iterateTimeline"];
9564
+ if (segments[2] === "metadata-fields" && segments.length === 4) return ["metadataFields.delete"];
9451
9565
  return [];
9452
9566
  }
9453
9567
  if (root === "policies") {
@@ -9459,6 +9573,7 @@ const operationsOf = (request) => {
9459
9573
  return method === "GET" ? ["policies.retrieve"] : method === "PATCH" ? ["policies.update"] : ["policies.delete"];
9460
9574
  }
9461
9575
  if (root === "lenses" && segments[1] !== void 0) return method === "GET" ? ["lenses.retrieve"] : method === "PATCH" ? ["lenses.update"] : ["lenses.delete"];
9576
+ if (root === "upload-presets" && segments.length === 2) return ["uploadPresets.delete"];
9462
9577
  if (root === "upload-presets") {
9463
9578
  if (segments[3] === void 0) return [query.get("wait") === "false" ? "assets.create" : "assets.classify"];
9464
9579
  return segments[4] === "part" ? ["assets.uploadPart"] : ["assets.retrieve"];
@@ -9487,7 +9602,15 @@ const operationsOf = (request) => {
9487
9602
  }
9488
9603
  return [];
9489
9604
  };
9490
- const isTextUpload = (request) => request.headers.get("x-calmlens-upload") === "content" && request.headers.get("content-type") === "text/plain";
9605
+ /** A plain-text upload: the SDKs send text as a JSON body with `content.plainText`. */
9606
+ const isTextUpload = (request) => {
9607
+ if (request.headers.get("x-calmlens-upload")) return false;
9608
+ try {
9609
+ return typeof JSON.parse(new TextDecoder().decode(request.bytes))?.content?.plainText === "string";
9610
+ } catch {
9611
+ return false;
9612
+ }
9613
+ };
9491
9614
  /** Like the API: a new folder is 201 Created, a queued batch 202 Accepted, everything else 200. */
9492
9615
  const SUCCESS_STATUS = {
9493
9616
  "folders.create": 201,
@@ -9531,6 +9654,10 @@ var MockCalmLensApi = class {
9531
9654
  this.hashLists = /* @__PURE__ */ new Map();
9532
9655
  this.hashListEntries = /* @__PURE__ */ new Map();
9533
9656
  this.pageFailure = (code, path) => code === "cursor/invalid" ? fail(API_ERROR_CODES.INVALID_CURSOR) : invalidField(code, path ?? "pageSize");
9657
+ this.configuredPresets = /* @__PURE__ */ new Map();
9658
+ this.settingsRevision = 1;
9659
+ this.projectSettingsValues = {};
9660
+ this.metadataFieldList = [];
9534
9661
  this.options = options;
9535
9662
  this.projectId = options.projectId;
9536
9663
  this.apiKey = options.apiKey;
@@ -9652,6 +9779,7 @@ var MockCalmLensApi = class {
9652
9779
  this.pendingReruns.delete(asset.id);
9653
9780
  const decided = await this.applyOutcome(asset, decision, "requested");
9654
9781
  const now = this.now();
9782
+ if (!review) decided.classification.moderation.pendingReview = null;
9655
9783
  decided.classification.moderation.manualReviews = [...decided.classification.moderation.manualReviews ?? [], {
9656
9784
  id: this.createId("rev"),
9657
9785
  decision,
@@ -9772,9 +9900,20 @@ var MockCalmLensApi = class {
9772
9900
  }
9773
9901
  return failure;
9774
9902
  }
9775
- describeBody({ bytes, headers }) {
9903
+ describeBody(request) {
9904
+ const { bytes, headers } = request;
9776
9905
  if (bytes.byteLength === 0) return void 0;
9777
9906
  const type = headers.get("content-type") ?? "";
9907
+ if (type.startsWith("multipart/form-data")) try {
9908
+ const form = readUploadForm(request);
9909
+ const file = request.query.get("contentType") ?? "";
9910
+ return {
9911
+ options: JSON.parse(form.options),
9912
+ file: file.startsWith("text/") ? new TextDecoder().decode(form.bytes) : form.bytes.slice()
9913
+ };
9914
+ } catch {
9915
+ return bytes.slice();
9916
+ }
9778
9917
  const text = () => new TextDecoder().decode(bytes);
9779
9918
  if (type === "application/json") try {
9780
9919
  return JSON.parse(text());
@@ -9816,13 +9955,20 @@ var MockCalmLensApi = class {
9816
9955
  if (!(request.segments[0] === "upload-presets") && headers.get("x-api-key") !== this.apiKey) return this.failureResponse(fail(API_ERROR_CODES.INVALID_API_KEY), url);
9817
9956
  const key = headers.get("idempotency-key")?.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");
9818
9957
  const upload = headers.get("x-calmlens-upload");
9958
+ const contentType = headers.get("content-type");
9959
+ const isForm = !!upload && /^multipart\/form-data\b/i.test(contentType ?? "");
9960
+ let formOptions;
9961
+ if (isForm && request.segments.at(-1) !== "part") try {
9962
+ formOptions = readUploadForm(request).options;
9963
+ } catch {}
9819
9964
  const fingerprint = JSON.stringify([
9820
9965
  request.method,
9821
9966
  request.segments,
9822
9967
  [...request.query].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0),
9823
- headers.get("content-type"),
9968
+ isForm ? "multipart/form-data" : contentType,
9824
9969
  upload,
9825
- upload ? request.bytes.byteLength : new TextDecoder().decode(request.bytes)
9970
+ upload ? request.bytes.byteLength : new TextDecoder().decode(request.bytes),
9971
+ formOptions ?? null
9826
9972
  ]);
9827
9973
  if (key !== void 0) {
9828
9974
  if (!isValidIdempotencyKey(key)) return this.failureResponse(fail(API_ERROR_CODES.INVALID_IDEMPOTENCY_KEY), url);
@@ -9873,8 +10019,17 @@ var MockCalmLensApi = class {
9873
10019
  case "POST lenses": return [201, this.createLens(this.json(request))];
9874
10020
  case "GET policy": return [200, this.toPolicy(this.findPolicy(this.ensurePolicies()))];
9875
10021
  case "PUT policy": return [200, this.assignPolicy(this.json(request))];
10022
+ case "GET upload-presets": return [200, this.listUploadPresets(request.query)];
10023
+ case "PUT upload-presets": return [200, this.ensureUploadPresets(this.json(request))];
10024
+ case "GET settings": return [200, this.toProjectSettings()];
10025
+ case "PUT settings": return [200, this.updateProjectSettings(this.json(request))];
10026
+ case "GET metadata-fields": return [200, this.toMetadataFields()];
10027
+ case "PUT metadata-fields": return [200, this.ensureMetadataFields(this.json(request))];
9876
10028
  }
9877
10029
  const [, , collection, itemId, itemAction, ...more] = segments;
10030
+ if (collection === "metadata-fields" && itemId !== void 0 && itemAction === void 0) {
10031
+ if (method === "DELETE") return [200, this.deleteMetadataField(itemId, request.query)];
10032
+ }
9878
10033
  if (collection === "assets" && itemId !== void 0 && itemAction === "timeline" && more.length === 0 && method === "GET") return [200, await this.listTimeline(itemId, request.query)];
9879
10034
  }
9880
10035
  if (root === "policies" && rest.length === 0) {
@@ -9895,6 +10050,9 @@ var MockCalmLensApi = class {
9895
10050
  case "PATCH": return [200, this.updateLens(id, this.json(request))];
9896
10051
  case "DELETE": return [200, this.deleteLens(id)];
9897
10052
  }
10053
+ if (root === "upload-presets" && id !== void 0 && action === void 0) {
10054
+ if (method === "DELETE") return [200, this.deleteUploadPreset(id)];
10055
+ }
9898
10056
  if (root === "upload-presets" && id !== void 0 && action === "assets") return [200, await this.presetRoute(request, id, rest, session)];
9899
10057
  if (root === "assets" && id !== void 0 && rest.length === 0) switch (`${method} ${action ?? ""}`) {
9900
10058
  case "GET ": return [200, await this.findOwnAsset(id)];
@@ -10450,42 +10608,49 @@ var MockCalmLensApi = class {
10450
10608
  await this.databaseStorage.deleteAsset(id);
10451
10609
  }
10452
10610
  }
10453
- /** The upload fields of `POST .../assets`: raw uploads carry them in the query. */
10611
+ /**
10612
+ * The upload fields of `POST .../assets`, from the JSON body (text and URLs) or an upload form's
10613
+ * options (files). Like the API, asset fields in the query are refused.
10614
+ */
10454
10615
  uploadFields(request) {
10616
+ const { query } = request;
10617
+ assertNoUploadOptionsInQuery(query);
10455
10618
  const upload = request.headers.get("x-calmlens-upload");
10456
10619
  if (upload !== "content" && upload !== "part") {
10457
10620
  const body = this.json(request);
10458
10621
  checkMetadata(body.metadata);
10459
- return body;
10622
+ const { content, part, sizeInBytes: _size, totalSizeInBytes, ...fields } = body;
10623
+ const text = content ?? part;
10624
+ if (text === void 0) return fields;
10625
+ if (typeof text.plainText !== "string" || typeof text.type !== "string") throw invalidField("validation/invalid-type", content ? "content" : "part");
10626
+ return {
10627
+ ...fields,
10628
+ contentType: text.type,
10629
+ bytes: new TextEncoder().encode(text.plainText),
10630
+ part: part ? {
10631
+ partNumber: typeof part.partNumber === "number" ? part.partNumber : 1,
10632
+ isFinal: part.isFinal === true,
10633
+ totalSizeInBytes: typeof totalSizeInBytes === "number" ? totalSizeInBytes : void 0
10634
+ } : void 0
10635
+ };
10460
10636
  }
10461
- const { query } = request;
10462
- const text = (name) => query.get(name) ?? void 0;
10463
- const parsed = (name) => {
10464
- const raw = query.get(name);
10465
- if (raw === null) return void 0;
10466
- try {
10467
- return JSON.parse(raw);
10468
- } catch {
10469
- throw invalidField("validation/invalid-value", name);
10470
- }
10471
- };
10637
+ const form = readUploadForm(request);
10638
+ let options;
10639
+ try {
10640
+ options = JSON.parse(form.options);
10641
+ } catch {
10642
+ throw fail(API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "The options part must be a JSON object with the asset's fields" });
10643
+ }
10644
+ if (!options || typeof options !== "object" || Array.isArray(options)) throw fail(API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "The options part must be a JSON object with the asset's fields" });
10645
+ const unknown = Object.keys(options).find((key) => !UPLOAD_OPTION_KEYS.includes(key));
10646
+ if (unknown !== void 0) throw invalidField("validation/unknown-field", unknown);
10647
+ if (typeof options.name !== "string") throw invalidField("validation/invalid-type", "name");
10648
+ checkMetadata(options.metadata);
10472
10649
  const total = query.get("totalSizeInBytes");
10473
- checkMetadata(parsed("metadata"));
10474
10650
  return {
10475
- name: query.get("name") ?? "",
10476
- description: text("description"),
10477
- processingOptions: parsed("processingOptions"),
10478
- visibility: text("visibility"),
10479
- metadata: parsed("metadata"),
10480
- tags: parsed("tags"),
10481
- authorId: text("authorId"),
10482
- context: parsed("context"),
10483
- externalId: text("externalId"),
10484
- externalUrl: text("externalUrl"),
10485
- folderId: text("folderId"),
10486
- uploadPresetId: text("uploadPresetId"),
10487
- contentType: query.get("contentType") ?? request.headers.get("content-type") ?? "",
10488
- bytes: request.bytes,
10651
+ ...options,
10652
+ contentType: query.get("contentType") ?? "",
10653
+ bytes: form.bytes,
10489
10654
  part: upload === "part" ? {
10490
10655
  partNumber: this.integer(query, "partNumber", 1),
10491
10656
  isFinal: query.get("isFinal") === "true",
@@ -10494,7 +10659,40 @@ var MockCalmLensApi = class {
10494
10659
  };
10495
10660
  }
10496
10661
  async createAsset(request) {
10497
- return this.storeAsset(this.uploadFields(request), request.query.get("wait") === "false");
10662
+ return this.storeAsset(this.applyUploadPreset(this.uploadFields(request)), request.query.get("wait") === "false");
10663
+ }
10664
+ /**
10665
+ * An API-key upload through a preset, as the API applies it: the preset gives the folder and
10666
+ * visibility, which the upload can't change, and the processing options unless the upload sets
10667
+ * its own, and refuses types and sizes it doesn't accept.
10668
+ */
10669
+ applyUploadPreset(fields) {
10670
+ if (!fields.uploadPresetId) return fields;
10671
+ const preset = [...this.configuredPresets.values()].find(({ id }) => id === fields.uploadPresetId);
10672
+ if (!preset) throw fail(API_ERROR_CODES.UPLOAD_PRESET_NOT_FOUND);
10673
+ if (!preset.enabled) throw fail(API_ERROR_CODES.UPLOAD_PRESET_DISABLED);
10674
+ if (preset.folderId && fields.folderId && fields.folderId !== preset.folderId) throw fail(API_ERROR_CODES.UPLOAD_PRESET_FIELD_NOT_ALLOWED, { details: { field: "folderId" } });
10675
+ if (fields.visibility && fields.visibility !== preset.visibility) throw fail(API_ERROR_CODES.UPLOAD_PRESET_FIELD_NOT_ALLOWED, { details: { field: "visibility" } });
10676
+ const contentType = fields.contentType;
10677
+ if (preset.allowedContentTypes?.length && contentType !== void 0 && !isFileAccepted({
10678
+ name: fields.name,
10679
+ type: contentType
10680
+ }, preset.allowedContentTypes.join(","))) throw fail(API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, { details: {
10681
+ source: "preset",
10682
+ contentType,
10683
+ allowedContentTypes: preset.allowedContentTypes
10684
+ } });
10685
+ const size = fields.part?.totalSizeInBytes ?? fields.bytes?.byteLength;
10686
+ if (preset.maxSizeInBytes && size !== void 0 && size > preset.maxSizeInBytes) throw fail(API_ERROR_CODES.UPLOAD_TOO_LARGE, { details: {
10687
+ limitBytes: preset.maxSizeInBytes,
10688
+ source: "preset"
10689
+ } });
10690
+ return {
10691
+ ...fields,
10692
+ folderId: preset.folderId ?? fields.folderId,
10693
+ visibility: preset.visibility,
10694
+ processingOptions: fields.processingOptions ?? preset.processingOptions
10695
+ };
10498
10696
  }
10499
10697
  async storeAsset(fields, queue) {
10500
10698
  if (!fields.name) throw fail(API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Asset name is required" });
@@ -10539,6 +10737,7 @@ var MockCalmLensApi = class {
10539
10737
  id,
10540
10738
  projectId: this.projectId,
10541
10739
  parentId: null,
10740
+ parentPages: [],
10542
10741
  folderId: fields.folderId ?? null,
10543
10742
  uploadPresetId: fields.uploadPresetId ?? null,
10544
10743
  createdAt: now,
@@ -10588,6 +10787,8 @@ var MockCalmLensApi = class {
10588
10787
  status: "pending",
10589
10788
  manualReviews: [],
10590
10789
  automatedStatus: null,
10790
+ policy: null,
10791
+ pendingReview: null,
10591
10792
  source: null,
10592
10793
  rule: null,
10593
10794
  explanationComplete: null,
@@ -10725,7 +10926,7 @@ var MockCalmLensApi = class {
10725
10926
  * it, a decided image reports the person and face detection its upload turned on.
10726
10927
  */
10727
10928
  async decided(asset, decision) {
10728
- const next = await this.applyOutcome(asset, decision.status, "policy", decision.report());
10929
+ const next = await this.applyOutcome(asset, decision.status, "policy", decision.report(this.now()));
10729
10930
  const features = this.processingOptions.get(asset.id)?.features;
10730
10931
  if (next.classification.status !== "completed" || asset.type !== "image") return next;
10731
10932
  return {
@@ -10994,7 +11195,11 @@ var MockCalmLensApi = class {
10994
11195
  if (preset.allowedContentTypes && !isFileAccepted({
10995
11196
  name: fields.name,
10996
11197
  type: fields.contentType ?? ""
10997
- }, preset.allowedContentTypes.join(","))) throw fail(API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, { details: { source: "preset" } });
11198
+ }, preset.allowedContentTypes.join(","))) throw fail(API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, { details: {
11199
+ source: "preset",
11200
+ contentType: fields.contentType ?? "",
11201
+ allowedContentTypes: preset.allowedContentTypes
11202
+ } });
10998
11203
  const size = fields.part?.totalSizeInBytes ?? fields.bytes?.byteLength;
10999
11204
  if (preset.maxFileSizeInBytes !== void 0 && size !== void 0 && size > preset.maxFileSizeInBytes) throw fail(API_ERROR_CODES.UPLOAD_TOO_LARGE, { details: {
11000
11205
  limitBytes: preset.maxFileSizeInBytes,
@@ -11160,6 +11365,139 @@ var MockCalmLensApi = class {
11160
11365
  async assertUniqueFolderName(name, parentId, excludeFolderId) {
11161
11366
  if ((await this.databaseStorage.listFolders?.(this.projectId) ?? []).find((folder) => folder.id !== excludeFolderId && (folder.parentId ?? null) === parentId && folder.name === name)) throw fail(API_ERROR_CODES.DUPLICATE_FOLDER_NAME, { message: `A folder named "${name}" already exists in this location.` });
11162
11367
  }
11368
+ /** A page of the project's upload presets, oldest first unless `sort` says otherwise. */
11369
+ listUploadPresets(query) {
11370
+ return createPage([...this.configuredPresets.values()], this.pageQuery(query), {
11371
+ scope: `upload-presets:${this.projectId}`,
11372
+ fail: this.pageFailure,
11373
+ defaultSort: [{
11374
+ field: "createdAt",
11375
+ direction: "asc"
11376
+ }]
11377
+ });
11378
+ }
11379
+ /** Like the API: every preset's revision and settings are checked before any is saved. */
11380
+ ensureUploadPresets(body) {
11381
+ const definitions = Array.isArray(body.uploadPresets) ? body.uploadPresets : [];
11382
+ if (definitions.length === 0) throw invalidField("validation/too-small", "uploadPresets");
11383
+ return { uploadPresets: definitions.map((definition, index) => {
11384
+ if (typeof definition.key !== "string" || !definition.key) throw invalidField("validation/invalid-type", `uploadPresets.${index}.key`);
11385
+ if (typeof definition.name !== "string" || !definition.name) throw invalidField("validation/invalid-type", `uploadPresets.${index}.name`);
11386
+ const existing = this.configuredPresets.get(definition.key);
11387
+ if (definition.revision !== void 0 && definition.revision !== (existing?.revision ?? 0)) throw fail(API_ERROR_CODES.UPLOAD_PRESET_REVISION_CONFLICT, { details: {
11388
+ key: definition.key,
11389
+ revision: existing?.revision ?? 0
11390
+ } });
11391
+ const list = (value) => Array.isArray(value) && value.length ? [...new Set(value)] : null;
11392
+ const values = {
11393
+ key: definition.key,
11394
+ name: definition.name,
11395
+ access: definition.access ?? "token",
11396
+ enabled: definition.enabled ?? true,
11397
+ allowedContentTypes: list(definition.allowedContentTypes),
11398
+ maxSizeInBytes: definition.maxSizeInBytes ?? null,
11399
+ folderId: definition.folderId ?? null,
11400
+ policyId: definition.policyId ?? null,
11401
+ visibility: definition.visibility ?? "private",
11402
+ processingOptions: definition.processingOptions ?? null,
11403
+ revealDecision: definition.revealDecision ?? false,
11404
+ dailyUploadLimit: definition.dailyUploadLimit ?? null,
11405
+ allowedOrigins: list(definition.allowedOrigins)
11406
+ };
11407
+ if (values.access === "anyone" && !values.dailyUploadLimit) throw fail(API_ERROR_CODES.UPLOAD_PRESET_DAILY_LIMIT_REQUIRED);
11408
+ return {
11409
+ existing,
11410
+ values
11411
+ };
11412
+ }).map(({ existing, values }) => {
11413
+ if (existing) {
11414
+ if (Object.entries(values).every(([key, value]) => stringifyJsonCanonical(value) === stringifyJsonCanonical(existing[key] ?? null))) return existing;
11415
+ }
11416
+ const now = this.now();
11417
+ const preset = {
11418
+ id: existing?.id ?? this.createId("preset"),
11419
+ projectId: this.projectId,
11420
+ createdByUserId: null,
11421
+ ...values,
11422
+ revision: (existing?.revision ?? 0) + 1,
11423
+ createdAt: existing?.createdAt ?? now,
11424
+ updatedAt: now
11425
+ };
11426
+ this.configuredPresets.set(preset.key, preset);
11427
+ return preset;
11428
+ }) };
11429
+ }
11430
+ deleteUploadPreset(uploadPresetId) {
11431
+ const preset = [...this.configuredPresets.values()].find(({ id }) => id === uploadPresetId);
11432
+ if (!preset) throw fail(API_ERROR_CODES.UPLOAD_PRESET_NOT_FOUND);
11433
+ this.configuredPresets.delete(preset.key);
11434
+ return {};
11435
+ }
11436
+ toProjectSettings() {
11437
+ return {
11438
+ projectId: this.projectId,
11439
+ revision: this.settingsRevision,
11440
+ settings: {
11441
+ optOutJurisdictions: [],
11442
+ blockUnmoderatedAssets: true,
11443
+ storeSensitiveMetadata: false,
11444
+ streamingEnabled: false,
11445
+ aiMediaSearchEnabled: false,
11446
+ remoteUrlRule: null,
11447
+ websiteSubmissionsPerMinute: null,
11448
+ ...this.projectSettingsValues,
11449
+ humanReview: {
11450
+ allowedSamplePercent: 0,
11451
+ restrictedSamplePercent: 0,
11452
+ uncertaintyMarginPercent: 0,
11453
+ reviewMissingEvidence: false,
11454
+ ...this.projectSettingsValues.humanReview
11455
+ }
11456
+ }
11457
+ };
11458
+ }
11459
+ checkSettingsRevision(revision) {
11460
+ if (revision !== void 0 && revision !== null && Number(revision) !== this.settingsRevision) throw fail(API_ERROR_CODES.PROJECT_SETTINGS_REVISION_CONFLICT);
11461
+ }
11462
+ /** Replaces the settings: those left out return to their defaults. */
11463
+ updateProjectSettings(body) {
11464
+ this.checkSettingsRevision(body.revision);
11465
+ const settings = body.settings;
11466
+ if (!settings || typeof settings !== "object" || Array.isArray(settings)) throw invalidField("validation/invalid-type", "settings");
11467
+ const before = stringifyJsonCanonical(this.toProjectSettings().settings);
11468
+ const previous = this.projectSettingsValues;
11469
+ this.projectSettingsValues = { ...settings };
11470
+ if (stringifyJsonCanonical(this.toProjectSettings().settings) === before) this.projectSettingsValues = previous;
11471
+ else this.settingsRevision += 1;
11472
+ return this.toProjectSettings();
11473
+ }
11474
+ toMetadataFields() {
11475
+ return {
11476
+ projectId: this.projectId,
11477
+ revision: this.settingsRevision,
11478
+ fields: this.metadataFieldList
11479
+ };
11480
+ }
11481
+ /** Creates or replaces fields by ID, keeping the others in order. */
11482
+ ensureMetadataFields(body) {
11483
+ this.checkSettingsRevision(body.revision);
11484
+ const fields = Array.isArray(body.fields) ? body.fields : [];
11485
+ if (fields.length === 0) throw invalidField("validation/too-small", "fields");
11486
+ const byId = new Map(fields.map((field) => [field.id, field]));
11487
+ const merged = [...this.metadataFieldList.map((field) => byId.get(field.id) ?? field), ...fields.filter((field) => !this.metadataFieldList.some(({ id }) => id === field.id))];
11488
+ if (stringifyJsonCanonical(merged) !== stringifyJsonCanonical(this.metadataFieldList)) {
11489
+ this.metadataFieldList = merged;
11490
+ this.settingsRevision += 1;
11491
+ }
11492
+ return this.toMetadataFields();
11493
+ }
11494
+ deleteMetadataField(fieldId, query) {
11495
+ if (!this.metadataFieldList.some(({ id }) => id === fieldId)) throw fail(API_ERROR_CODES.METADATA_FIELD_NOT_FOUND, { details: { fieldId } });
11496
+ this.checkSettingsRevision(query.get("revision") ?? void 0);
11497
+ this.metadataFieldList = this.metadataFieldList.filter(({ id }) => id !== fieldId);
11498
+ this.settingsRevision += 1;
11499
+ return this.toMetadataFields();
11500
+ }
11163
11501
  /** Saves each lens in order, like the API: new ones, or a changed definition. */
11164
11502
  ensureLenses(body) {
11165
11503
  const lenses = Array.isArray(body.lenses) ? body.lenses : [];
@@ -11169,10 +11507,11 @@ var MockCalmLensApi = class {
11169
11507
  ensureLens(options) {
11170
11508
  const existing = this.lenses.get(options.identifier);
11171
11509
  if (!existing) return this.saveNewLens(options);
11172
- if (existing.name === options.name && (existing.description ?? null) === (options.description ?? null) && existing.type === options.type && existing.active === options.active && stringifyJsonCanonical(existing.transform ?? null) === stringifyJsonCanonical(options.transform ?? null)) return existing;
11510
+ if (existing.name === options.name && (existing.description ?? null) === (options.description ?? null) && existing.type === options.type && existing.active === (options.active ?? true) && stringifyJsonCanonical(existing.transform ?? null) === stringifyJsonCanonical(options.transform ?? null)) return existing;
11173
11511
  const lens = {
11174
11512
  ...existing,
11175
11513
  ...options,
11514
+ active: options.active ?? true,
11176
11515
  updatedAt: this.now()
11177
11516
  };
11178
11517
  this.lenses.set(lens.identifier, lens);
@@ -11184,6 +11523,7 @@ var MockCalmLensApi = class {
11184
11523
  id: this.createId("lens"),
11185
11524
  projectId: this.projectId,
11186
11525
  ...options,
11526
+ active: options.active ?? true,
11187
11527
  createdAt: now,
11188
11528
  updatedAt: now
11189
11529
  };
@@ -11290,12 +11630,14 @@ var MockCalmLensApi = class {
11290
11630
  code: "asset/not-available",
11291
11631
  message: "Asset is not available"
11292
11632
  }, url);
11293
- const grants = request.headers.get("x-api-key") === this.apiKey ? this.grants : [];
11633
+ const hasApiKey = request.headers.get("x-api-key") === this.apiKey;
11634
+ const grants = hasApiKey ? this.grants : [];
11294
11635
  const folders = await this.databaseStorage.listFolders?.(this.projectId) ?? [];
11295
11636
  const canDownload = () => permits(grants, "assets:download", asset.folderId ?? null, folders);
11296
11637
  const status = asset.classification.moderation.status;
11297
11638
  const isHead = request.method === "HEAD";
11298
11639
  const { rendered, preview } = asset.content;
11640
+ if (asset.visibility !== "public" && !grant && !hasApiKey && resource !== "placeholder" && resource !== "info") return notFound();
11299
11641
  if (resource === "info") return this.serveInfo(request, asset, Boolean(grant) || canDownload());
11300
11642
  if (asset.content.safetyHold) return notAvailable();
11301
11643
  if (resource === "placeholder") {
@@ -11329,7 +11671,7 @@ var MockCalmLensApi = class {
11329
11671
  "X-Content-Type-Options": "nosniff"
11330
11672
  });
11331
11673
  if (resource === "rendered" && !rendered || resource === "preview" && !preview) return noRenderedVersion();
11332
- if (isHls && !asset.content.hls) return noRenderedVersion();
11674
+ if (isHls && asset.content.hls?.status !== "ready") return noRenderedVersion();
11333
11675
  const stillImage = resource === "preview" || resource === "rendered" && rendered?.kind === "image";
11334
11676
  if (!stillImage && hasSelector) return invalidTransform();
11335
11677
  if (selector.options) {
@@ -11379,8 +11721,8 @@ var MockCalmLensApi = class {
11379
11721
  const { url, query } = request;
11380
11722
  const isPrivate = asset.visibility !== "public";
11381
11723
  if (isPrivate && !authorised) return this.jsonResponse(404, {
11382
- code: "asset/not-available",
11383
- message: "Asset is not available"
11724
+ code: "asset/not-found",
11725
+ message: "Asset not found"
11384
11726
  }, url);
11385
11727
  let claims = {};
11386
11728
  try {