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/cjs/testing.js CHANGED
@@ -1,15 +1,15 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_TestTriggers_BTyXtX0Q = require("./TestTriggers-BTyXtX0Q-ATuFDhLX.js");
3
- const require_ModerationContextLimits = require("./ModerationContextLimits-BxOmeSqq.js");
4
- const require_CalmLensServerClient = require("./CalmLensServerClient-nfu6_YEW.js");
5
- const require_CalmLensOptionKeys = require("./CalmLensOptionKeys-CYY6elxg.js");
2
+ const require_TestTriggers_CiFcTHX3 = require("./TestTriggers-CiFcTHX3-BmfH4J3f.js");
3
+ const require_ModerationContextLimits = require("./ModerationContextLimits-Bm8DxcJ_.js");
4
+ const require_CalmLensServerClient = require("./CalmLensServerClient-B35N3hCo.js");
5
+ const require_CalmLensOptionKeys = require("./CalmLensOptionKeys-DsPvFCox.js");
6
6
  const require_CryptoUtils_B_x8lMIx = require("./CryptoUtils-B_x8lMIx-YBW1-bvL.js");
7
- const require_CalmLensAppClient = require("./CalmLensAppClient-0UVCuNqW.js");
8
- const require_UploadController = require("./UploadController-DLyiLDTB.js");
7
+ const require_CalmLensAppClient = require("./CalmLensAppClient-DWClthAd.js");
8
+ const require_UploadController = require("./UploadController-DoD51qnV.js");
9
9
  let zod = require("zod");
10
- zod = require_TestTriggers_BTyXtX0Q.__toESM(zod, 1);
10
+ zod = require_TestTriggers_CiFcTHX3.__toESM(zod, 1);
11
11
  // src/contract/MediaTestTriggers.js
12
- const MEDIA_TEST_SIGNALS = [...require_TestTriggers_BTyXtX0Q.CLASSIFICATION_CATEGORIES, "violence.graphic"];
12
+ const MEDIA_TEST_SIGNALS = [...require_TestTriggers_CiFcTHX3.CLASSIFICATION_CATEGORIES, "violence.graphic"];
13
13
  const HEX_WORDS = [
14
14
  "zero",
15
15
  "one",
@@ -31,7 +31,7 @@ const HEX_WORDS = [
31
31
  /** Read this aloud, or render it as large, high-contrast text in a video frame. */
32
32
  async function generateMediaTestCode(signal, testInputKey) {
33
33
  if (!MEDIA_TEST_SIGNALS.includes(signal)) throw new RangeError("Unsupported media test signal");
34
- return `Calm Lens test ${[...await require_TestTriggers_BTyXtX0Q.getTestInputTag("media", signal, testInputKey)].map((character) => HEX_WORDS[Number.parseInt(character, 16)]).join(" ")} ${signal.replace(/[.-]/g, " ")} end test`;
34
+ return `Calm Lens test ${[...await require_TestTriggers_CiFcTHX3.getTestInputTag("media", signal, testInputKey)].map((character) => HEX_WORDS[Number.parseInt(character, 16)]).join(" ")} ${signal.replace(/[.-]/g, " ")} end test`;
35
35
  }
36
36
  // src/contract/Ids-BESMSxGb.js
37
37
  var __defProp = Object.defineProperty;
@@ -7989,7 +7989,7 @@ const EXAMPLE_IDS = {
7989
7989
  * across the packages that build records from plain strings).
7990
7990
  */
7991
7991
  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]] });
7992
- // src/contract/Permissions-BqpmE0Qa.js
7992
+ // src/contract/Permissions-DPNlE8m-.js
7993
7993
  const ACTION_SCHEMA = zod.enum([
7994
7994
  "assets:read",
7995
7995
  "assets:download",
@@ -8046,10 +8046,13 @@ const GRANT_SCHEMA = zod.object({
8046
8046
  const GRANTS_SCHEMA = zod.array(GRANT_SCHEMA).max(100);
8047
8047
  zod.enum([
8048
8048
  "admin",
8049
+ "configurator",
8049
8050
  "editor",
8050
8051
  "viewer",
8051
8052
  "custom"
8052
8053
  ]);
8054
+ [...ACTION_SCHEMA.options.filter((a) => !isProjectAction(a))];
8055
+ [...ACTION_SCHEMA.options.filter((a) => !isProjectAction(a))];
8053
8056
  const permits = (grants, action, folderId, folders) => grants.some((grant) => {
8054
8057
  if (![action, ...actionsImplying(action)].some((held) => grant.actions.includes(held))) return false;
8055
8058
  if (grant.folderId === null) return true;
@@ -8125,6 +8128,7 @@ const MOCK_QUALIFIERS = {
8125
8128
  "sexual-educational",
8126
8129
  "sexual-discussion",
8127
8130
  "sexual-fictional",
8131
+ "sexual-artistic",
8128
8132
  "sexual-support-prevention"
8129
8133
  ],
8130
8134
  "violence": [
@@ -8285,6 +8289,7 @@ const isScore = (score) => typeof score === "number" && Number.isFinite(score) &
8285
8289
  var MockDecision = class {
8286
8290
  #flags = /* @__PURE__ */ new Map();
8287
8291
  #notEvaluated = /* @__PURE__ */ new Set();
8292
+ #pendingReview;
8288
8293
  constructor(status) {
8289
8294
  if (!OUTCOMES.includes(status)) throw require_ModerationContextLimits.invalidArgument(`status must be one of ${OUTCOMES.join(", ")}`);
8290
8295
  this.status = status;
@@ -8318,15 +8323,32 @@ var MockDecision = class {
8318
8323
  this.#notEvaluated.add(category);
8319
8324
  return this;
8320
8325
  }
8326
+ /**
8327
+ * Leaves the decision waiting for human review, as `classification.moderation.pendingReview`
8328
+ * reports: `sampled`, or `uncertain` with the `uncertainCategories` that made it so. The queue's
8329
+ * decision (`decide` on the mock) clears it; `assets.decide` doesn't, as with the API.
8330
+ */
8331
+ pendingReview(reason, uncertainCategories = []) {
8332
+ if (this.status === "pending" || this.status === "failed") throw require_ModerationContextLimits.invalidArgument(`a ${this.status} decision can't wait for review`);
8333
+ if (reason !== "sampled" && reason !== "uncertain") throw require_ModerationContextLimits.invalidArgument("reason must be sampled or uncertain");
8334
+ if (reason === "sampled" && uncertainCategories.length) throw require_ModerationContextLimits.invalidArgument("a sampled review has no uncertain categories");
8335
+ for (const category of uncertainCategories) this.#checkCategory(category);
8336
+ this.#pendingReview = {
8337
+ reason,
8338
+ uncertainCategories: [...uncertainCategories]
8339
+ };
8340
+ return this;
8341
+ }
8321
8342
  #checkCategory(category) {
8322
8343
  if (!MOCK_CATEGORIES.includes(category)) throw require_ModerationContextLimits.invalidArgument(`${category} is not a CalmLens category`);
8323
8344
  }
8324
8345
  /**
8325
8346
  * The report a decided asset gets, as the API sends it: every category (unflagged ones
8326
8347
  * evaluated with score 0), policy-adjusted results and the automated status and
8327
- * `flaggedCategories`. `undefined` for `pending` and `failed`.
8348
+ * `flaggedCategories`. `requestedAt` is when a pending review joined the queue. `undefined` for
8349
+ * `pending` and `failed`.
8328
8350
  */
8329
- report() {
8351
+ report(requestedAt = 0) {
8330
8352
  const status = this.status;
8331
8353
  if (status === "pending" || status === "failed") return void 0;
8332
8354
  const action = (score) => status !== "allowed" && score >= .5 ? STATUS_ACTION[status] : "allow";
@@ -8352,9 +8374,20 @@ var MockDecision = class {
8352
8374
  return {
8353
8375
  categories: Object.fromEntries(evaluated.map(([category, score]) => [category, {
8354
8376
  score,
8355
- action: action(score)
8377
+ action: action(score),
8378
+ source: { kind: score >= .5 ? "default" : "below-threshold" },
8379
+ settings: {
8380
+ action: status === "allowed" ? "allow" : STATUS_ACTION[status],
8381
+ allowances: [],
8382
+ restrictions: []
8383
+ }
8356
8384
  }])),
8357
8385
  explanationComplete: true,
8386
+ policy: null,
8387
+ pendingReview: this.#pendingReview ? {
8388
+ requestedAt,
8389
+ ...this.#pendingReview
8390
+ } : null,
8358
8391
  source: "policy",
8359
8392
  rule: null,
8360
8393
  automatedStatus: status,
@@ -9145,7 +9178,16 @@ const MOCK_OPERATIONS = [
9145
9178
  "lenses.update",
9146
9179
  "lenses.delete",
9147
9180
  "ensureLens",
9148
- "ensureLenses"
9181
+ "ensureLenses",
9182
+ "uploadPresets.list",
9183
+ "uploadPresets.iterate",
9184
+ "uploadPresets.ensure",
9185
+ "uploadPresets.delete",
9186
+ "projectSettings.get",
9187
+ "projectSettings.update",
9188
+ "metadataFields.list",
9189
+ "metadataFields.ensure",
9190
+ "metadataFields.delete"
9149
9191
  ];
9150
9192
  const MAX_PAGE_SIZE = 100;
9151
9193
  const MAX_DECISION_NOTE_LENGTH = 1499;
@@ -9384,6 +9426,74 @@ const invalidField = (code, path) => new ApiFailure(400, require_ModerationConte
9384
9426
  message: `Invalid ${path}`,
9385
9427
  code
9386
9428
  }] });
9429
+ /** The asset fields an upload carries in its body; the API refuses them in the query string. */
9430
+ const UPLOAD_OPTION_KEYS = [
9431
+ "name",
9432
+ "description",
9433
+ "processingOptions",
9434
+ "visibility",
9435
+ "metadata",
9436
+ "tags",
9437
+ "authorId",
9438
+ "context",
9439
+ "externalId",
9440
+ "externalUrl",
9441
+ "folderId",
9442
+ "uploadPresetId"
9443
+ ];
9444
+ const indexOfBytes = (haystack, needle, from = 0) => {
9445
+ for (let index = haystack.indexOf(needle[0], from); index !== -1;) {
9446
+ if (index + needle.length > haystack.length) return -1;
9447
+ let offset = 1;
9448
+ while (offset < needle.length && haystack[index + offset] === needle[offset]) offset++;
9449
+ if (offset === needle.length) return index;
9450
+ index = haystack.indexOf(needle[0], index + 1);
9451
+ }
9452
+ return -1;
9453
+ };
9454
+ /**
9455
+ * Reads a raw upload's `multipart/form-data` body like the API: an `options` part, then a `file`
9456
+ * part, then the closing boundary. Anything else is refused.
9457
+ */
9458
+ const readUploadForm = (request) => {
9459
+ const contentType = request.headers.get("content-type") ?? "";
9460
+ if (contentType.split(";")[0].trim().toLowerCase() !== "multipart/form-data") throw new ApiFailure(415, require_ModerationContextLimits.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 });
9461
+ const boundary = /;\s*boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType);
9462
+ const invalid = (message) => fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message });
9463
+ if (!boundary) throw invalid("The multipart/form-data Content-Type needs a boundary");
9464
+ const encoder = new TextEncoder();
9465
+ const delimiter = encoder.encode(`\r\n--${boundary[1] ?? boundary[2]}`);
9466
+ const body = new Uint8Array(2 + request.bytes.length);
9467
+ body.set(encoder.encode("\r\n"));
9468
+ body.set(request.bytes, 2);
9469
+ const parts = [];
9470
+ let at = indexOfBytes(body, delimiter);
9471
+ while (at !== -1) {
9472
+ const start = at + delimiter.length;
9473
+ if (body[start] === 45 && body[start + 1] === 45) break;
9474
+ const headerEnd = indexOfBytes(body, encoder.encode("\r\n\r\n"), start);
9475
+ const next = headerEnd === -1 ? -1 : indexOfBytes(body, delimiter, headerEnd + 4);
9476
+ if (next === -1) throw invalid("The upload body ended before its closing boundary");
9477
+ const headers = new TextDecoder().decode(body.slice(start, headerEnd));
9478
+ const name = /content-disposition:\s*form-data\s*;[^\r\n]*?\bname="([^"]*)"/i.exec(headers)?.[1];
9479
+ parts.push({
9480
+ name,
9481
+ content: body.slice(headerEnd + 4, next)
9482
+ });
9483
+ at = next;
9484
+ }
9485
+ if (at === -1) throw invalid("The upload body ended before its closing boundary");
9486
+ 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");
9487
+ return {
9488
+ options: new TextDecoder().decode(parts[0].content),
9489
+ bytes: parts[1].content
9490
+ };
9491
+ };
9492
+ /** A request that names asset fields in its query, which the API refuses. */
9493
+ const assertNoUploadOptionsInQuery = (query) => {
9494
+ const fields = UPLOAD_OPTION_KEYS.filter((key) => query.has(key));
9495
+ if (fields.length) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_OPTIONS_IN_QUERY, { details: { fields } });
9496
+ };
9387
9497
  /**
9388
9498
  * Refuses `metadata` the API's schema refuses (METADATA_ITEM_SCHEMA): it is `null` or a list of
9389
9499
  * `{ id, value }` objects with a string `id` and any JSON `value`.
@@ -9409,7 +9519,7 @@ const MOCK_PRESET_NAMES = {
9409
9519
  * personal information and profanity, `block` otherwise) and no rules. The mock holds no built-in
9410
9520
  * preset settings, and uploads are never decided by a policy.
9411
9521
  */
9412
- const mockPresetSettings = () => ({ categorySettings: Object.fromEntries(require_TestTriggers_BTyXtX0Q.CLASSIFICATION_CATEGORIES.map((category) => [category, {
9522
+ const mockPresetSettings = () => ({ categorySettings: Object.fromEntries(require_TestTriggers_CiFcTHX3.CLASSIFICATION_CATEGORIES.map((category) => [category, {
9413
9523
  action: category === "personal-information" || category === "profanity" ? "allow" : "block",
9414
9524
  allowances: [],
9415
9525
  restrictions: []
@@ -9421,13 +9531,13 @@ const mockPresetSettings = () => ({ categorySettings: Object.fromEntries(require
9421
9531
  const checkPolicySettings = (settings) => {
9422
9532
  const categories = settings?.categorySettings;
9423
9533
  if (!categories || typeof categories !== "object") throw invalidField("validation/invalid-type", "settings.categorySettings");
9424
- for (const category of require_TestTriggers_BTyXtX0Q.CLASSIFICATION_CATEGORIES) {
9534
+ for (const category of require_TestTriggers_CiFcTHX3.CLASSIFICATION_CATEGORIES) {
9425
9535
  const value = categories[category];
9426
9536
  if (!value || typeof value !== "object") throw invalidField("validation/invalid-type", `settings.categorySettings.${category}`);
9427
9537
  for (const key of ["allowances", "restrictions"]) if (!Array.isArray(value[key])) throw invalidField("validation/invalid-type", `settings.categorySettings.${category}.${key}`);
9428
9538
  if (typeof value.action !== "string") throw invalidField("validation/invalid-value", `settings.categorySettings.${category}.action`);
9429
9539
  }
9430
- for (const key of Object.keys(categories)) if (!require_TestTriggers_BTyXtX0Q.CLASSIFICATION_CATEGORIES.includes(key)) throw invalidField("validation/unknown-field", `settings.categorySettings.${key}`);
9540
+ for (const key of Object.keys(categories)) if (!require_TestTriggers_CiFcTHX3.CLASSIFICATION_CATEGORIES.includes(key)) throw invalidField("validation/unknown-field", `settings.categorySettings.${key}`);
9431
9541
  };
9432
9542
  /** The client methods that send a request, the one it is recorded under first. */
9433
9543
  const operationsOf = (request) => {
@@ -9441,6 +9551,9 @@ const operationsOf = (request) => {
9441
9551
  case "folders": return method === "GET" ? ["folders.list", "folders.iterate"] : ["folders.create"];
9442
9552
  case "hash-lists": return method === "GET" ? ["hashLists.list", "hashLists.iterate"] : ["hashLists.create"];
9443
9553
  case "policy": return method === "GET" ? ["policies.retrieveAssigned"] : ["policies.assign"];
9554
+ case "upload-presets": return method === "GET" ? ["uploadPresets.list", "uploadPresets.iterate"] : ["uploadPresets.ensure"];
9555
+ case "settings": return method === "GET" ? ["projectSettings.get"] : ["projectSettings.update"];
9556
+ case "metadata-fields": return method === "GET" ? ["metadataFields.list"] : ["metadataFields.ensure"];
9444
9557
  case "assets/search": return ["assets.search"];
9445
9558
  case "assets/batch": return ["assets.batch"];
9446
9559
  case "signed-asset-urls": return ["cdn.signAssetUrl"];
@@ -9450,6 +9563,7 @@ const operationsOf = (request) => {
9450
9563
  return isTextUpload(request) ? ["assets.classify", "text.classify"] : ["assets.classify"];
9451
9564
  }
9452
9565
  if (segments[2] === "assets" && segments[4] === "timeline" && segments.length === 5) return ["assets.listTimeline", "assets.iterateTimeline"];
9566
+ if (segments[2] === "metadata-fields" && segments.length === 4) return ["metadataFields.delete"];
9453
9567
  return [];
9454
9568
  }
9455
9569
  if (root === "policies") {
@@ -9461,6 +9575,7 @@ const operationsOf = (request) => {
9461
9575
  return method === "GET" ? ["policies.retrieve"] : method === "PATCH" ? ["policies.update"] : ["policies.delete"];
9462
9576
  }
9463
9577
  if (root === "lenses" && segments[1] !== void 0) return method === "GET" ? ["lenses.retrieve"] : method === "PATCH" ? ["lenses.update"] : ["lenses.delete"];
9578
+ if (root === "upload-presets" && segments.length === 2) return ["uploadPresets.delete"];
9464
9579
  if (root === "upload-presets") {
9465
9580
  if (segments[3] === void 0) return [query.get("wait") === "false" ? "assets.create" : "assets.classify"];
9466
9581
  return segments[4] === "part" ? ["assets.uploadPart"] : ["assets.retrieve"];
@@ -9489,7 +9604,15 @@ const operationsOf = (request) => {
9489
9604
  }
9490
9605
  return [];
9491
9606
  };
9492
- const isTextUpload = (request) => request.headers.get("x-calmlens-upload") === "content" && request.headers.get("content-type") === "text/plain";
9607
+ /** A plain-text upload: the SDKs send text as a JSON body with `content.plainText`. */
9608
+ const isTextUpload = (request) => {
9609
+ if (request.headers.get("x-calmlens-upload")) return false;
9610
+ try {
9611
+ return typeof JSON.parse(new TextDecoder().decode(request.bytes))?.content?.plainText === "string";
9612
+ } catch {
9613
+ return false;
9614
+ }
9615
+ };
9493
9616
  /** Like the API: a new folder is 201 Created, a queued batch 202 Accepted, everything else 200. */
9494
9617
  const SUCCESS_STATUS = {
9495
9618
  "folders.create": 201,
@@ -9533,6 +9656,10 @@ var MockCalmLensApi = class {
9533
9656
  this.hashLists = /* @__PURE__ */ new Map();
9534
9657
  this.hashListEntries = /* @__PURE__ */ new Map();
9535
9658
  this.pageFailure = (code, path) => code === "cursor/invalid" ? fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_CURSOR) : invalidField(code, path ?? "pageSize");
9659
+ this.configuredPresets = /* @__PURE__ */ new Map();
9660
+ this.settingsRevision = 1;
9661
+ this.projectSettingsValues = {};
9662
+ this.metadataFieldList = [];
9536
9663
  this.options = options;
9537
9664
  this.projectId = options.projectId;
9538
9665
  this.apiKey = options.apiKey;
@@ -9654,6 +9781,7 @@ var MockCalmLensApi = class {
9654
9781
  this.pendingReruns.delete(asset.id);
9655
9782
  const decided = await this.applyOutcome(asset, decision, "requested");
9656
9783
  const now = this.now();
9784
+ if (!review) decided.classification.moderation.pendingReview = null;
9657
9785
  decided.classification.moderation.manualReviews = [...decided.classification.moderation.manualReviews ?? [], {
9658
9786
  id: this.createId("rev"),
9659
9787
  decision,
@@ -9774,9 +9902,20 @@ var MockCalmLensApi = class {
9774
9902
  }
9775
9903
  return failure;
9776
9904
  }
9777
- describeBody({ bytes, headers }) {
9905
+ describeBody(request) {
9906
+ const { bytes, headers } = request;
9778
9907
  if (bytes.byteLength === 0) return void 0;
9779
9908
  const type = headers.get("content-type") ?? "";
9909
+ if (type.startsWith("multipart/form-data")) try {
9910
+ const form = readUploadForm(request);
9911
+ const file = request.query.get("contentType") ?? "";
9912
+ return {
9913
+ options: JSON.parse(form.options),
9914
+ file: file.startsWith("text/") ? new TextDecoder().decode(form.bytes) : form.bytes.slice()
9915
+ };
9916
+ } catch {
9917
+ return bytes.slice();
9918
+ }
9780
9919
  const text = () => new TextDecoder().decode(bytes);
9781
9920
  if (type === "application/json") try {
9782
9921
  return JSON.parse(text());
@@ -9818,13 +9957,20 @@ var MockCalmLensApi = class {
9818
9957
  if (!(request.segments[0] === "upload-presets") && headers.get("x-api-key") !== this.apiKey) return this.failureResponse(fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_API_KEY), url);
9819
9958
  const key = headers.get("idempotency-key")?.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");
9820
9959
  const upload = headers.get("x-calmlens-upload");
9960
+ const contentType = headers.get("content-type");
9961
+ const isForm = !!upload && /^multipart\/form-data\b/i.test(contentType ?? "");
9962
+ let formOptions;
9963
+ if (isForm && request.segments.at(-1) !== "part") try {
9964
+ formOptions = readUploadForm(request).options;
9965
+ } catch {}
9821
9966
  const fingerprint = JSON.stringify([
9822
9967
  request.method,
9823
9968
  request.segments,
9824
9969
  [...request.query].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0),
9825
- headers.get("content-type"),
9970
+ isForm ? "multipart/form-data" : contentType,
9826
9971
  upload,
9827
- upload ? request.bytes.byteLength : new TextDecoder().decode(request.bytes)
9972
+ upload ? request.bytes.byteLength : new TextDecoder().decode(request.bytes),
9973
+ formOptions ?? null
9828
9974
  ]);
9829
9975
  if (key !== void 0) {
9830
9976
  if (!isValidIdempotencyKey(key)) return this.failureResponse(fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_IDEMPOTENCY_KEY), url);
@@ -9875,8 +10021,17 @@ var MockCalmLensApi = class {
9875
10021
  case "POST lenses": return [201, this.createLens(this.json(request))];
9876
10022
  case "GET policy": return [200, this.toPolicy(this.findPolicy(this.ensurePolicies()))];
9877
10023
  case "PUT policy": return [200, this.assignPolicy(this.json(request))];
10024
+ case "GET upload-presets": return [200, this.listUploadPresets(request.query)];
10025
+ case "PUT upload-presets": return [200, this.ensureUploadPresets(this.json(request))];
10026
+ case "GET settings": return [200, this.toProjectSettings()];
10027
+ case "PUT settings": return [200, this.updateProjectSettings(this.json(request))];
10028
+ case "GET metadata-fields": return [200, this.toMetadataFields()];
10029
+ case "PUT metadata-fields": return [200, this.ensureMetadataFields(this.json(request))];
9878
10030
  }
9879
10031
  const [, , collection, itemId, itemAction, ...more] = segments;
10032
+ if (collection === "metadata-fields" && itemId !== void 0 && itemAction === void 0) {
10033
+ if (method === "DELETE") return [200, this.deleteMetadataField(itemId, request.query)];
10034
+ }
9880
10035
  if (collection === "assets" && itemId !== void 0 && itemAction === "timeline" && more.length === 0 && method === "GET") return [200, await this.listTimeline(itemId, request.query)];
9881
10036
  }
9882
10037
  if (root === "policies" && rest.length === 0) {
@@ -9897,6 +10052,9 @@ var MockCalmLensApi = class {
9897
10052
  case "PATCH": return [200, this.updateLens(id, this.json(request))];
9898
10053
  case "DELETE": return [200, this.deleteLens(id)];
9899
10054
  }
10055
+ if (root === "upload-presets" && id !== void 0 && action === void 0) {
10056
+ if (method === "DELETE") return [200, this.deleteUploadPreset(id)];
10057
+ }
9900
10058
  if (root === "upload-presets" && id !== void 0 && action === "assets") return [200, await this.presetRoute(request, id, rest, session)];
9901
10059
  if (root === "assets" && id !== void 0 && rest.length === 0) switch (`${method} ${action ?? ""}`) {
9902
10060
  case "GET ": return [200, await this.findOwnAsset(id)];
@@ -10452,42 +10610,49 @@ var MockCalmLensApi = class {
10452
10610
  await this.databaseStorage.deleteAsset(id);
10453
10611
  }
10454
10612
  }
10455
- /** The upload fields of `POST .../assets`: raw uploads carry them in the query. */
10613
+ /**
10614
+ * The upload fields of `POST .../assets`, from the JSON body (text and URLs) or an upload form's
10615
+ * options (files). Like the API, asset fields in the query are refused.
10616
+ */
10456
10617
  uploadFields(request) {
10618
+ const { query } = request;
10619
+ assertNoUploadOptionsInQuery(query);
10457
10620
  const upload = request.headers.get("x-calmlens-upload");
10458
10621
  if (upload !== "content" && upload !== "part") {
10459
10622
  const body = this.json(request);
10460
10623
  checkMetadata(body.metadata);
10461
- return body;
10624
+ const { content, part, sizeInBytes: _size, totalSizeInBytes, ...fields } = body;
10625
+ const text = content ?? part;
10626
+ if (text === void 0) return fields;
10627
+ if (typeof text.plainText !== "string" || typeof text.type !== "string") throw invalidField("validation/invalid-type", content ? "content" : "part");
10628
+ return {
10629
+ ...fields,
10630
+ contentType: text.type,
10631
+ bytes: new TextEncoder().encode(text.plainText),
10632
+ part: part ? {
10633
+ partNumber: typeof part.partNumber === "number" ? part.partNumber : 1,
10634
+ isFinal: part.isFinal === true,
10635
+ totalSizeInBytes: typeof totalSizeInBytes === "number" ? totalSizeInBytes : void 0
10636
+ } : void 0
10637
+ };
10462
10638
  }
10463
- const { query } = request;
10464
- const text = (name) => query.get(name) ?? void 0;
10465
- const parsed = (name) => {
10466
- const raw = query.get(name);
10467
- if (raw === null) return void 0;
10468
- try {
10469
- return JSON.parse(raw);
10470
- } catch {
10471
- throw invalidField("validation/invalid-value", name);
10472
- }
10473
- };
10639
+ const form = readUploadForm(request);
10640
+ let options;
10641
+ try {
10642
+ options = JSON.parse(form.options);
10643
+ } catch {
10644
+ throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "The options part must be a JSON object with the asset's fields" });
10645
+ }
10646
+ if (!options || typeof options !== "object" || Array.isArray(options)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "The options part must be a JSON object with the asset's fields" });
10647
+ const unknown = Object.keys(options).find((key) => !UPLOAD_OPTION_KEYS.includes(key));
10648
+ if (unknown !== void 0) throw invalidField("validation/unknown-field", unknown);
10649
+ if (typeof options.name !== "string") throw invalidField("validation/invalid-type", "name");
10650
+ checkMetadata(options.metadata);
10474
10651
  const total = query.get("totalSizeInBytes");
10475
- checkMetadata(parsed("metadata"));
10476
10652
  return {
10477
- name: query.get("name") ?? "",
10478
- description: text("description"),
10479
- processingOptions: parsed("processingOptions"),
10480
- visibility: text("visibility"),
10481
- metadata: parsed("metadata"),
10482
- tags: parsed("tags"),
10483
- authorId: text("authorId"),
10484
- context: parsed("context"),
10485
- externalId: text("externalId"),
10486
- externalUrl: text("externalUrl"),
10487
- folderId: text("folderId"),
10488
- uploadPresetId: text("uploadPresetId"),
10489
- contentType: query.get("contentType") ?? request.headers.get("content-type") ?? "",
10490
- bytes: request.bytes,
10653
+ ...options,
10654
+ contentType: query.get("contentType") ?? "",
10655
+ bytes: form.bytes,
10491
10656
  part: upload === "part" ? {
10492
10657
  partNumber: this.integer(query, "partNumber", 1),
10493
10658
  isFinal: query.get("isFinal") === "true",
@@ -10496,7 +10661,40 @@ var MockCalmLensApi = class {
10496
10661
  };
10497
10662
  }
10498
10663
  async createAsset(request) {
10499
- return this.storeAsset(this.uploadFields(request), request.query.get("wait") === "false");
10664
+ return this.storeAsset(this.applyUploadPreset(this.uploadFields(request)), request.query.get("wait") === "false");
10665
+ }
10666
+ /**
10667
+ * An API-key upload through a preset, as the API applies it: the preset gives the folder and
10668
+ * visibility, which the upload can't change, and the processing options unless the upload sets
10669
+ * its own, and refuses types and sizes it doesn't accept.
10670
+ */
10671
+ applyUploadPreset(fields) {
10672
+ if (!fields.uploadPresetId) return fields;
10673
+ const preset = [...this.configuredPresets.values()].find(({ id }) => id === fields.uploadPresetId);
10674
+ if (!preset) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_NOT_FOUND);
10675
+ if (!preset.enabled) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_DISABLED);
10676
+ if (preset.folderId && fields.folderId && fields.folderId !== preset.folderId) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_FIELD_NOT_ALLOWED, { details: { field: "folderId" } });
10677
+ if (fields.visibility && fields.visibility !== preset.visibility) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_FIELD_NOT_ALLOWED, { details: { field: "visibility" } });
10678
+ const contentType = fields.contentType;
10679
+ if (preset.allowedContentTypes?.length && contentType !== void 0 && !require_UploadController.isFileAccepted({
10680
+ name: fields.name,
10681
+ type: contentType
10682
+ }, preset.allowedContentTypes.join(","))) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, { details: {
10683
+ source: "preset",
10684
+ contentType,
10685
+ allowedContentTypes: preset.allowedContentTypes
10686
+ } });
10687
+ const size = fields.part?.totalSizeInBytes ?? fields.bytes?.byteLength;
10688
+ if (preset.maxSizeInBytes && size !== void 0 && size > preset.maxSizeInBytes) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_TOO_LARGE, { details: {
10689
+ limitBytes: preset.maxSizeInBytes,
10690
+ source: "preset"
10691
+ } });
10692
+ return {
10693
+ ...fields,
10694
+ folderId: preset.folderId ?? fields.folderId,
10695
+ visibility: preset.visibility,
10696
+ processingOptions: fields.processingOptions ?? preset.processingOptions
10697
+ };
10500
10698
  }
10501
10699
  async storeAsset(fields, queue) {
10502
10700
  if (!fields.name) throw fail(require_ModerationContextLimits.API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Asset name is required" });
@@ -10541,6 +10739,7 @@ var MockCalmLensApi = class {
10541
10739
  id,
10542
10740
  projectId: this.projectId,
10543
10741
  parentId: null,
10742
+ parentPages: [],
10544
10743
  folderId: fields.folderId ?? null,
10545
10744
  uploadPresetId: fields.uploadPresetId ?? null,
10546
10745
  createdAt: now,
@@ -10590,6 +10789,8 @@ var MockCalmLensApi = class {
10590
10789
  status: "pending",
10591
10790
  manualReviews: [],
10592
10791
  automatedStatus: null,
10792
+ policy: null,
10793
+ pendingReview: null,
10593
10794
  source: null,
10594
10795
  rule: null,
10595
10796
  explanationComplete: null,
@@ -10727,7 +10928,7 @@ var MockCalmLensApi = class {
10727
10928
  * it, a decided image reports the person and face detection its upload turned on.
10728
10929
  */
10729
10930
  async decided(asset, decision) {
10730
- const next = await this.applyOutcome(asset, decision.status, "policy", decision.report());
10931
+ const next = await this.applyOutcome(asset, decision.status, "policy", decision.report(this.now()));
10731
10932
  const features = this.processingOptions.get(asset.id)?.features;
10732
10933
  if (next.classification.status !== "completed" || asset.type !== "image") return next;
10733
10934
  return {
@@ -10996,7 +11197,11 @@ var MockCalmLensApi = class {
10996
11197
  if (preset.allowedContentTypes && !require_UploadController.isFileAccepted({
10997
11198
  name: fields.name,
10998
11199
  type: fields.contentType ?? ""
10999
- }, preset.allowedContentTypes.join(","))) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, { details: { source: "preset" } });
11200
+ }, preset.allowedContentTypes.join(","))) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, { details: {
11201
+ source: "preset",
11202
+ contentType: fields.contentType ?? "",
11203
+ allowedContentTypes: preset.allowedContentTypes
11204
+ } });
11000
11205
  const size = fields.part?.totalSizeInBytes ?? fields.bytes?.byteLength;
11001
11206
  if (preset.maxFileSizeInBytes !== void 0 && size !== void 0 && size > preset.maxFileSizeInBytes) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_TOO_LARGE, { details: {
11002
11207
  limitBytes: preset.maxFileSizeInBytes,
@@ -11162,6 +11367,139 @@ var MockCalmLensApi = class {
11162
11367
  async assertUniqueFolderName(name, parentId, excludeFolderId) {
11163
11368
  if ((await this.databaseStorage.listFolders?.(this.projectId) ?? []).find((folder) => folder.id !== excludeFolderId && (folder.parentId ?? null) === parentId && folder.name === name)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.DUPLICATE_FOLDER_NAME, { message: `A folder named "${name}" already exists in this location.` });
11164
11369
  }
11370
+ /** A page of the project's upload presets, oldest first unless `sort` says otherwise. */
11371
+ listUploadPresets(query) {
11372
+ return createPage([...this.configuredPresets.values()], this.pageQuery(query), {
11373
+ scope: `upload-presets:${this.projectId}`,
11374
+ fail: this.pageFailure,
11375
+ defaultSort: [{
11376
+ field: "createdAt",
11377
+ direction: "asc"
11378
+ }]
11379
+ });
11380
+ }
11381
+ /** Like the API: every preset's revision and settings are checked before any is saved. */
11382
+ ensureUploadPresets(body) {
11383
+ const definitions = Array.isArray(body.uploadPresets) ? body.uploadPresets : [];
11384
+ if (definitions.length === 0) throw invalidField("validation/too-small", "uploadPresets");
11385
+ return { uploadPresets: definitions.map((definition, index) => {
11386
+ if (typeof definition.key !== "string" || !definition.key) throw invalidField("validation/invalid-type", `uploadPresets.${index}.key`);
11387
+ if (typeof definition.name !== "string" || !definition.name) throw invalidField("validation/invalid-type", `uploadPresets.${index}.name`);
11388
+ const existing = this.configuredPresets.get(definition.key);
11389
+ if (definition.revision !== void 0 && definition.revision !== (existing?.revision ?? 0)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_REVISION_CONFLICT, { details: {
11390
+ key: definition.key,
11391
+ revision: existing?.revision ?? 0
11392
+ } });
11393
+ const list = (value) => Array.isArray(value) && value.length ? [...new Set(value)] : null;
11394
+ const values = {
11395
+ key: definition.key,
11396
+ name: definition.name,
11397
+ access: definition.access ?? "token",
11398
+ enabled: definition.enabled ?? true,
11399
+ allowedContentTypes: list(definition.allowedContentTypes),
11400
+ maxSizeInBytes: definition.maxSizeInBytes ?? null,
11401
+ folderId: definition.folderId ?? null,
11402
+ policyId: definition.policyId ?? null,
11403
+ visibility: definition.visibility ?? "private",
11404
+ processingOptions: definition.processingOptions ?? null,
11405
+ revealDecision: definition.revealDecision ?? false,
11406
+ dailyUploadLimit: definition.dailyUploadLimit ?? null,
11407
+ allowedOrigins: list(definition.allowedOrigins)
11408
+ };
11409
+ if (values.access === "anyone" && !values.dailyUploadLimit) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_DAILY_LIMIT_REQUIRED);
11410
+ return {
11411
+ existing,
11412
+ values
11413
+ };
11414
+ }).map(({ existing, values }) => {
11415
+ if (existing) {
11416
+ if (Object.entries(values).every(([key, value]) => require_CalmLensServerClient.stringifyJsonCanonical(value) === require_CalmLensServerClient.stringifyJsonCanonical(existing[key] ?? null))) return existing;
11417
+ }
11418
+ const now = this.now();
11419
+ const preset = {
11420
+ id: existing?.id ?? this.createId("preset"),
11421
+ projectId: this.projectId,
11422
+ createdByUserId: null,
11423
+ ...values,
11424
+ revision: (existing?.revision ?? 0) + 1,
11425
+ createdAt: existing?.createdAt ?? now,
11426
+ updatedAt: now
11427
+ };
11428
+ this.configuredPresets.set(preset.key, preset);
11429
+ return preset;
11430
+ }) };
11431
+ }
11432
+ deleteUploadPreset(uploadPresetId) {
11433
+ const preset = [...this.configuredPresets.values()].find(({ id }) => id === uploadPresetId);
11434
+ if (!preset) throw fail(require_ModerationContextLimits.API_ERROR_CODES.UPLOAD_PRESET_NOT_FOUND);
11435
+ this.configuredPresets.delete(preset.key);
11436
+ return {};
11437
+ }
11438
+ toProjectSettings() {
11439
+ return {
11440
+ projectId: this.projectId,
11441
+ revision: this.settingsRevision,
11442
+ settings: {
11443
+ optOutJurisdictions: [],
11444
+ blockUnmoderatedAssets: true,
11445
+ storeSensitiveMetadata: false,
11446
+ streamingEnabled: false,
11447
+ aiMediaSearchEnabled: false,
11448
+ remoteUrlRule: null,
11449
+ websiteSubmissionsPerMinute: null,
11450
+ ...this.projectSettingsValues,
11451
+ humanReview: {
11452
+ allowedSamplePercent: 0,
11453
+ restrictedSamplePercent: 0,
11454
+ uncertaintyMarginPercent: 0,
11455
+ reviewMissingEvidence: false,
11456
+ ...this.projectSettingsValues.humanReview
11457
+ }
11458
+ }
11459
+ };
11460
+ }
11461
+ checkSettingsRevision(revision) {
11462
+ if (revision !== void 0 && revision !== null && Number(revision) !== this.settingsRevision) throw fail(require_ModerationContextLimits.API_ERROR_CODES.PROJECT_SETTINGS_REVISION_CONFLICT);
11463
+ }
11464
+ /** Replaces the settings: those left out return to their defaults. */
11465
+ updateProjectSettings(body) {
11466
+ this.checkSettingsRevision(body.revision);
11467
+ const settings = body.settings;
11468
+ if (!settings || typeof settings !== "object" || Array.isArray(settings)) throw invalidField("validation/invalid-type", "settings");
11469
+ const before = require_CalmLensServerClient.stringifyJsonCanonical(this.toProjectSettings().settings);
11470
+ const previous = this.projectSettingsValues;
11471
+ this.projectSettingsValues = { ...settings };
11472
+ if (require_CalmLensServerClient.stringifyJsonCanonical(this.toProjectSettings().settings) === before) this.projectSettingsValues = previous;
11473
+ else this.settingsRevision += 1;
11474
+ return this.toProjectSettings();
11475
+ }
11476
+ toMetadataFields() {
11477
+ return {
11478
+ projectId: this.projectId,
11479
+ revision: this.settingsRevision,
11480
+ fields: this.metadataFieldList
11481
+ };
11482
+ }
11483
+ /** Creates or replaces fields by ID, keeping the others in order. */
11484
+ ensureMetadataFields(body) {
11485
+ this.checkSettingsRevision(body.revision);
11486
+ const fields = Array.isArray(body.fields) ? body.fields : [];
11487
+ if (fields.length === 0) throw invalidField("validation/too-small", "fields");
11488
+ const byId = new Map(fields.map((field) => [field.id, field]));
11489
+ const merged = [...this.metadataFieldList.map((field) => byId.get(field.id) ?? field), ...fields.filter((field) => !this.metadataFieldList.some(({ id }) => id === field.id))];
11490
+ if (require_CalmLensServerClient.stringifyJsonCanonical(merged) !== require_CalmLensServerClient.stringifyJsonCanonical(this.metadataFieldList)) {
11491
+ this.metadataFieldList = merged;
11492
+ this.settingsRevision += 1;
11493
+ }
11494
+ return this.toMetadataFields();
11495
+ }
11496
+ deleteMetadataField(fieldId, query) {
11497
+ if (!this.metadataFieldList.some(({ id }) => id === fieldId)) throw fail(require_ModerationContextLimits.API_ERROR_CODES.METADATA_FIELD_NOT_FOUND, { details: { fieldId } });
11498
+ this.checkSettingsRevision(query.get("revision") ?? void 0);
11499
+ this.metadataFieldList = this.metadataFieldList.filter(({ id }) => id !== fieldId);
11500
+ this.settingsRevision += 1;
11501
+ return this.toMetadataFields();
11502
+ }
11165
11503
  /** Saves each lens in order, like the API: new ones, or a changed definition. */
11166
11504
  ensureLenses(body) {
11167
11505
  const lenses = Array.isArray(body.lenses) ? body.lenses : [];
@@ -11171,10 +11509,11 @@ var MockCalmLensApi = class {
11171
11509
  ensureLens(options) {
11172
11510
  const existing = this.lenses.get(options.identifier);
11173
11511
  if (!existing) return this.saveNewLens(options);
11174
- if (existing.name === options.name && (existing.description ?? null) === (options.description ?? null) && existing.type === options.type && existing.active === options.active && require_CalmLensServerClient.stringifyJsonCanonical(existing.transform ?? null) === require_CalmLensServerClient.stringifyJsonCanonical(options.transform ?? null)) return existing;
11512
+ if (existing.name === options.name && (existing.description ?? null) === (options.description ?? null) && existing.type === options.type && existing.active === (options.active ?? true) && require_CalmLensServerClient.stringifyJsonCanonical(existing.transform ?? null) === require_CalmLensServerClient.stringifyJsonCanonical(options.transform ?? null)) return existing;
11175
11513
  const lens = {
11176
11514
  ...existing,
11177
11515
  ...options,
11516
+ active: options.active ?? true,
11178
11517
  updatedAt: this.now()
11179
11518
  };
11180
11519
  this.lenses.set(lens.identifier, lens);
@@ -11186,6 +11525,7 @@ var MockCalmLensApi = class {
11186
11525
  id: this.createId("lens"),
11187
11526
  projectId: this.projectId,
11188
11527
  ...options,
11528
+ active: options.active ?? true,
11189
11529
  createdAt: now,
11190
11530
  updatedAt: now
11191
11531
  };
@@ -11292,12 +11632,14 @@ var MockCalmLensApi = class {
11292
11632
  code: "asset/not-available",
11293
11633
  message: "Asset is not available"
11294
11634
  }, url);
11295
- const grants = request.headers.get("x-api-key") === this.apiKey ? this.grants : [];
11635
+ const hasApiKey = request.headers.get("x-api-key") === this.apiKey;
11636
+ const grants = hasApiKey ? this.grants : [];
11296
11637
  const folders = await this.databaseStorage.listFolders?.(this.projectId) ?? [];
11297
11638
  const canDownload = () => permits(grants, "assets:download", asset.folderId ?? null, folders);
11298
11639
  const status = asset.classification.moderation.status;
11299
11640
  const isHead = request.method === "HEAD";
11300
11641
  const { rendered, preview } = asset.content;
11642
+ if (asset.visibility !== "public" && !grant && !hasApiKey && resource !== "placeholder" && resource !== "info") return notFound();
11301
11643
  if (resource === "info") return this.serveInfo(request, asset, Boolean(grant) || canDownload());
11302
11644
  if (asset.content.safetyHold) return notAvailable();
11303
11645
  if (resource === "placeholder") {
@@ -11331,7 +11673,7 @@ var MockCalmLensApi = class {
11331
11673
  "X-Content-Type-Options": "nosniff"
11332
11674
  });
11333
11675
  if (resource === "rendered" && !rendered || resource === "preview" && !preview) return noRenderedVersion();
11334
- if (isHls && !asset.content.hls) return noRenderedVersion();
11676
+ if (isHls && asset.content.hls?.status !== "ready") return noRenderedVersion();
11335
11677
  const stillImage = resource === "preview" || resource === "rendered" && rendered?.kind === "image";
11336
11678
  if (!stillImage && hasSelector) return invalidTransform();
11337
11679
  if (selector.options) {
@@ -11381,8 +11723,8 @@ var MockCalmLensApi = class {
11381
11723
  const { url, query } = request;
11382
11724
  const isPrivate = asset.visibility !== "public";
11383
11725
  if (isPrivate && !authorised) return this.jsonResponse(404, {
11384
- code: "asset/not-available",
11385
- message: "Asset is not available"
11726
+ code: "asset/not-found",
11727
+ message: "Asset not found"
11386
11728
  }, url);
11387
11729
  let claims = {};
11388
11730
  try {