calmlens 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +13 -9
  2. package/bin/calmlens.js +1646 -706
  3. package/cjs/{BrowserUpload-CJ4Xc9bR.js → BrowserUpload-CeSwiMo5.js} +1 -1
  4. package/{esm/BrowserUpload-RkxV_Vv7.d.ts → cjs/BrowserUpload-D-NnAN7g.d.ts} +2 -2
  5. package/cjs/{CalmLensAppClient-LHMEQ-UZ.js → CalmLensAppClient-0UVCuNqW.js} +30 -10
  6. package/cjs/{CalmLensAppClient-B5gfOB6J.d.ts → CalmLensAppClient-gG16T2py.d.ts} +13 -3
  7. package/cjs/{CalmLensOptionKeys-BUj7v5AG.js → CalmLensOptionKeys-CYY6elxg.js} +242 -345
  8. package/cjs/{CalmLensServerClient-DCSbwIBs.d.ts → CalmLensServerClient-BHx3x_nZ.d.ts} +107 -49
  9. package/cjs/{CalmLensServerClient-BVOEUT_v.js → CalmLensServerClient-nfu6_YEW.js} +297 -92
  10. package/cjs/{CalmLensTypes-DpU-hXq2.d.ts → CalmLensTypes-CUB0YYVz.d.ts} +26601 -27354
  11. package/cjs/{Classification-D3SkprrQ-CMnQKW13.d.ts → Classification-Q5zGpR8l-CEWjnE39.d.ts} +731 -607
  12. package/cjs/Core-C82YmjjX.d.ts +823 -0
  13. package/cjs/Core-Dc3cteU7.js +998 -0
  14. package/cjs/FileIcons-4qSX7DW2.d.ts +67 -0
  15. package/cjs/{ModerationContextLimits-FDpQmw_T.js → ModerationContextLimits-BxOmeSqq.js} +970 -278
  16. package/cjs/{ReactUpload-BvpW4hJi.js → ReactUpload-BK2O3dnK.js} +1 -1
  17. package/cjs/{ReactUpload-huIMnOJ4.d.ts → ReactUpload-DiiXfKvj.d.ts} +1 -1
  18. package/cjs/{TestTriggers-CMwMrbjy-K0YBzu2a.js → TestTriggers-BTyXtX0Q-ATuFDhLX.js} +343 -35
  19. package/{esm/TestTriggers-D-fwfhEP-hlaP1oW2.d.ts → cjs/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts} +146 -8
  20. package/cjs/{UploadController-D4qOZZc3.js → UploadController-DLyiLDTB.js} +34 -14
  21. package/cjs/{WebhookPayload-CQg8BBZQ.d.ts → WebhookPayload-BLT2y_Jy.d.ts} +93 -86
  22. package/cjs/app.d.ts +6 -7
  23. package/cjs/app.js +4 -3
  24. package/cjs/elements.d.ts +123 -22
  25. package/cjs/elements.js +553 -156
  26. package/cjs/file-icons.d.ts +2 -67
  27. package/cjs/index-CKRgjV16.d.ts +16 -0
  28. package/cjs/index.d.ts +5 -6
  29. package/cjs/index.js +3 -2
  30. package/cjs/react-native.d.ts +52 -11
  31. package/cjs/react-native.js +231 -99
  32. package/cjs/react.d.ts +42 -9
  33. package/cjs/react.js +381 -118
  34. package/cjs/server.d.ts +48 -7
  35. package/cjs/server.js +7 -3
  36. package/cjs/test-inputs.d.ts +2 -2
  37. package/cjs/test-inputs.js +13 -9
  38. package/cjs/testing.d.ts +29 -16
  39. package/cjs/testing.js +1511 -397
  40. package/cjs/ui-CTBUxnVp.d.ts +139 -0
  41. package/cjs/ui-CZ8exACq.js +1359 -0
  42. package/cjs/ui.d.ts +3 -2
  43. package/cjs/ui.js +45 -22
  44. package/cjs/vue.d.ts +802 -199
  45. package/cjs/vue.js +359 -127
  46. package/{cjs/BrowserUpload-RkxV_Vv7.d.ts → esm/BrowserUpload-D-NnAN7g.d.ts} +2 -2
  47. package/esm/{BrowserUpload-DpzS2bbj.js → BrowserUpload-i9OhCzMJ.js} +1 -1
  48. package/esm/{CalmLensAppClient-BjlvBweS.js → CalmLensAppClient-CK4_Py0c.js} +30 -10
  49. package/esm/{CalmLensAppClient-B5gfOB6J.d.ts → CalmLensAppClient-gG16T2py.d.ts} +13 -3
  50. package/esm/{CalmLensOptionKeys-BKez0Wiw.js → CalmLensOptionKeys-BGZlIsT2.js} +235 -338
  51. package/esm/{CalmLensServerClient-DCSbwIBs.d.ts → CalmLensServerClient-BHx3x_nZ.d.ts} +107 -49
  52. package/esm/{CalmLensServerClient-DemxbNMn.js → CalmLensServerClient-dAQUcDWb.js} +274 -93
  53. package/esm/{CalmLensTypes-DpU-hXq2.d.ts → CalmLensTypes-CUB0YYVz.d.ts} +26601 -27354
  54. package/esm/{Classification-D3SkprrQ-CMnQKW13.d.ts → Classification-Q5zGpR8l-CEWjnE39.d.ts} +731 -607
  55. package/esm/Core-BxeIud_S.js +843 -0
  56. package/esm/Core-C82YmjjX.d.ts +823 -0
  57. package/esm/FileIcons-4qSX7DW2.d.ts +67 -0
  58. package/esm/{ModerationContextLimits-lLfmyLni.js → ModerationContextLimits-B6_RalCQ.js} +911 -261
  59. package/esm/{ReactUpload-huIMnOJ4.d.ts → ReactUpload-DiiXfKvj.d.ts} +1 -1
  60. package/esm/{ReactUpload-6klucehl.js → ReactUpload-DxwVqfX1.js} +1 -1
  61. package/esm/{TestTriggers-CMwMrbjy-bdowBBKw.js → TestTriggers-BTyXtX0Q-GRB9jQwo.js} +320 -36
  62. package/{cjs/TestTriggers-D-fwfhEP-hlaP1oW2.d.ts → esm/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts} +146 -8
  63. package/esm/{UploadController-UxP6gj7A.js → UploadController-D9Z-h00Q.js} +34 -14
  64. package/esm/{WebhookPayload-CQg8BBZQ.d.ts → WebhookPayload-BLT2y_Jy.d.ts} +93 -86
  65. package/esm/app.d.ts +6 -7
  66. package/esm/app.js +3 -3
  67. package/esm/elements.d.ts +123 -22
  68. package/esm/elements.js +497 -128
  69. package/esm/file-icons.d.ts +2 -67
  70. package/esm/index-CKRgjV16.d.ts +16 -0
  71. package/esm/index.d.ts +5 -6
  72. package/esm/index.js +1 -1
  73. package/esm/react-native.d.ts +52 -11
  74. package/esm/react-native.js +205 -75
  75. package/esm/react.d.ts +42 -9
  76. package/esm/react.js +327 -91
  77. package/esm/server.d.ts +48 -7
  78. package/esm/server.js +3 -3
  79. package/esm/styles.css +142 -22
  80. package/esm/svelte/AssetViewer.svelte +25 -0
  81. package/esm/svelte/CalmLensAsset.svelte +318 -0
  82. package/esm/svelte/CalmLensDocumentViewer.svelte +7 -0
  83. package/esm/svelte/CalmLensImageViewer.svelte +7 -0
  84. package/esm/svelte/CalmLensSpreadsheetViewer.svelte +7 -0
  85. package/esm/svelte/CalmLensTextViewer.svelte +7 -0
  86. package/esm/svelte/CalmLensWebsiteViewer.svelte +7 -0
  87. package/esm/svelte/index.d.ts +29 -6
  88. package/esm/svelte/index.js +7 -2
  89. package/esm/test-inputs.d.ts +2 -2
  90. package/esm/test-inputs.js +1 -1
  91. package/esm/testing.d.ts +29 -16
  92. package/esm/testing.js +1507 -393
  93. package/esm/ui-CTBUxnVp.d.ts +139 -0
  94. package/esm/ui-Cr7s6JHm.js +1258 -0
  95. package/esm/ui.d.ts +3 -2
  96. package/esm/ui.js +4 -3
  97. package/esm/vue.d.ts +802 -199
  98. package/esm/vue.js +308 -103
  99. package/package.json +3 -1
  100. package/cjs/ModerationContext-9lGm-Mna-CcmbRnOy.d.ts +0 -67
  101. package/cjs/index-BcDDQJF2.d.ts +0 -253
  102. package/cjs/ui-B23r8BvW.d.ts +0 -539
  103. package/cjs/ui-Dq-cm6Rx.js +0 -586
  104. package/esm/ModerationContext-9lGm-Mna-CcmbRnOy.d.ts +0 -67
  105. package/esm/index-BcDDQJF2.d.ts +0 -253
  106. package/esm/svelte/CalmLensMedia.svelte +0 -134
  107. package/esm/ui-B23r8BvW.d.ts +0 -539
  108. package/esm/ui-Bn29rfAi.js +0 -461
package/esm/testing.js CHANGED
@@ -1,10 +1,10 @@
1
- import { E as MAX_IMAGE_UPLOAD_BYTES, F as API_ERROR_CODES, I as API_ERROR_DEFINITIONS, M as SDK_ERROR_CODES, N as invalidArgument, O as getRejectedUploadMimeTypeError, P as invalidConfig, j as CalmLensError, k as isRejectedUploadMimeType, p as randomUuid, r as selectModerationContextItems, v as validateAppClientOptions, x as validateServerClientOptions } from "./ModerationContextLimits-lLfmyLni.js";
2
- import { a as WEBHOOK_TIMESTAMP_HEADER, l as signUploadTokenWithApiKey, n as WEBHOOK_DELIVERY_HEADER, r as WEBHOOK_SIGNATURE_HEADER, t as CalmLensServerClient, u as stringifyJsonCanonical } from "./CalmLensServerClient-DemxbNMn.js";
3
- import { g as validateAssetPayload, h as assetToData, i as MOCK_HOOKS, m as assetDataToUint8Array, p as sleep } from "./CalmLensOptionKeys-BKez0Wiw.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-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";
4
4
  import { t as hmacSha256Hex } from "./CryptoUtils-B_x8lMIx-DhuWGzqn.js";
5
- import { t as CalmLensAppClient } from "./CalmLensAppClient-BjlvBweS.js";
6
- import { a as placeholderHashToDataURL, r as isFileAccepted } from "./UploadController-UxP6gj7A.js";
7
- import { s as getTestInputTag, u as CLASSIFICATION_CATEGORIES } from "./TestTriggers-CMwMrbjy-bdowBBKw.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";
8
8
  import * as zod from "zod";
9
9
  // src/contract/MediaTestTriggers.js
10
10
  const MEDIA_TEST_SIGNALS = [...CLASSIFICATION_CATEGORIES, "violence.graphic"];
@@ -31,7 +31,7 @@ async function generateMediaTestCode(signal, testInputKey) {
31
31
  if (!MEDIA_TEST_SIGNALS.includes(signal)) throw new RangeError("Unsupported media test signal");
32
32
  return `Calm Lens test ${[...await getTestInputTag("media", signal, testInputKey)].map((character) => HEX_WORDS[Number.parseInt(character, 16)]).join(" ")} ${signal.replace(/[.-]/g, " ")} end test`;
33
33
  }
34
- // src/contract/Ids-D2XfVlL6.js
34
+ // src/contract/Ids-BESMSxGb.js
35
35
  var __defProp = Object.defineProperty;
36
36
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
37
37
  var __exportAll = (all, no_symbols) => {
@@ -7907,6 +7907,7 @@ const ID_PREFIXES = {
7907
7907
  member: "mem",
7908
7908
  invitation: "inv",
7909
7909
  transfer: "xfer",
7910
+ assetBatch: "batch",
7910
7911
  supportTicket: "tkt",
7911
7912
  supportTicketMessage: "msg",
7912
7913
  humanReview: "rev",
@@ -7968,6 +7969,7 @@ const EXAMPLE_IDS = {
7968
7969
  mem: "mem_9Xm4Rk7Lq2Vt8Wb3Np5C",
7969
7970
  inv: "inv_3Qk8Xm2Rt9Lv4Wb7Np6C",
7970
7971
  xfer: "xfer_6Lq2Xm8Rk4Vt9Wb3Np7C",
7972
+ batch: "batch_5Rt8Xm3Lq9Vk2Wb7Np4C",
7971
7973
  tkt: "tkt_6Xm2Rk9Lq4Vt7Wb3Np8C",
7972
7974
  msg: "msg_2Rk7Xm4Lq9Vt3Wb8Np5C",
7973
7975
  rev: "rev_8Xm3Rk2Lq7Vt9Wb4Np6C",
@@ -7985,7 +7987,7 @@ const EXAMPLE_IDS = {
7985
7987
  * across the packages that build records from plain strings).
7986
7988
  */
7987
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]] });
7988
- // src/contract/Permissions-C2KeOlab.js
7990
+ // src/contract/Permissions-BqpmE0Qa.js
7989
7991
  const ACTION_SCHEMA = zod.enum([
7990
7992
  "assets:read",
7991
7993
  "assets:download",
@@ -8106,6 +8108,8 @@ const MOCK_QUALIFIERS = {
8106
8108
  "sexual-non-consensual",
8107
8109
  "sexual-intimate-image-abuse",
8108
8110
  "sexual-extreme",
8111
+ "sexual-strangulation",
8112
+ "sexual-incest",
8109
8113
  "sexual-minors",
8110
8114
  "sexual-solicitation",
8111
8115
  "sexual-paid",
@@ -8317,7 +8321,7 @@ var MockDecision = class {
8317
8321
  }
8318
8322
  /**
8319
8323
  * The report a decided asset gets, as the API sends it: every category (unflagged ones
8320
- * evaluated with score 0), policy-adjusted results and the automated action and
8324
+ * evaluated with score 0), policy-adjusted results and the automated status and
8321
8325
  * `flaggedCategories`. `undefined` for `pending` and `failed`.
8322
8326
  */
8323
8327
  report() {
@@ -8350,10 +8354,16 @@ var MockDecision = class {
8350
8354
  }])),
8351
8355
  explanationComplete: true,
8352
8356
  source: "policy",
8353
- automatedAction: STATUS_ACTION[status],
8357
+ rule: null,
8358
+ automatedStatus: status,
8354
8359
  regions: [],
8360
+ linkSafety: null,
8361
+ timeline: null,
8355
8362
  flaggedCategories: evaluated.filter(([, score]) => action(score) !== "allow").map(([category]) => category),
8356
- raw: { categories }
8363
+ raw: {
8364
+ categories,
8365
+ hashMatches: []
8366
+ }
8357
8367
  };
8358
8368
  }
8359
8369
  };
@@ -8361,17 +8371,395 @@ var MockDecision = class {
8361
8371
  const mockDecision = (status) => new MockDecision(status);
8362
8372
  /** The default `moderate`: queued work stays pending until `completeProcessing`, which allows it. */
8363
8373
  const defaultModerate = ({ trigger, queued }) => queued && trigger !== "complete" ? "pending" : "allowed";
8374
+ // src/testing/MockAssetFilters.ts
8375
+ /** The asset fields a list filter may name, each with the operators it accepts. */
8376
+ const MOCK_ASSET_FILTER_FIELDS = {
8377
+ id: {
8378
+ kind: "text",
8379
+ nullable: false,
8380
+ operators: [
8381
+ "==",
8382
+ "!=",
8383
+ ">",
8384
+ ">=",
8385
+ "<",
8386
+ "<=",
8387
+ "=in=",
8388
+ "=out="
8389
+ ]
8390
+ },
8391
+ parentId: {
8392
+ kind: "text",
8393
+ nullable: true,
8394
+ operators: [
8395
+ "==",
8396
+ "!=",
8397
+ ">",
8398
+ ">=",
8399
+ "<",
8400
+ "<=",
8401
+ "=in=",
8402
+ "=out="
8403
+ ]
8404
+ },
8405
+ folderId: {
8406
+ kind: "text",
8407
+ nullable: true,
8408
+ operators: [
8409
+ "==",
8410
+ "!=",
8411
+ ">",
8412
+ ">=",
8413
+ "<",
8414
+ "<=",
8415
+ "=in=",
8416
+ "=out="
8417
+ ]
8418
+ },
8419
+ uploadPresetId: {
8420
+ kind: "text",
8421
+ nullable: true,
8422
+ operators: [
8423
+ "==",
8424
+ "!=",
8425
+ ">",
8426
+ ">=",
8427
+ "<",
8428
+ "<=",
8429
+ "=in=",
8430
+ "=out="
8431
+ ]
8432
+ },
8433
+ createdAt: {
8434
+ kind: "number",
8435
+ nullable: false,
8436
+ operators: [
8437
+ "==",
8438
+ "!=",
8439
+ ">",
8440
+ ">=",
8441
+ "<",
8442
+ "<=",
8443
+ "=in=",
8444
+ "=out="
8445
+ ]
8446
+ },
8447
+ updatedAt: {
8448
+ kind: "number",
8449
+ nullable: false,
8450
+ operators: [
8451
+ "==",
8452
+ "!=",
8453
+ ">",
8454
+ ">=",
8455
+ "<",
8456
+ "<=",
8457
+ "=in=",
8458
+ "=out="
8459
+ ]
8460
+ },
8461
+ type: {
8462
+ kind: "text",
8463
+ nullable: false,
8464
+ operators: [
8465
+ "==",
8466
+ "!=",
8467
+ ">",
8468
+ ">=",
8469
+ "<",
8470
+ "<=",
8471
+ "=in=",
8472
+ "=out="
8473
+ ]
8474
+ },
8475
+ name: {
8476
+ kind: "text",
8477
+ nullable: false,
8478
+ operators: [
8479
+ "==",
8480
+ "!=",
8481
+ ">",
8482
+ ">=",
8483
+ "<",
8484
+ "<=",
8485
+ "=in=",
8486
+ "=out="
8487
+ ]
8488
+ },
8489
+ description: {
8490
+ kind: "text",
8491
+ nullable: true,
8492
+ operators: [
8493
+ "==",
8494
+ "!=",
8495
+ ">",
8496
+ ">=",
8497
+ "<",
8498
+ "<=",
8499
+ "=in=",
8500
+ "=out="
8501
+ ]
8502
+ },
8503
+ externalId: {
8504
+ kind: "text",
8505
+ nullable: true,
8506
+ operators: [
8507
+ "==",
8508
+ "!=",
8509
+ ">",
8510
+ ">=",
8511
+ "<",
8512
+ "<=",
8513
+ "=in=",
8514
+ "=out="
8515
+ ]
8516
+ },
8517
+ externalUrl: {
8518
+ kind: "text",
8519
+ nullable: true,
8520
+ operators: [
8521
+ "==",
8522
+ "!=",
8523
+ ">",
8524
+ ">=",
8525
+ "<",
8526
+ "<=",
8527
+ "=in=",
8528
+ "=out="
8529
+ ]
8530
+ },
8531
+ authorId: {
8532
+ kind: "text",
8533
+ nullable: true,
8534
+ operators: [
8535
+ "==",
8536
+ "!=",
8537
+ ">",
8538
+ ">=",
8539
+ "<",
8540
+ "<=",
8541
+ "=in=",
8542
+ "=out="
8543
+ ]
8544
+ },
8545
+ tags: {
8546
+ kind: "list",
8547
+ nullable: false,
8548
+ operators: ["=in=", "=out="]
8549
+ },
8550
+ visibility: {
8551
+ kind: "text",
8552
+ nullable: true,
8553
+ operators: [
8554
+ "==",
8555
+ "!=",
8556
+ ">",
8557
+ ">=",
8558
+ "<",
8559
+ "<=",
8560
+ "=in=",
8561
+ "=out="
8562
+ ]
8563
+ },
8564
+ "upload.status": {
8565
+ kind: "text",
8566
+ nullable: false,
8567
+ operators: [
8568
+ "==",
8569
+ "!=",
8570
+ ">",
8571
+ ">=",
8572
+ "<",
8573
+ "<=",
8574
+ "=in=",
8575
+ "=out="
8576
+ ]
8577
+ },
8578
+ "upload.updatedAt": {
8579
+ kind: "number",
8580
+ nullable: true,
8581
+ operators: [
8582
+ "==",
8583
+ "!=",
8584
+ ">",
8585
+ ">=",
8586
+ "<",
8587
+ "<=",
8588
+ "=in=",
8589
+ "=out="
8590
+ ]
8591
+ },
8592
+ "classification.status": {
8593
+ kind: "text",
8594
+ nullable: false,
8595
+ operators: [
8596
+ "==",
8597
+ "!=",
8598
+ ">",
8599
+ ">=",
8600
+ "<",
8601
+ "<=",
8602
+ "=in=",
8603
+ "=out="
8604
+ ]
8605
+ },
8606
+ "classification.updatedAt": {
8607
+ kind: "number",
8608
+ nullable: true,
8609
+ operators: [
8610
+ "==",
8611
+ "!=",
8612
+ ">",
8613
+ ">=",
8614
+ "<",
8615
+ "<=",
8616
+ "=in=",
8617
+ "=out="
8618
+ ]
8619
+ },
8620
+ "classification.completedAt": {
8621
+ kind: "number",
8622
+ nullable: true,
8623
+ operators: [
8624
+ "==",
8625
+ "!=",
8626
+ ">",
8627
+ ">=",
8628
+ "<",
8629
+ "<=",
8630
+ "=in=",
8631
+ "=out="
8632
+ ]
8633
+ },
8634
+ "classification.moderation.status": {
8635
+ kind: "text",
8636
+ nullable: false,
8637
+ operators: [
8638
+ "==",
8639
+ "!=",
8640
+ ">",
8641
+ ">=",
8642
+ "<",
8643
+ "<=",
8644
+ "=in=",
8645
+ "=out="
8646
+ ]
8647
+ },
8648
+ "content.status": {
8649
+ kind: "text",
8650
+ nullable: false,
8651
+ operators: [
8652
+ "==",
8653
+ "!=",
8654
+ ">",
8655
+ ">=",
8656
+ "<",
8657
+ "<=",
8658
+ "=in=",
8659
+ "=out="
8660
+ ]
8661
+ },
8662
+ "content.removalReason": {
8663
+ kind: "text",
8664
+ nullable: true,
8665
+ operators: [
8666
+ "==",
8667
+ "!=",
8668
+ ">",
8669
+ ">=",
8670
+ "<",
8671
+ "<=",
8672
+ "=in=",
8673
+ "=out="
8674
+ ]
8675
+ },
8676
+ "content.updatedAt": {
8677
+ kind: "number",
8678
+ nullable: true,
8679
+ operators: [
8680
+ "==",
8681
+ "!=",
8682
+ ">",
8683
+ ">=",
8684
+ "<",
8685
+ "<=",
8686
+ "=in=",
8687
+ "=out="
8688
+ ]
8689
+ },
8690
+ "content.format": {
8691
+ kind: "text",
8692
+ nullable: true,
8693
+ operators: [
8694
+ "==",
8695
+ "!=",
8696
+ ">",
8697
+ ">=",
8698
+ "<",
8699
+ "<=",
8700
+ "=in=",
8701
+ "=out="
8702
+ ]
8703
+ },
8704
+ "content.extension": {
8705
+ kind: "text",
8706
+ nullable: true,
8707
+ operators: [
8708
+ "==",
8709
+ "!=",
8710
+ ">",
8711
+ ">=",
8712
+ "<",
8713
+ "<=",
8714
+ "=in=",
8715
+ "=out="
8716
+ ]
8717
+ },
8718
+ "content.sizeInBytes": {
8719
+ kind: "number",
8720
+ nullable: true,
8721
+ operators: [
8722
+ "==",
8723
+ "!=",
8724
+ ">",
8725
+ ">=",
8726
+ "<",
8727
+ "<=",
8728
+ "=in=",
8729
+ "=out="
8730
+ ]
8731
+ }
8732
+ };
8364
8733
  // src/testing/MockUtils.ts
8734
+ /**
8735
+ * A `sort` query value as the API parses it (`sortQueryField` in shared/Page.ts): comma-separated
8736
+ * fields from `fields`, descending when prefixed with `-`, none repeated and at most `max`.
8737
+ * Undefined for a list that sends none; `undefined`'s default applies.
8738
+ */
8739
+ const parseSort = (value, fields, max, fail) => {
8740
+ if (value === null) return void 0;
8741
+ const sort = [];
8742
+ for (const part of value.split(",").map((item) => item.trim())) {
8743
+ const field = part.startsWith("-") ? part.slice(1) : part;
8744
+ if (!/^-?[A-Za-z][A-Za-z0-9.]*$/.test(part) || !fields.includes(field)) throw fail();
8745
+ if (sort.some((rule) => rule.field === field)) throw fail();
8746
+ sort.push({
8747
+ field,
8748
+ direction: part.startsWith("-") ? "desc" : "asc"
8749
+ });
8750
+ }
8751
+ if (sort.length > max) throw fail();
8752
+ return sort;
8753
+ };
8365
8754
  const toBase64Utf8 = (value) => btoa(Array.from(new TextEncoder().encode(value), (byte) => String.fromCharCode(byte)).join(""));
8366
8755
  const fromBase64Utf8 = (value) => new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(atob(value), (char) => char.charCodeAt(0)));
8367
8756
  /**
8368
8757
  * One keyset page like the API's (packages/shared-backend/src/CursorPagination.ts): ordered by
8369
- * `ordering` (newest first by default) with an `id` tie-breaker added, starting after the
8370
- * cursor's values. The cursor is tied to `scope` (the filter, folder or parent) and the
8371
- * ordering, so it only continues the query it came from. `name` and `id` are compared by code
8372
- * point, like the database.
8758
+ * `sort` (newest first by default) with an `id` tie-breaker added, starting after the cursor's
8759
+ * values. The cursor is tied to `scope` (the filter, folder or parent) and the sort, so it only
8760
+ * continues the query it came from. `name` and `id` are compared by code point, like the database.
8373
8761
  */
8374
- const createPage = (items, query, { scope, fail, defaultPageSize = 50, defaultOrdering = [{
8762
+ const createPage = (items, query, { scope, fail, defaultPageSize = 50, defaultSort = [{
8375
8763
  field: "createdAt",
8376
8764
  direction: "desc"
8377
8765
  }] }) => {
@@ -8379,7 +8767,7 @@ const createPage = (items, query, { scope, fail, defaultPageSize = 50, defaultOr
8379
8767
  if (typeof pageSize !== "number" || !Number.isFinite(pageSize) || pageSize < 1) throw fail("validation/too-small", "pageSize");
8380
8768
  if (pageSize > 100) throw fail("validation/too-big", "pageSize");
8381
8769
  if (!Number.isInteger(pageSize)) throw invalidArgument("Invalid page size");
8382
- const ordering = query.ordering?.length ? [...query.ordering] : [...defaultOrdering];
8770
+ const ordering = query.sort?.length ? [...query.sort] : [...defaultSort];
8383
8771
  if (!ordering.some(({ field }) => field === "id")) ordering.push({
8384
8772
  field: "id",
8385
8773
  direction: ordering[0].direction
@@ -8393,7 +8781,7 @@ const createPage = (items, query, { scope, fail, defaultPageSize = 50, defaultOr
8393
8781
  values = parsed?.values;
8394
8782
  if (parsed?.scope !== signature || !Array.isArray(values) || values.length !== ordering.length || values.some((value, i) => STRING_FIELDS.has(ordering[i].field) ? typeof value !== "string" : typeof value !== "number" || !Number.isFinite(value))) throw new Error();
8395
8783
  } catch {
8396
- throw fail("validation/invalid-cursor");
8784
+ throw fail("cursor/invalid");
8397
8785
  }
8398
8786
  remaining = remaining.filter((item) => {
8399
8787
  for (const [i, rule] of ordering.entries()) {
@@ -8408,9 +8796,7 @@ const createPage = (items, query, { scope, fail, defaultPageSize = 50, defaultOr
8408
8796
  const last = pageItems.at(-1);
8409
8797
  return {
8410
8798
  items: pageItems,
8411
- pageSize,
8412
8799
  hasMore,
8413
- ordering,
8414
8800
  nextCursor: hasMore && last ? toBase64Utf8(JSON.stringify({
8415
8801
  scope: signature,
8416
8802
  values: ordering.map(({ field }) => last[field])
@@ -8426,7 +8812,7 @@ const compareValues = (left, right) => {
8426
8812
  const [a, b] = [String(left), String(right)];
8427
8813
  return a < b ? -1 : a > b ? 1 : 0;
8428
8814
  };
8429
- /** Sorts like the API's `ordering`; without one, newest first. */
8815
+ /** Sorts like the API's `sort`; without one, newest first. */
8430
8816
  const orderItems = (items, ordering) => {
8431
8817
  const rules = ordering?.length ? ordering : [{
8432
8818
  field: "createdAt",
@@ -8440,90 +8826,196 @@ const orderItems = (items, ordering) => {
8440
8826
  return 0;
8441
8827
  });
8442
8828
  };
8443
- const COMPARISON = /^([A-Za-z][\w.]*)(==|!=|=in=|=out=|>=|<=|=gt=|=ge=|=lt=|=le=|>|<)(.+)$/;
8444
- const parseFilterValue = (raw) => {
8445
- const value = raw.trim();
8446
- if (/^".*"$/.test(value) || /^'.*'$/.test(value)) return value.slice(1, -1);
8447
- if (value === "null") return null;
8448
- if (value === "true") return true;
8449
- if (value === "false") return false;
8450
- if (value !== "" && !Number.isNaN(Number(value))) return Number(value);
8451
- return value;
8829
+ /** Thrown for a filter the API refuses with `filter/invalid`. */
8830
+ var MockInvalidFilter = class extends Error {};
8831
+ /** The characters that end an unquoted word, as in @rsql/parser. */
8832
+ const RESERVED = "\"'();,=!~<> \n \r";
8833
+ const LOGIC_WORDS = ["and", "or"];
8834
+ /** Splits a filter into tokens like @rsql/parser's lexer. */
8835
+ const tokenize = (filter) => {
8836
+ const tokens = [];
8837
+ let i = 0;
8838
+ while (i < filter.length) {
8839
+ const char = filter[i];
8840
+ if (" \n \r".includes(char)) i++;
8841
+ else if (char === "\"" || char === "'") {
8842
+ let text = "";
8843
+ let j = i + 1;
8844
+ for (; j < filter.length && filter[j] !== char; j++) {
8845
+ if (filter[j] === "\\" && j + 1 < filter.length) j++;
8846
+ text += filter[j];
8847
+ }
8848
+ if (j >= filter.length) throw new MockInvalidFilter();
8849
+ tokens.push({
8850
+ kind: "quoted",
8851
+ text
8852
+ });
8853
+ i = j + 1;
8854
+ } else if (char === "(" || char === ")") {
8855
+ tokens.push({
8856
+ kind: "paren",
8857
+ text: char
8858
+ });
8859
+ i++;
8860
+ } else if (char === ";" || char === ",") {
8861
+ tokens.push({
8862
+ kind: "logic",
8863
+ text: char === ";" ? "and" : "or"
8864
+ });
8865
+ i++;
8866
+ } else if ("=!~<>".includes(char)) {
8867
+ const operator = /^(==|!=|<=|>=|<|>|=[a-z]*=)/.exec(filter.slice(i))?.[0];
8868
+ if (!operator) throw new MockInvalidFilter();
8869
+ tokens.push({
8870
+ kind: "operator",
8871
+ text: operator
8872
+ });
8873
+ i += operator.length;
8874
+ } else {
8875
+ const word = LOGIC_WORDS.find((logic) => filter.startsWith(`${logic} `, i));
8876
+ if (word) {
8877
+ tokens.push({
8878
+ kind: "logic",
8879
+ text: word
8880
+ });
8881
+ i += word.length;
8882
+ continue;
8883
+ }
8884
+ let j = i + 1;
8885
+ while (j < filter.length && !RESERVED.includes(filter[j])) j++;
8886
+ tokens.push({
8887
+ kind: "word",
8888
+ text: filter.slice(i, j)
8889
+ });
8890
+ i = j;
8891
+ }
8892
+ }
8893
+ return tokens;
8894
+ };
8895
+ /**
8896
+ * A field's value as the API reads it (zodbase/rsql): `null` is a missing value only on a
8897
+ * nullable field, and a number field's value must be a finite number.
8898
+ */
8899
+ const readFilterValue = (field, text) => {
8900
+ const { kind, nullable } = MOCK_ASSET_FILTER_FIELDS[field];
8901
+ if (text === "null" && nullable) return null;
8902
+ if (kind !== "number") return text;
8903
+ const number = Number(text);
8904
+ if (text === "" || !Number.isFinite(number)) throw new MockInvalidFilter();
8905
+ return number;
8906
+ };
8907
+ /** Parses a filter: `;` (and) binds tighter than `,` (or), and parentheses group. */
8908
+ const parseFilter = (filter) => {
8909
+ const tokens = tokenize(filter);
8910
+ let position = 0;
8911
+ const peek = () => tokens[position];
8912
+ const next = () => {
8913
+ const token = tokens[position++];
8914
+ if (!token) throw new MockInvalidFilter();
8915
+ return token;
8916
+ };
8917
+ const value = () => {
8918
+ const token = next();
8919
+ if (token.kind !== "word" && token.kind !== "quoted") throw new MockInvalidFilter();
8920
+ return token.text;
8921
+ };
8922
+ const term = () => {
8923
+ const token = next();
8924
+ if (token.kind === "paren" && token.text === "(") {
8925
+ const node = alternatives();
8926
+ if (next().text !== ")") throw new MockInvalidFilter();
8927
+ return node;
8928
+ }
8929
+ if (token.kind !== "word" || !Object.hasOwn(MOCK_ASSET_FILTER_FIELDS, token.text)) throw new MockInvalidFilter();
8930
+ const field = token.text;
8931
+ const operator = next();
8932
+ if (operator.kind !== "operator" || !MOCK_ASSET_FILTER_FIELDS[field].operators.includes(operator.text)) throw new MockInvalidFilter();
8933
+ let texts;
8934
+ if (peek()?.kind === "paren" && peek()?.text === "(") {
8935
+ next();
8936
+ texts = [value()];
8937
+ while (peek()?.kind === "logic" && peek()?.text === "or") {
8938
+ next();
8939
+ texts.push(value());
8940
+ }
8941
+ if (next().text !== ")") throw new MockInvalidFilter();
8942
+ } else texts = [value()];
8943
+ if (texts.length > 1 && operator.text !== "=in=" && operator.text !== "=out=") throw new MockInvalidFilter();
8944
+ return {
8945
+ type: "comparison",
8946
+ field,
8947
+ operator: operator.text,
8948
+ values: texts.map((text) => readFilterValue(field, text))
8949
+ };
8950
+ };
8951
+ const conjunction = () => {
8952
+ const nodes = [term()];
8953
+ while (peek()?.kind === "logic" && peek()?.text === "and") {
8954
+ next();
8955
+ nodes.push(term());
8956
+ }
8957
+ return nodes.length === 1 ? nodes[0] : {
8958
+ type: "and",
8959
+ nodes
8960
+ };
8961
+ };
8962
+ const alternatives = () => {
8963
+ const nodes = [conjunction()];
8964
+ while (peek()?.kind === "logic" && peek()?.text === "or") {
8965
+ next();
8966
+ nodes.push(conjunction());
8967
+ }
8968
+ return nodes.length === 1 ? nodes[0] : {
8969
+ type: "or",
8970
+ nodes
8971
+ };
8972
+ };
8973
+ const node = alternatives();
8974
+ if (position !== tokens.length) throw new MockInvalidFilter();
8975
+ return node;
8452
8976
  };
8453
8977
  const readField = (item, path) => path.split(".").reduce((value, key) => value && typeof value === "object" ? value[key] : void 0, item);
8454
- const unsupportedFilter = (expression) => invalidArgument(`MockCalmLensServerClient cannot evaluate the filter "${expression}". It supports ==, !=, <, <=, >, >=, =in= and =out=, joined by ; (and) or , (or) and grouped with parentheses.`);
8455
- const matchesComparison = (item, comparison) => {
8456
- const match = COMPARISON.exec(comparison.trim());
8457
- if (!match) throw unsupportedFilter(comparison);
8458
- const [, field, operator, rawValue] = match;
8459
- const actual = readField(item, field);
8460
- const isList = operator === "=in=" || operator === "=out=";
8461
- if (isList && !/^\(.*\)$/.test(rawValue.trim())) throw unsupportedFilter(comparison);
8462
- const values = isList ? rawValue.trim().slice(1, -1).split(",").map(parseFilterValue) : [parseFilterValue(rawValue)];
8463
- const equals = (expected) => Array.isArray(actual) ? actual.includes(expected) : expected === null ? actual === null || actual === void 0 : actual === expected;
8978
+ /** `*` matches any run of characters, regardless of case; every other character itself. */
8979
+ const wildcard = (pattern) => new RegExp(`^${pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "isu");
8980
+ /** Compares like SQL: a missing value never matches, except `== null`. */
8981
+ const matchesComparison = (item, { field, operator, values }) => {
8982
+ const actual = readField(item, field) ?? null;
8983
+ const [value] = values;
8984
+ if (actual === null && MOCK_ASSET_FILTER_FIELDS[field].kind === "list") return operator === "=out=";
8985
+ if (actual === null) return operator === "==" && value === null;
8986
+ if (operator === "!=" && value === null) return true;
8987
+ const actuals = Array.isArray(actual) ? actual : [actual];
8988
+ const equals = (expected) => actuals.some((each) => each === expected);
8989
+ if ((operator === "==" || operator === "!=") && typeof value === "string" && value.includes("*")) {
8990
+ const pattern = wildcard(value);
8991
+ const matched = actuals.some((each) => typeof each === "string" && pattern.test(each));
8992
+ return operator === "==" ? matched : !matched;
8993
+ }
8464
8994
  switch (operator) {
8465
- case "==": return equals(values[0]);
8466
- case "!=": return !equals(values[0]);
8995
+ case "==": return equals(value);
8996
+ case "!=": return !equals(value);
8467
8997
  case "=in=": return values.some(equals);
8468
- case "=out=": return !values.some(equals);
8469
- case ">":
8470
- case "=gt=": return compareValues(actual, values[0]) > 0;
8471
- case ">=":
8472
- case "=ge=": return compareValues(actual, values[0]) >= 0;
8473
- case "<":
8474
- case "=lt=": return compareValues(actual, values[0]) < 0;
8475
- default: return compareValues(actual, values[0]) <= 0;
8476
- }
8477
- };
8478
- /** Splits on `separator` outside quotes and parentheses. */
8479
- const splitTopLevel = (text, separator) => {
8480
- const parts = [];
8481
- let depth = 0;
8482
- let quote = null;
8483
- let current = "";
8484
- for (const char of text) {
8485
- if (quote) {
8486
- if (char === quote) quote = null;
8487
- } else if (char === "\"" || char === "'") quote = char;
8488
- else if (char === "(") depth++;
8489
- else if (char === ")") depth--;
8490
- else if (char === separator && depth === 0) {
8491
- parts.push(current);
8492
- current = "";
8493
- continue;
8494
- }
8495
- current += char;
8496
- }
8497
- parts.push(current);
8498
- return parts;
8499
- };
8500
- /** The expression inside `( … )` when the parentheses enclose all of `text`, else undefined. */
8501
- const unwrapGroup = (text) => {
8502
- if (!text.startsWith("(") || !text.endsWith(")")) return void 0;
8503
- let depth = 0;
8504
- let quote = null;
8505
- for (const [index, char] of [...text].entries()) if (quote) {
8506
- if (char === quote) quote = null;
8507
- } else if (char === "\"" || char === "'") quote = char;
8508
- else if (char === "(") depth++;
8509
- else if (char === ")" && --depth === 0) return index === text.length - 1 ? text.slice(1, -1) : void 0;
8510
- };
8511
- /** Evaluates `,` (or) of `;` (and) terms, where a term is a comparison or a `( … )` group. */
8512
- const matchesExpression = (item, expression) => splitTopLevel(expression, ",").some((alternative) => splitTopLevel(alternative, ";").every((term) => {
8513
- const trimmed = term.trim();
8514
- if (!trimmed) throw unsupportedFilter(expression);
8515
- const group = unwrapGroup(trimmed);
8516
- return group === void 0 ? matchesComparison(item, trimmed) : matchesExpression(item, group);
8517
- }));
8998
+ case "=out=": return !values.includes(null) && !values.some(equals);
8999
+ }
9000
+ if (value === null) return false;
9001
+ const order = compareValues(actual, value);
9002
+ switch (operator) {
9003
+ case ">": return order > 0;
9004
+ case ">=": return order >= 0;
9005
+ case "<": return order < 0;
9006
+ default: return order <= 0;
9007
+ }
9008
+ };
9009
+ const matchesNode = (item, node) => node.type === "comparison" ? matchesComparison(item, node) : node.type === "and" ? node.nodes.every((child) => matchesNode(item, child)) : node.nodes.some((child) => matchesNode(item, child));
8518
9010
  /**
8519
- * Applies an RSQL `filter` like the API: comparisons joined by `;` (and), which binds tighter
8520
- * than `,` (or), and grouped with parentheses. Anything it can't evaluate throws instead of
8521
- * returning wrong results.
9011
+ * Applies an RSQL `filter` like the API (zodbase/rsql with MOCK_ASSET_FILTER_FIELDS): only the
9012
+ * listed fields, each with its own operators, `;` (and) binding tighter than `,` (or), and parentheses. Throws
9013
+ * `MockInvalidFilter` for any filter the API refuses with `filter/invalid`.
8522
9014
  */
8523
9015
  const filterAssets = (items, filter) => {
8524
9016
  if (!filter) return items;
8525
- if (items.length === 0) matchesExpression({}, filter);
8526
- return items.filter((item) => matchesExpression(item, filter));
9017
+ const node = parseFilter(filter);
9018
+ return items.filter((item) => matchesNode(item, node));
8527
9019
  };
8528
9020
  const MAX_SEARCH_TOKENS = 8;
8529
9021
  /** The keyword fields the API searches, in the order it reports matches. */
@@ -8584,15 +9076,100 @@ const REVIEW_DECISIONS = [
8584
9076
  "blocked",
8585
9077
  "purged"
8586
9078
  ];
9079
+ /**
9080
+ * A client method, named like its path on the client. A request is recorded under the first
9081
+ * method that sends it; `callsTo` and `failNextRequest` also match the others (see
9082
+ * `MockCalmLensCall`).
9083
+ */
9084
+ const MOCK_OPERATIONS = [
9085
+ "assets.list",
9086
+ "assets.iterate",
9087
+ "assets.search",
9088
+ "assets.retrieve",
9089
+ "assets.waitForDecision",
9090
+ "assets.update",
9091
+ "assets.listChildren",
9092
+ "assets.iterateChildren",
9093
+ "assets.listTimeline",
9094
+ "assets.iterateTimeline",
9095
+ "assets.create",
9096
+ "assets.classify",
9097
+ "assets.uploadPart",
9098
+ "assets.move",
9099
+ "assets.retry",
9100
+ "assets.explain",
9101
+ "assets.decide",
9102
+ "assets.removeContent",
9103
+ "assets.delete",
9104
+ "assets.batch",
9105
+ "text.classify",
9106
+ "cdn.serve",
9107
+ "cdn.getAssetInfo",
9108
+ "cdn.signAssetUrl",
9109
+ "events.list",
9110
+ "events.pages",
9111
+ "folders.list",
9112
+ "folders.iterate",
9113
+ "folders.retrieve",
9114
+ "folders.create",
9115
+ "folders.update",
9116
+ "folders.delete",
9117
+ "folders.move",
9118
+ "hashLists.list",
9119
+ "hashLists.iterate",
9120
+ "hashLists.retrieve",
9121
+ "hashLists.create",
9122
+ "hashLists.update",
9123
+ "hashLists.delete",
9124
+ "hashLists.listEntries",
9125
+ "hashLists.iterateEntries",
9126
+ "hashLists.addEntry",
9127
+ "hashLists.removeEntry",
9128
+ "policies.list",
9129
+ "policies.iterate",
9130
+ "policies.retrieve",
9131
+ "policies.create",
9132
+ "policies.update",
9133
+ "policies.reset",
9134
+ "policies.upgrade",
9135
+ "policies.setAutomaticUpdates",
9136
+ "policies.delete",
9137
+ "policies.retrieveAssigned",
9138
+ "policies.assign",
9139
+ "lenses.list",
9140
+ "lenses.iterate",
9141
+ "lenses.create",
9142
+ "lenses.retrieve",
9143
+ "lenses.update",
9144
+ "lenses.delete",
9145
+ "ensureLens",
9146
+ "ensureLenses"
9147
+ ];
8587
9148
  const MAX_PAGE_SIZE = 100;
8588
9149
  const MAX_DECISION_NOTE_LENGTH = 1499;
8589
9150
  /** How the API names a reviewer acting through an unnamed API key. */
8590
9151
  const API_KEY_REVIEWER_NAME = "An API key";
8591
- const MAX_SEARCH_LIMIT = 20;
9152
+ /** The actor of events the mock's API key causes: mock keys have no ID. */
9153
+ const MOCK_API_KEY_ACTOR = {
9154
+ type: "api-key",
9155
+ id: null
9156
+ };
9157
+ /** The actor of a reviewer's decision through the `decide` test hook. */
9158
+ const MOCK_REVIEWER_ACTOR = {
9159
+ type: "user",
9160
+ id: null
9161
+ };
9162
+ const AUTOMATED_ACTOR = {
9163
+ type: "automated",
9164
+ id: null
9165
+ };
9166
+ /** An event type's shape (`resource.action`), as the mock checks `types` without the catalog. */
9167
+ const EVENT_TYPE_PATTERN = /^[a-z][a-z-]*\.[a-z][a-z-]*$/;
9168
+ const MAX_SEARCH_PAGE_SIZE = 20;
8592
9169
  const MAX_SEARCH_QUERY_LENGTH = 200;
8593
9170
  /**
8594
- * The ThumbHash the mock gives every classified image, standing in for one computed from its
8595
- * pixels. The `placeholder` resource serves it as a PNG, like the CDN.
9171
+ * The ThumbHash the mock gives every processed asset's preview, standing in for one computed from
9172
+ * its pixels. The `placeholder` resource serves it as a PNG, like the CDN.
8596
9173
  */
8597
9174
  const MOCK_THUMBHASH = "1QcSHQRnh493V4dIh4eXh1h4kJUI";
8598
9175
  /** Like the API: 1 to 255 printable ASCII characters, once HTTP has trimmed the header value. */
@@ -8616,10 +9193,19 @@ const toEventAsset = (asset) => ({
8616
9193
  upload: { status: asset.upload.status },
8617
9194
  classification: {
8618
9195
  status: asset.classification.status,
9196
+ testInput: asset.classification.testInput,
8619
9197
  moderation: { status: asset.classification.moderation.status }
8620
9198
  },
8621
9199
  content: { status: asset.content.status }
8622
9200
  });
9201
+ /** The moderation status each `asset.<status>` event announces. */
9202
+ const ANNOUNCED_STATUS = {
9203
+ "asset.allowed": "allowed",
9204
+ "asset.limited": "limited",
9205
+ "asset.age-restricted": "age-restricted",
9206
+ "asset.blocked": "blocked",
9207
+ "asset.purged": "purged"
9208
+ };
8623
9209
  /** A `moderate` answer or `completeProcessing` decision as a checked `MockDecision`. */
8624
9210
  const toDecision = (value) => {
8625
9211
  if (value instanceof MockDecision) return value;
@@ -8632,12 +9218,116 @@ const assetNameFact = (asset) => ({
8632
9218
  value: asset.name,
8633
9219
  url: `https://calmlens.com/go/asset/${asset.id}`
8634
9220
  });
8635
- /** Removing content removes the placeholder and average colour with it. */
8636
- const withoutPlaceholder = (image) => image ? {
8637
- ...image,
8638
- thumbhash: null,
8639
- averageColor: null
8640
- } : image;
9221
+ /** The page the mock serves at `/embed`, standing in for the CDN's embed page. */
9222
+ const MOCK_EMBED_HTML = "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>Embed</title></head><body></body></html>";
9223
+ /** A ThumbHash as the PNG the placeholder resource serves. */
9224
+ const mockPlaceholderPng = (thumbhash) => Uint8Array.from(atob(placeholderHashToDataURL(thumbhash).split(",", 2)[1]), (char) => char.charCodeAt(0));
9225
+ /** Removing or withholding content removes its rendered file and preview, as the API does. */
9226
+ const NO_RENDERING = {
9227
+ rendered: null,
9228
+ preview: null,
9229
+ hls: null
9230
+ };
9231
+ /** The size of the waveform the API makes as an audio asset's preview. */
9232
+ const WAVEFORM_SIZE = {
9233
+ width: 1200,
9234
+ height: 300
9235
+ };
9236
+ /** Audio and video formats browsers play as uploaded, so the API serves them as stored (Asset.ts). */
9237
+ const BROWSER_SAFE_MEDIA_FORMATS = [
9238
+ "video/mp4",
9239
+ "audio/mpeg",
9240
+ "audio/aac",
9241
+ "audio/mp4",
9242
+ "audio/x-m4a",
9243
+ "audio/ogg"
9244
+ ];
9245
+ /** Spreadsheets, which have no rendered file or preview (Asset.ts). */
9246
+ const SPREADSHEET_MIME_TYPES = [
9247
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
9248
+ "application/vnd.ms-excel.sheet.macroenabled.12",
9249
+ "application/vnd.ms-excel",
9250
+ "application/vnd.oasis.opendocument.spreadsheet"
9251
+ ];
9252
+ /** Whether browsers play an audio or video upload's format as it is, so it is served as stored. */
9253
+ const isBrowserSafeMediaFormat = (format) => BROWSER_SAFE_MEDIA_FORMATS.includes(normalizeUploadMimeType(format ?? ""));
9254
+ /**
9255
+ * The rendered file and preview the API reports for an asset with its content held (Asset.ts,
9256
+ * getAssetRendered and getAssetPreview). Once uploaded, an image renders as itself with a preview
9257
+ * that has no ThumbHash yet, and a PDF and browser-safe audio and video render as uploaded. Once
9258
+ * processed, a website renders as its screenshot; a document or presentation as a PDF, with its
9259
+ * first page as the preview; video and audio as a browser-safe file (MP4 or M4A unless browsers
9260
+ * play the upload), audio with a waveform preview and video with no poster; and every preview has
9261
+ * its ThumbHash. Text, spreadsheets and other files have neither. The mock decodes nothing, so
9262
+ * sizes are unknown, audio has no peaks, and audio and video never get an HLS stream.
9263
+ */
9264
+ const mockRendering = (asset, processed) => {
9265
+ const format = asset.content.format;
9266
+ const mimeType = normalizeUploadMimeType(format ?? "");
9267
+ const browserSafe = isBrowserSafeMediaFormat(format);
9268
+ const preview = (size) => ({
9269
+ ...size,
9270
+ thumbhash: processed ? MOCK_THUMBHASH : null,
9271
+ averageColor: processed ? "#7f7f7f" : null
9272
+ });
9273
+ const unsized = {
9274
+ width: null,
9275
+ height: null
9276
+ };
9277
+ const rendersOnUpload = asset.type === "image" || mimeType === "application/pdf" || (asset.type === "video" || asset.type === "audio") && browserSafe;
9278
+ if (!processed && !rendersOnUpload) return NO_RENDERING;
9279
+ switch (asset.type) {
9280
+ case "image": return {
9281
+ rendered: {
9282
+ kind: "image",
9283
+ format: format ?? "image/png",
9284
+ ...unsized
9285
+ },
9286
+ preview: preview(unsized),
9287
+ hls: null
9288
+ };
9289
+ case "website": return {
9290
+ rendered: {
9291
+ kind: "image",
9292
+ format: "image/png",
9293
+ ...unsized
9294
+ },
9295
+ preview: preview(unsized),
9296
+ hls: null
9297
+ };
9298
+ case "multimedia-document":
9299
+ if (SPREADSHEET_MIME_TYPES.includes(mimeType)) return NO_RENDERING;
9300
+ return {
9301
+ rendered: {
9302
+ kind: "pdf",
9303
+ format: "application/pdf",
9304
+ ...unsized
9305
+ },
9306
+ preview: processed ? preview(unsized) : null,
9307
+ hls: null
9308
+ };
9309
+ case "video": return {
9310
+ rendered: {
9311
+ kind: "video",
9312
+ format: browserSafe ? format : "video/mp4",
9313
+ ...unsized
9314
+ },
9315
+ preview: null,
9316
+ hls: null
9317
+ };
9318
+ case "audio": return {
9319
+ rendered: {
9320
+ kind: "audio",
9321
+ format: browserSafe ? format : "audio/mp4",
9322
+ ...unsized,
9323
+ ...processed && { peaks: [] }
9324
+ },
9325
+ preview: processed ? preview(WAVEFORM_SIZE) : null,
9326
+ hls: null
9327
+ };
9328
+ default: return NO_RENDERING;
9329
+ }
9330
+ };
8641
9331
  /** An asset's type from its content type, or `website` for a URL. */
8642
9332
  const inferAssetType = (contentType) => {
8643
9333
  if (contentType === void 0) return "website";
@@ -8659,8 +9349,52 @@ var ApiFailure = class {
8659
9349
  }
8660
9350
  };
8661
9351
  const fail = (code, { message, details } = {}) => new ApiFailure(API_ERROR_DEFINITIONS[code].status, code, message ?? API_ERROR_DEFINITIONS[code].message, details);
8662
- /** A request the API's schema refuses: `validation/<zod issue>` with HTTP 400 and the field. */
8663
- const invalidField = (code, path) => new ApiFailure(400, code, `Invalid ${path}`, { path });
9352
+ /**
9353
+ * A request the API's schema refuses: `validation/invalid-request` with HTTP 400, listing the field
9354
+ * and its issue code (such as `validation/too-big`) in `details.issues`.
9355
+ */
9356
+ /**
9357
+ * The mock's grant, the asset segment of a URL `signAssetUrl` signs: `sig_` and the hex of
9358
+ * `{assetId}.{1|0}.{expiresAt}`, its asset, original access and expiry. Every SDK's mock writes it
9359
+ * the same way. It is readable, not signed, as the mock has no secret to keep.
9360
+ */
9361
+ const encodeMockGrant = (grant) => `sig_${[...new TextEncoder().encode(`${grant.assetId}.${grant.original ? 1 : 0}.${grant.expiresAt}`)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
9362
+ /** Reads a mock grant, or `undefined` for a segment the mock didn't sign. */
9363
+ const decodeMockGrant = (segment) => {
9364
+ const hex = segment.slice(4);
9365
+ if (!/^(?:[0-9a-f]{2})+$/.test(hex)) return void 0;
9366
+ let text;
9367
+ try {
9368
+ text = new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(hex.match(/../g), (pair) => Number.parseInt(pair, 16)));
9369
+ } catch {
9370
+ return;
9371
+ }
9372
+ const match = /^(.+)\.([01])\.(\d+)$/s.exec(text);
9373
+ if (!match) return void 0;
9374
+ return {
9375
+ assetId: match[1],
9376
+ original: match[2] === "1",
9377
+ expiresAt: Number(match[3])
9378
+ };
9379
+ };
9380
+ const invalidField = (code, path) => new ApiFailure(400, API_ERROR_CODES.INVALID_REQUEST, `Invalid ${path}`, { issues: [{
9381
+ path,
9382
+ message: `Invalid ${path}`,
9383
+ code
9384
+ }] });
9385
+ /**
9386
+ * Refuses `metadata` the API's schema refuses (METADATA_ITEM_SCHEMA): it is `null` or a list of
9387
+ * `{ id, value }` objects with a string `id` and any JSON `value`.
9388
+ */
9389
+ const checkMetadata = (metadata) => {
9390
+ if (metadata === void 0 || metadata === null) return;
9391
+ if (!Array.isArray(metadata)) throw invalidField("validation/invalid-type", "metadata");
9392
+ metadata.forEach((item, index) => {
9393
+ if (typeof item !== "object" || item === null || Array.isArray(item)) throw invalidField("validation/invalid-type", `metadata.${index}`);
9394
+ if (typeof item.id !== "string") throw invalidField("validation/invalid-type", `metadata.${index}.id`);
9395
+ if (item.value === void 0) throw invalidField("validation/invalid-value", `metadata.${index}.value`);
9396
+ });
9397
+ };
8664
9398
  /** The built-in presets the mock knows, by display name. */
8665
9399
  const MOCK_PRESET_NAMES = {
8666
9400
  "general-community": "General",
@@ -8668,35 +9402,65 @@ const MOCK_PRESET_NAMES = {
8668
9402
  "education-support": "Learning and support",
8669
9403
  "wholesome-community": "Teen-safe"
8670
9404
  };
9405
+ /**
9406
+ * The settings of the mock's presets: every category with its default action (`allow` for
9407
+ * personal information and profanity, `block` otherwise) and no rules. The mock holds no built-in
9408
+ * preset settings, and uploads are never decided by a policy.
9409
+ */
9410
+ const mockPresetSettings = () => ({ categorySettings: Object.fromEntries(CLASSIFICATION_CATEGORIES.map((category) => [category, {
9411
+ action: category === "personal-information" || category === "profanity" ? "allow" : "block",
9412
+ allowances: [],
9413
+ restrictions: []
9414
+ }])) });
9415
+ /**
9416
+ * Refuses settings the API refuses (MODERATION_POLICY_SETTINGS_SCHEMA): every category, each with
9417
+ * an `action` and its `allowances` and `restrictions` lists.
9418
+ */
9419
+ const checkPolicySettings = (settings) => {
9420
+ const categories = settings?.categorySettings;
9421
+ if (!categories || typeof categories !== "object") throw invalidField("validation/invalid-type", "settings.categorySettings");
9422
+ for (const category of CLASSIFICATION_CATEGORIES) {
9423
+ const value = categories[category];
9424
+ if (!value || typeof value !== "object") throw invalidField("validation/invalid-type", `settings.categorySettings.${category}`);
9425
+ for (const key of ["allowances", "restrictions"]) if (!Array.isArray(value[key])) throw invalidField("validation/invalid-type", `settings.categorySettings.${category}.${key}`);
9426
+ if (typeof value.action !== "string") throw invalidField("validation/invalid-value", `settings.categorySettings.${category}.action`);
9427
+ }
9428
+ for (const key of Object.keys(categories)) if (!CLASSIFICATION_CATEGORIES.includes(key)) throw invalidField("validation/unknown-field", `settings.categorySettings.${key}`);
9429
+ };
8671
9430
  /** The client methods that send a request, the one it is recorded under first. */
8672
9431
  const operationsOf = (request) => {
8673
9432
  const { method, segments, query, cdn } = request;
8674
- if (cdn) return ["cdn.serve"];
9433
+ if (cdn) return segments[3] === "info" ? ["cdn.getAssetInfo"] : ["cdn.serve"];
8675
9434
  const [root] = segments;
8676
9435
  if (root === "projects") {
8677
9436
  switch (segments.slice(2).join("/")) {
8678
9437
  case "events": return ["events.list", "events.pages"];
8679
- case "lenses": return ["ensureLenses", "ensureLens"];
8680
- case "folders": return method === "GET" ? ["folders.list"] : ["folders.create"];
8681
- case "hash-lists": return method === "GET" ? ["hashLists.list"] : ["hashLists.create"];
8682
- case "policies": return method === "GET" ? ["policies.list"] : ["policies.create"];
8683
- case "policy": return ["policies.assign"];
9438
+ case "lenses": return method === "GET" ? ["lenses.list", "lenses.iterate"] : method === "POST" ? ["lenses.create"] : ["ensureLenses", "ensureLens"];
9439
+ case "folders": return method === "GET" ? ["folders.list", "folders.iterate"] : ["folders.create"];
9440
+ case "hash-lists": return method === "GET" ? ["hashLists.list", "hashLists.iterate"] : ["hashLists.create"];
9441
+ case "policy": return method === "GET" ? ["policies.retrieveAssigned"] : ["policies.assign"];
8684
9442
  case "assets/search": return ["assets.search"];
8685
9443
  case "assets/batch": return ["assets.batch"];
9444
+ case "signed-asset-urls": return ["cdn.signAssetUrl"];
8686
9445
  case "assets":
8687
9446
  if (method === "GET") return ["assets.list", "assets.iterate"];
8688
- if (query.get("queue") === "true") return ["assets.create"];
9447
+ if (query.get("wait") === "false") return ["assets.create"];
8689
9448
  return isTextUpload(request) ? ["assets.classify", "text.classify"] : ["assets.classify"];
8690
9449
  }
8691
- if (segments[2] === "policies" && segments[3] !== void 0) {
8692
- if (segments[4] === "preset") return ["policies.applyPreset"];
8693
- if (segments[4] === "automatic-updates") return ["policies.setAutomaticUpdates"];
8694
- return method === "GET" ? ["policies.retrieve"] : method === "PATCH" ? ["policies.update"] : ["policies.delete"];
8695
- }
9450
+ if (segments[2] === "assets" && segments[4] === "timeline" && segments.length === 5) return ["assets.listTimeline", "assets.iterateTimeline"];
8696
9451
  return [];
8697
9452
  }
9453
+ if (root === "policies") {
9454
+ const [, policyId, policyAction] = segments;
9455
+ if (policyId === void 0) return method === "GET" ? ["policies.list", "policies.iterate"] : ["policies.create"];
9456
+ if (policyAction === "reset") return ["policies.reset"];
9457
+ if (policyAction === "upgrade") return ["policies.upgrade"];
9458
+ if (policyAction === "automatic-updates") return ["policies.setAutomaticUpdates"];
9459
+ return method === "GET" ? ["policies.retrieve"] : method === "PATCH" ? ["policies.update"] : ["policies.delete"];
9460
+ }
9461
+ if (root === "lenses" && segments[1] !== void 0) return method === "GET" ? ["lenses.retrieve"] : method === "PATCH" ? ["lenses.update"] : ["lenses.delete"];
8698
9462
  if (root === "upload-presets") {
8699
- if (segments[3] === void 0) return [query.get("queue") === "true" ? "assets.create" : "assets.classify"];
9463
+ if (segments[3] === void 0) return [query.get("wait") === "false" ? "assets.create" : "assets.classify"];
8700
9464
  return segments[4] === "part" ? ["assets.uploadPart"] : ["assets.retrieve"];
8701
9465
  }
8702
9466
  const id = segments[1];
@@ -8706,16 +9470,15 @@ const operationsOf = (request) => {
8706
9470
  return method === "GET" ? ["folders.retrieve"] : method === "PATCH" ? ["folders.update"] : ["folders.delete"];
8707
9471
  }
8708
9472
  if (root === "hash-lists" && id !== void 0) {
8709
- if (action === "entries") return method === "GET" ? ["hashLists.listEntries"] : ["hashLists.addEntry"];
9473
+ if (action === "entries") return method === "GET" ? ["hashLists.listEntries", "hashLists.iterateEntries"] : ["hashLists.addEntry"];
8710
9474
  return method === "GET" ? ["hashLists.retrieve"] : method === "PATCH" ? ["hashLists.update"] : ["hashLists.delete"];
8711
9475
  }
8712
9476
  if (root === "hash-list-entries" && id !== void 0) return ["hashLists.removeEntry"];
8713
9477
  if (root !== "assets" || id === void 0) return [];
8714
9478
  switch (action) {
8715
9479
  case void 0: return method === "GET" ? ["assets.retrieve", "assets.waitForDecision"] : method === "PATCH" ? ["assets.update"] : ["assets.delete"];
8716
- case "content": return ["assets.deleteContent"];
9480
+ case "content": return ["assets.removeContent"];
8717
9481
  case "children": return ["assets.listChildren", "assets.iterateChildren"];
8718
- case "signed-url": return ["assets.createSignedUrl"];
8719
9482
  case "part": return ["assets.uploadPart"];
8720
9483
  case "move": return ["assets.move"];
8721
9484
  case "retry": return ["assets.retry"];
@@ -8753,8 +9516,12 @@ const createMonotonicClock = () => {
8753
9516
  var MockCalmLensApi = class {
8754
9517
  constructor(options) {
8755
9518
  this.calls = [];
9519
+ this.cdnBaseUrl = "";
8756
9520
  this.lenses = /* @__PURE__ */ new Map();
8757
9521
  this.eventFeed = [];
9522
+ this.assetEventSequences = /* @__PURE__ */ new Map();
9523
+ this.processingOptions = /* @__PURE__ */ new Map();
9524
+ this.pendingReruns = /* @__PURE__ */ new Set();
8758
9525
  this.openUploads = /* @__PURE__ */ new Map();
8759
9526
  this.idempotentResults = /* @__PURE__ */ new Map();
8760
9527
  this.pendingFailures = [];
@@ -8763,7 +9530,7 @@ var MockCalmLensApi = class {
8763
9530
  this.policies = /* @__PURE__ */ new Map();
8764
9531
  this.hashLists = /* @__PURE__ */ new Map();
8765
9532
  this.hashListEntries = /* @__PURE__ */ new Map();
8766
- this.pageFailure = (code, path) => code === "validation/invalid-cursor" ? fail(API_ERROR_CODES.INVALID_CURSOR) : invalidField(code, path ?? "pageSize");
9533
+ this.pageFailure = (code, path) => code === "cursor/invalid" ? fail(API_ERROR_CODES.INVALID_CURSOR) : invalidField(code, path ?? "pageSize");
8767
9534
  this.options = options;
8768
9535
  this.projectId = options.projectId;
8769
9536
  this.apiKey = options.apiKey;
@@ -8775,6 +9542,8 @@ var MockCalmLensApi = class {
8775
9542
  }
8776
9543
  /** Queues a failure for the next request, or the next one `operation` sends. */
8777
9544
  failNextRequest(failure, options = {}) {
9545
+ if (options.operation !== void 0 && !MOCK_OPERATIONS.includes(options.operation)) throw invalidArgument(`${options.operation} is not a client method that sends requests`);
9546
+ if (!(typeof failure === "string" && failure in API_ERROR_DEFINITIONS) && (options.details !== void 0 || options.retryAfter !== void 0)) throw invalidArgument("details and retryAfter apply only to an API error code");
8778
9547
  if (options.retryAfter !== void 0 && !(Number.isInteger(options.retryAfter) && options.retryAfter >= 0)) throw invalidArgument("retryAfter must be a whole number of seconds");
8779
9548
  this.pendingFailures.push({
8780
9549
  failure,
@@ -8791,10 +9560,14 @@ var MockCalmLensApi = class {
8791
9560
  */
8792
9561
  async enqueueEvent(input) {
8793
9562
  const asset = input.asset === void 0 && input.assetId ? await this.databaseStorage.getAsset(input.assetId) : void 0;
8794
- return this.pushEvent(asset ? {
9563
+ if (!asset) return this.pushEvent(input);
9564
+ const snapshot = toEventAsset(asset);
9565
+ const announced = ANNOUNCED_STATUS[input.type];
9566
+ if (announced) snapshot.classification.moderation.status = announced;
9567
+ return this.pushEvent({
8795
9568
  ...input,
8796
- asset: toEventAsset(asset)
8797
- } : input);
9569
+ asset: snapshot
9570
+ });
8798
9571
  }
8799
9572
  /** Adds an event to the feed, filling the fields the API always sets. */
8800
9573
  pushEvent(input) {
@@ -8807,10 +9580,14 @@ var MockCalmLensApi = class {
8807
9580
  description: null,
8808
9581
  assetId: null,
8809
9582
  asset: null,
9583
+ actor: MOCK_API_KEY_ACTOR,
8810
9584
  facts: [],
8811
9585
  createdAt: now,
8812
9586
  ...input
8813
9587
  };
9588
+ const sequence = event.assetId ? (this.assetEventSequences.get(event.assetId) ?? 0) + 1 : null;
9589
+ if (event.assetId && sequence !== null) this.assetEventSequences.set(event.assetId, sequence);
9590
+ event.assetSequence = sequence;
8814
9591
  this.eventFeed.push(event);
8815
9592
  return event;
8816
9593
  }
@@ -8837,15 +9614,17 @@ var MockCalmLensApi = class {
8837
9614
  } catch (failure) {
8838
9615
  throw this.toError(failure);
8839
9616
  }
8840
- if (asset.classification.status !== "processing") throw invalidArgument(`asset ${assetId} isn't processing`);
9617
+ const rerun = this.pendingReruns.has(asset.id);
9618
+ if (!rerun && asset.classification.status !== "processing") throw invalidArgument(`asset ${assetId} isn't processing`);
8841
9619
  const settled = decision === void 0 ? void 0 : toDecision(decision);
8842
- return structuredClone(await this.moderateStored(asset, "complete", settled));
9620
+ if (!rerun) return structuredClone(await this.moderateStored(asset, "complete", settled));
9621
+ return structuredClone(await this.settleRerun(asset, settled ?? await this.decisionFor(asset, "complete", true)));
8843
9622
  }
8844
9623
  /**
8845
9624
  * `POST /assets/:assetId/decision`, like the API: an asset still uploading or processing can't
8846
9625
  * be decided, one pending moderation can only be blocked or purged, a decision must change the
8847
- * status and purged content can only be blocked. Mock API keys have no name, so the reviewer is
8848
- * "An API key".
9626
+ * status and purged content can only be blocked. The review is the API key's, and mock API keys
9627
+ * have no ID or name, so its ID is `null` and the event names the reviewer "An API key".
8849
9628
  */
8850
9629
  async decideAsset(assetId, body) {
8851
9630
  const { decision, note: rawNote } = body;
@@ -8862,43 +9641,38 @@ var MockCalmLensApi = class {
8862
9641
  if (decision !== "purged" && decision !== "blocked" && status === "pending") throw fail(API_ERROR_CODES.ASSET_DECISION_NOT_ALLOWED);
8863
9642
  if (status === decision) throw fail(API_ERROR_CODES.ASSET_DECISION_UNCHANGED);
8864
9643
  if (decision !== "purged" && decision !== "blocked" && status === "purged") throw fail(API_ERROR_CODES.ASSET_CONTENT_PURGED);
8865
- return this.recordDecision(asset, decision, {
8866
- note,
8867
- reviewerName: API_KEY_REVIEWER_NAME
8868
- });
9644
+ return this.recordDecision(asset, decision, { note });
8869
9645
  }
8870
9646
  /**
8871
9647
  * Sets the reviewer's decision: the moderation status, a manual review and the
8872
- * `asset.<status>` event (after `asset.content-removed` when purging). The test hook records no
8873
- * reviewer or note; the API's handler records both.
9648
+ * `asset.<status>` event (after `asset.content-removed` when purging). Either way the review is
9649
+ * the mock API key's; the test hook records no note, the API's handler records it.
8874
9650
  */
8875
9651
  async recordDecision(asset, decision, review) {
9652
+ this.pendingReruns.delete(asset.id);
8876
9653
  const decided = await this.applyOutcome(asset, decision, "requested");
8877
9654
  const now = this.now();
8878
9655
  decided.classification.moderation.manualReviews = [...decided.classification.moderation.manualReviews ?? [], {
8879
9656
  id: this.createId("rev"),
8880
9657
  decision,
8881
9658
  note: review?.note ?? null,
8882
- ...review && {
8883
- reviewerName: review.reviewerName,
8884
- reviewerEmail: null
9659
+ decidedBy: {
9660
+ type: "api-key",
9661
+ id: null
8885
9662
  },
8886
9663
  reviewedAt: now,
8887
- appliedToAsset: true
9664
+ applied: true
8888
9665
  }];
8889
9666
  const stored = await this.databaseStorage.updateAsset(decided);
8890
- if (decision === "purged") this.recordLifecycleEvent("asset.content-removed", stored);
9667
+ if (decision === "purged") this.recordLifecycleEvent("asset.content-removed", stored, { actor: review ? MOCK_API_KEY_ACTOR : MOCK_REVIEWER_ACTOR });
8891
9668
  this.pushEvent({
8892
9669
  type: `asset.${decision}`,
8893
9670
  severity: decision === "allowed" || decision === "limited" ? "low" : "high",
8894
9671
  title: `asset.${decision}`,
8895
9672
  assetId: stored.id,
8896
9673
  asset: toEventAsset(stored),
9674
+ actor: review ? MOCK_API_KEY_ACTOR : MOCK_REVIEWER_ACTOR,
8897
9675
  facts: [
8898
- {
8899
- key: "decided-by",
8900
- value: "reviewer"
8901
- },
8902
9676
  {
8903
9677
  key: "asset-type",
8904
9678
  value: stored.type
@@ -8909,11 +9683,8 @@ var MockCalmLensApi = class {
8909
9683
  url: `https://calmlens.com/go/asset/${stored.id}`
8910
9684
  },
8911
9685
  ...review ? [{
8912
- key: "reviewer-user-id",
8913
- value: null
8914
- }, {
8915
9686
  key: "reviewer-name",
8916
- value: review.reviewerName
9687
+ value: API_KEY_REVIEWER_NAME
8917
9688
  }] : [],
8918
9689
  {
8919
9690
  key: "note",
@@ -8941,6 +9712,7 @@ var MockCalmLensApi = class {
8941
9712
  async handle(input, init, endpoints, session) {
8942
9713
  if (init?.signal?.aborted) throw init.signal.reason;
8943
9714
  const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
9715
+ this.cdnBaseUrl = endpoints.cdnBaseUrl;
8944
9716
  const cdn = url.startsWith(`${endpoints.cdnBaseUrl}/`);
8945
9717
  const base = cdn ? endpoints.cdnBaseUrl : endpoints.baseUrl;
8946
9718
  if (!url.startsWith(`${base}/`)) throw new TypeError(`MockCalmLensServerClient does not serve ${url}`);
@@ -8953,6 +9725,7 @@ var MockCalmLensApi = class {
8953
9725
  method: (init?.method ?? "GET").toUpperCase(),
8954
9726
  url,
8955
9727
  segments: path.split("/").filter(Boolean).map(decodeSegment),
9728
+ rawSegments: path.split("/").filter(Boolean),
8956
9729
  query: new URLSearchParams(queryIndex === -1 ? "" : relative.slice(queryIndex + 1)),
8957
9730
  headers,
8958
9731
  bytes,
@@ -9089,25 +9862,39 @@ var MockCalmLensApi = class {
9089
9862
  case "GET assets": return [200, await this.listAssets(request.query)];
9090
9863
  case "GET assets/search": return [200, await this.searchAssets(request.query)];
9091
9864
  case "POST assets/batch": return [202, await this.batch(this.json(request))];
9865
+ case "POST signed-asset-urls": return [200, await this.signAssetUrl(this.json(request))];
9092
9866
  case "GET events": return [200, this.listEvents(request.query)];
9093
9867
  case "GET folders": return [200, await this.listFolders(request.query)];
9094
9868
  case "POST folders": return [201, await this.createFolder(this.json(request))];
9095
9869
  case "GET hash-lists": return [200, this.listHashLists(request.query)];
9096
9870
  case "POST hash-lists": return [201, this.createHashList(this.json(request))];
9097
9871
  case "PUT lenses": return [200, this.ensureLenses(this.json(request))];
9098
- case "GET policies": return [200, this.listPolicies()];
9099
- case "POST policies": return [201, this.createPolicy(this.json(request))];
9872
+ case "GET lenses": return [200, this.listLenses(request.query)];
9873
+ case "POST lenses": return [201, this.createLens(this.json(request))];
9874
+ case "GET policy": return [200, this.toPolicy(this.findPolicy(this.ensurePolicies()))];
9100
9875
  case "PUT policy": return [200, this.assignPolicy(this.json(request))];
9101
9876
  }
9102
- const [, , collection, policyId, policyAction, ...more] = segments;
9103
- if (collection === "policies" && policyId !== void 0 && more.length === 0) switch (`${method} ${policyAction ?? ""}`) {
9104
- case "GET ": return [200, this.toPolicy(this.findPolicy(policyId))];
9105
- case "PATCH ": return [200, this.updatePolicy(policyId, this.json(request))];
9106
- case "DELETE ": return [200, this.deletePolicy(policyId)];
9107
- case "POST preset": return [200, this.applyPolicyPreset(policyId, this.json(request))];
9108
- case "PUT automatic-updates": return [200, this.setPolicyAutomaticUpdates(policyId, this.json(request))];
9877
+ const [, , collection, itemId, itemAction, ...more] = segments;
9878
+ if (collection === "assets" && itemId !== void 0 && itemAction === "timeline" && more.length === 0 && method === "GET") return [200, await this.listTimeline(itemId, request.query)];
9879
+ }
9880
+ if (root === "policies" && rest.length === 0) {
9881
+ if (id === void 0) {
9882
+ if (method === "GET") return [200, this.listPolicies(request.query)];
9883
+ if (method === "POST") return [201, this.createPolicy(this.json(request))];
9884
+ } else switch (`${method} ${action ?? ""}`) {
9885
+ case "GET ": return [200, this.toPolicy(this.findPolicy(id))];
9886
+ case "PATCH ": return [200, this.updatePolicy(id, this.json(request))];
9887
+ case "DELETE ": return [200, this.deletePolicy(id)];
9888
+ case "POST reset": return [200, this.restorePolicy(id, "reset", this.json(request))];
9889
+ case "POST upgrade": return [200, this.restorePolicy(id, "upgrade", this.json(request))];
9890
+ case "PUT automatic-updates": return [200, this.setPolicyAutomaticUpdates(id, this.json(request))];
9109
9891
  }
9110
9892
  }
9893
+ if (root === "lenses" && id !== void 0 && action === void 0) switch (method) {
9894
+ case "GET": return [200, this.findLens(id)];
9895
+ case "PATCH": return [200, this.updateLens(id, this.json(request))];
9896
+ case "DELETE": return [200, this.deleteLens(id)];
9897
+ }
9111
9898
  if (root === "upload-presets" && id !== void 0 && action === "assets") return [200, await this.presetRoute(request, id, rest, session)];
9112
9899
  if (root === "assets" && id !== void 0 && rest.length === 0) switch (`${method} ${action ?? ""}`) {
9113
9900
  case "GET ": return [200, await this.findOwnAsset(id)];
@@ -9115,7 +9902,6 @@ var MockCalmLensApi = class {
9115
9902
  case "DELETE ": return [200, await this.deleteAsset(id)];
9116
9903
  case "GET children": return [200, await this.listChildren(id, request.query)];
9117
9904
  case "POST part": return [200, await this.uploadPart(id, request)];
9118
- case "POST signed-url": return [200, await this.createSignedUrl(id, this.json(request))];
9119
9905
  case "POST move": return [200, await this.moveAsset(id, this.json(request))];
9120
9906
  case "POST retry": return [200, await this.retryAsset(id)];
9121
9907
  case "POST explain": return [200, await this.explainAsset(id, this.json(request))];
@@ -9141,21 +9927,23 @@ var MockCalmLensApi = class {
9141
9927
  }
9142
9928
  throw fail(API_ERROR_CODES.ROUTE_NOT_FOUND, { message: `No route for ${method} /${segments.join("/")}` });
9143
9929
  }
9930
+ /** The project's policy, after creating the organisation's own General policy on first use. */
9144
9931
  ensurePolicies() {
9145
- if (this.projectPolicyId) return;
9932
+ if (this.projectPolicyId) return this.projectPolicyId;
9146
9933
  const now = this.now();
9147
9934
  const general = this.newPolicy({
9148
9935
  name: MOCK_PRESET_NAMES["general-community"],
9149
- settings: { categorySettings: {} },
9150
- automaticUpdates: true,
9936
+ settings: mockPresetSettings(),
9937
+ followsPreset: true,
9151
9938
  preset: {
9152
9939
  id: "general-community",
9153
9940
  version: 1,
9154
- projectId: this.projectId
9941
+ own: true
9155
9942
  },
9156
9943
  createdAt: now
9157
9944
  });
9158
9945
  this.projectPolicyId = general.id;
9946
+ return general.id;
9159
9947
  }
9160
9948
  newPolicy(values) {
9161
9949
  const policy = {
@@ -9164,7 +9952,7 @@ var MockCalmLensApi = class {
9164
9952
  description: values.description ?? "",
9165
9953
  settings: values.settings,
9166
9954
  revision: 1,
9167
- automaticUpdates: values.automaticUpdates ?? false,
9955
+ followsPreset: values.followsPreset ?? false,
9168
9956
  preset: values.preset ?? null,
9169
9957
  baseline: structuredClone(values.settings),
9170
9958
  createdAt: values.createdAt,
@@ -9174,12 +9962,14 @@ var MockCalmLensApi = class {
9174
9962
  return policy;
9175
9963
  }
9176
9964
  toPolicy(policy) {
9177
- const { baseline: _baseline, preset, ...rest } = policy;
9965
+ const { baseline: _baseline, preset, followsPreset, ...rest } = policy;
9178
9966
  return {
9179
9967
  ...structuredClone(rest),
9180
9968
  preset: preset && {
9181
- ...preset,
9182
- latestVersion: 1
9969
+ id: preset.id,
9970
+ version: preset.version,
9971
+ latestVersion: 1,
9972
+ mode: preset.own ? followsPreset ? "live" : "pinned" : "copy"
9183
9973
  },
9184
9974
  projectIds: policy.id === this.projectPolicyId ? [this.projectId] : []
9185
9975
  };
@@ -9190,26 +9980,32 @@ var MockCalmLensApi = class {
9190
9980
  if (!policy) throw fail(API_ERROR_CODES.POLICY_NOT_FOUND);
9191
9981
  return policy;
9192
9982
  }
9193
- listPolicies() {
9983
+ /** A page of the organisation's policies, oldest first unless `sort` says otherwise. */
9984
+ listPolicies(query) {
9194
9985
  this.ensurePolicies();
9195
- return {
9196
- policies: [...this.policies.values()].map((policy) => this.toPolicy(policy)),
9197
- projectPolicyId: this.projectPolicyId
9198
- };
9986
+ return createPage([...this.policies.values()].map((policy) => this.toPolicy(policy)), this.pageQuery(query), {
9987
+ scope: `policies:${this.projectId}`,
9988
+ fail: this.pageFailure,
9989
+ defaultSort: [{
9990
+ field: "createdAt",
9991
+ direction: "asc"
9992
+ }]
9993
+ });
9199
9994
  }
9200
9995
  createPolicy(body) {
9201
9996
  this.ensurePolicies();
9202
9997
  const { name, description, settings, presetId } = body;
9203
9998
  const preset = typeof presetId === "string" ? presetId : void 0;
9204
9999
  if (settings === void 0 === (preset === void 0) || preset !== void 0 && !(preset in MOCK_PRESET_NAMES) || preset === void 0 && (typeof name !== "string" || !name.trim())) throw fail(API_ERROR_CODES.INVALID_VALUE, { message: "Send settings with a name, or presetId" });
10000
+ if (!preset) checkPolicySettings(settings);
9205
10001
  const policy = this.newPolicy({
9206
10002
  name: typeof name === "string" && name.trim() ? name.trim() : MOCK_PRESET_NAMES[preset],
9207
10003
  ...typeof description === "string" ? { description } : {},
9208
- settings: preset ? { categorySettings: {} } : settings,
10004
+ settings: preset ? mockPresetSettings() : settings,
9209
10005
  ...preset ? { preset: {
9210
10006
  id: preset,
9211
10007
  version: 1,
9212
- projectId: null
10008
+ own: false
9213
10009
  } } : {},
9214
10010
  createdAt: this.now()
9215
10011
  });
@@ -9229,28 +10025,30 @@ var MockCalmLensApi = class {
9229
10025
  }
9230
10026
  updatePolicy(policyId, body) {
9231
10027
  const policy = this.findPolicy(policyId);
10028
+ if (body.settings !== void 0) checkPolicySettings(body.settings);
9232
10029
  return this.savePolicy(policy, body.revision, {
9233
10030
  ...typeof body.name === "string" ? { name: body.name.trim() } : {},
9234
10031
  ...typeof body.description === "string" ? { description: body.description } : {},
9235
10032
  ...body.settings !== void 0 ? { settings: body.settings } : {},
9236
- automaticUpdates: false
10033
+ followsPreset: false
9237
10034
  });
9238
10035
  }
9239
- applyPolicyPreset(policyId, body) {
10036
+ /** Resets a `pinned` or `copy` policy to its preset release, or upgrades it to the latest. */
10037
+ restorePolicy(policyId, operation, body) {
9240
10038
  const policy = this.findPolicy(policyId);
9241
- if (!policy.preset || policy.automaticUpdates) throw fail(API_ERROR_CODES.POLICY_NO_PRESET);
10039
+ if (!policy.preset || policy.followsPreset) throw fail(API_ERROR_CODES.POLICY_NO_PRESET);
9242
10040
  if (body.presetVersion !== policy.preset.version) throw fail(API_ERROR_CODES.POLICY_PRESET_VERSION_CONFLICT);
9243
- if (body.operation === "update") throw fail(API_ERROR_CODES.POLICY_PRESET_UPDATE_UNAVAILABLE);
10041
+ if (operation === "upgrade") throw fail(API_ERROR_CODES.POLICY_PRESET_UPDATE_UNAVAILABLE);
9244
10042
  return this.savePolicy(policy, body.revision, { settings: structuredClone(policy.baseline) });
9245
10043
  }
9246
10044
  setPolicyAutomaticUpdates(policyId, body) {
9247
10045
  const policy = this.findPolicy(policyId);
9248
10046
  const enabled = body.enabled === true;
9249
- if (policy.preset?.projectId !== this.projectId || policy.automaticUpdates === enabled) throw fail(API_ERROR_CODES.POLICY_AUTOMATIC_UPDATES_UNAVAILABLE);
10047
+ if (!policy.preset?.own || policy.followsPreset === enabled) throw fail(API_ERROR_CODES.POLICY_AUTOMATIC_UPDATES_UNAVAILABLE);
9250
10048
  if (body.revision !== policy.revision) throw fail(API_ERROR_CODES.POLICY_REVISION_CONFLICT);
9251
10049
  if (body.presetVersion !== 1) throw fail(API_ERROR_CODES.POLICY_PRESET_VERSION_CONFLICT);
9252
10050
  return this.savePolicy(policy, body.revision, {
9253
- automaticUpdates: enabled,
10051
+ followsPreset: enabled,
9254
10052
  ...enabled ? {
9255
10053
  name: MOCK_PRESET_NAMES[policy.preset.id],
9256
10054
  description: "",
@@ -9315,26 +10113,10 @@ var MockCalmLensApi = class {
9315
10113
  }
9316
10114
  listHashListEntries(hashListId, query) {
9317
10115
  this.findHashList(hashListId);
9318
- const pageSize = this.integer(query, "pageSize", 50);
9319
- const entries = [...this.hashListEntries.values()].filter((entry) => entry.hashListId === hashListId).reverse();
9320
- const cursor = query.get("cursor");
9321
- const start = cursor ? Number(atob(cursor)) : 0;
9322
- if (!Number.isInteger(start) || start < 0) throw fail(API_ERROR_CODES.INVALID_CURSOR);
9323
- const items = entries.slice(start, start + pageSize);
9324
- const hasMore = start + pageSize < entries.length;
9325
- return {
9326
- items,
9327
- hasMore,
9328
- nextCursor: hasMore ? btoa(String(start + pageSize)) : null,
9329
- pageSize,
9330
- ordering: [{
9331
- field: "createdAt",
9332
- direction: "desc"
9333
- }, {
9334
- field: "id",
9335
- direction: "desc"
9336
- }]
9337
- };
10116
+ return createPage([...this.hashListEntries.values()].filter((entry) => entry.hashListId === hashListId), this.pageQuery(query), {
10117
+ scope: `hash-list-entries:${hashListId}`,
10118
+ fail: this.pageFailure
10119
+ });
9338
10120
  }
9339
10121
  async addHashListEntry(hashListId, body) {
9340
10122
  const list = this.findHashList(hashListId);
@@ -9343,10 +10125,10 @@ var MockCalmLensApi = class {
9343
10125
  const assetId = typeof body.assetId === "string" ? body.assetId : void 0;
9344
10126
  if (hash === void 0 === (assetId === void 0)) throw fail(API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Send either hash or assetId" });
9345
10127
  if (assetId) {
9346
- const image = (await this.findOwnAsset(assetId)).content.image;
9347
- if (!image?.perceptualHash) throw fail(API_ERROR_CODES.HASH_LIST_ASSET_NOT_HASHED);
9348
- hash = image.perceptualHash;
9349
- quality = image.perceptualHashQuality ?? null;
10128
+ const { content } = await this.findOwnAsset(assetId);
10129
+ if (!content.perceptualHash) throw fail(API_ERROR_CODES.HASH_LIST_ASSET_NOT_HASHED);
10130
+ hash = content.perceptualHash;
10131
+ quality = content.perceptualHashQuality ?? null;
9350
10132
  }
9351
10133
  if (!/^[0-9a-f]{64}$/.test(hash)) throw fail(API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Use a PDQ hash of 64 hexadecimal characters" });
9352
10134
  const existing = [...this.hashListEntries.values()].find((entry) => entry.hashListId === list.id && entry.hash === hash);
@@ -9358,7 +10140,7 @@ var MockCalmLensApi = class {
9358
10140
  hash,
9359
10141
  quality,
9360
10142
  label: typeof body.label === "string" ? body.label : null,
9361
- sourceAssetId: assetId ?? null,
10143
+ assetId: assetId ?? null,
9362
10144
  createdAt: this.now()
9363
10145
  };
9364
10146
  this.hashListEntries.set(entry.id, entry);
@@ -9371,7 +10153,7 @@ var MockCalmLensApi = class {
9371
10153
  const body = JSON.parse(new TextDecoder().decode(request.bytes));
9372
10154
  return body && typeof body === "object" ? body : {};
9373
10155
  } catch {
9374
- throw new ApiFailure(400, "validation/invalid-json", "Invalid JSON body");
10156
+ throw invalidField("validation/invalid-type", "");
9375
10157
  }
9376
10158
  }
9377
10159
  /** A whole number from the query, or `fallback` when absent; other values fail like zod. */
@@ -9383,26 +10165,22 @@ var MockCalmLensApi = class {
9383
10165
  if (!Number.isInteger(value)) throw invalidField("validation/invalid-type", name);
9384
10166
  return value;
9385
10167
  }
9386
- /** `ordering[i][field]` and `ordering[i][direction]` pairs, as qs parses them. */
9387
- ordering(query) {
9388
- const ordering = [];
9389
- for (const [key, value] of query) {
9390
- const match = /^ordering\[(\d+)\]\[(field|direction)\]$/.exec(key);
9391
- if (!match) continue;
9392
- const index = Number(match[1]);
9393
- ordering[index] = {
9394
- ...ordering[index],
9395
- [match[2]]: value
9396
- };
9397
- }
9398
- return ordering.filter(Boolean);
10168
+ /** The list's `sort`, from `fields`, as the API's `sortQueryField` reads it. */
10169
+ sort(query, fields, max) {
10170
+ return parseSort(query.get("sort"), fields, max, () => invalidField("validation/invalid-value", "sort"));
9399
10171
  }
10172
+ /**
10173
+ * A cursor list's query, checked like CURSOR_PAGE_QUERY_SCHEMA before anything else: `pageSize`
10174
+ * from 1 to 100, and a `sort` of at most two fields from `createdAt` and `id`.
10175
+ */
9400
10176
  pageQuery(query) {
9401
- const ordering = this.ordering(query);
10177
+ const pageSize = this.integer(query, "pageSize", 50);
10178
+ if (pageSize < 1) throw invalidField("validation/too-small", "pageSize");
10179
+ if (pageSize > 100) throw invalidField("validation/too-big", "pageSize");
9402
10180
  return {
9403
- pageSize: this.integer(query, "pageSize", 50),
10181
+ pageSize,
9404
10182
  cursor: query.get("cursor") ?? void 0,
9405
- ordering: ordering.length ? ordering : void 0
10183
+ sort: this.sort(query, ["createdAt", "id"], 2)
9406
10184
  };
9407
10185
  }
9408
10186
  async findOwnAsset(assetId) {
@@ -9412,16 +10190,16 @@ var MockCalmLensApi = class {
9412
10190
  }
9413
10191
  async listAssets(query) {
9414
10192
  let assets = await this.databaseStorage.listAssets(this.projectId);
9415
- const folderId = query.get("folderId");
9416
- if (folderId !== null) assets = assets.filter((asset) => (asset.folderId ?? null) === folderId);
10193
+ const page = this.pageQuery(query);
9417
10194
  const filter = query.get("filter") ?? void 0;
9418
- assets = filterAssets(assets, filter);
9419
- return createPage(assets, this.pageQuery(query), {
9420
- scope: JSON.stringify([
9421
- this.projectId,
9422
- filter ?? null,
9423
- folderId
9424
- ]),
10195
+ try {
10196
+ assets = filterAssets(assets, filter);
10197
+ } catch (error) {
10198
+ if (error instanceof MockInvalidFilter) throw fail(API_ERROR_CODES.INVALID_FILTER);
10199
+ throw error;
10200
+ }
10201
+ return createPage(assets, page, {
10202
+ scope: JSON.stringify([this.projectId, filter ?? null]),
9425
10203
  fail: this.pageFailure
9426
10204
  });
9427
10205
  }
@@ -9434,12 +10212,12 @@ var MockCalmLensApi = class {
9434
10212
  const query = (params.get("query") ?? "").trim();
9435
10213
  if (!query) throw invalidField("validation/too-small", "query");
9436
10214
  if (query.length > MAX_SEARCH_QUERY_LENGTH) throw invalidField("validation/too-big", "query");
9437
- const limit = this.integer(params, "limit", 10);
9438
- if (limit < 1) throw invalidField("validation/too-small", "limit");
9439
- if (limit > MAX_SEARCH_LIMIT) throw invalidField("validation/too-big", "limit");
10215
+ const pageSize = this.integer(params, "pageSize", 10);
10216
+ if (pageSize < 1) throw invalidField("validation/too-small", "pageSize");
10217
+ if (pageSize > MAX_SEARCH_PAGE_SIZE) throw invalidField("validation/too-big", "pageSize");
9440
10218
  return {
9441
10219
  query,
9442
- items: searchAssets(await this.databaseStorage.listAssets(this.projectId), query, limit),
10220
+ items: searchAssets(await this.databaseStorage.listAssets(this.projectId), query, pageSize),
9443
10221
  semanticStatus: "disabled"
9444
10222
  };
9445
10223
  }
@@ -9451,7 +10229,27 @@ var MockCalmLensApi = class {
9451
10229
  fail: this.pageFailure
9452
10230
  });
9453
10231
  }
10232
+ /**
10233
+ * An asset's findings timeline, as the API lists it (publicGetAssetTimeline.ts): refused while a
10234
+ * safety hold is on. The mock analyses no audio or video, so it keeps no segments: every
10235
+ * timeline is empty, and no cursor continues one.
10236
+ */
10237
+ async listTimeline(assetId, query) {
10238
+ const asset = await this.findOwnAsset(assetId);
10239
+ const pageSize = this.integer(query, "pageSize", 50);
10240
+ if (pageSize < 1) throw invalidField("validation/too-small", "pageSize");
10241
+ if (pageSize > 100) throw invalidField("validation/too-big", "pageSize");
10242
+ if (asset.content.safetyHold) throw fail(API_ERROR_CODES.ASSET_HELD, { details: { hold: "safety" } });
10243
+ if (query.get("cursor") !== null) throw fail(API_ERROR_CODES.INVALID_CURSOR);
10244
+ return {
10245
+ items: [],
10246
+ nextCursor: null,
10247
+ hasMore: false
10248
+ };
10249
+ }
9454
10250
  async updateAsset(assetId, body) {
10251
+ checkMetadata(body.metadata);
10252
+ if (body.name === null) throw invalidField("validation/invalid-type", "name");
9455
10253
  const asset = await this.findOwnAsset(assetId);
9456
10254
  if (body.externalId) {
9457
10255
  if ((await this.databaseStorage.listAssets(this.projectId)).some((other) => other.id !== asset.id && other.externalId === body.externalId)) throw fail(API_ERROR_CODES.DUPLICATE_EXTERNAL_ID);
@@ -9478,14 +10276,46 @@ var MockCalmLensApi = class {
9478
10276
  updatedAt: this.now()
9479
10277
  });
9480
10278
  }
9481
- async createSignedUrl(assetId, body) {
9482
- const asset = await this.findOwnAsset(assetId);
9483
- const expiresInSeconds = body.expiresInSeconds ?? 900;
9484
- const resource = body.resource ?? "rendered";
9485
- const selector = (body.lens ? `&lens=${encodeURIComponent(String(body.lens))}` : "") + (body.transform ? `&transform=${encodeURIComponent(String(body.transform))}` : "");
10279
+ /**
10280
+ * Signs an asset URL like the API (`POST /projects/:projectId/signed-asset-urls`): a grant to one
10281
+ * asset, by ID or external ID, until it expires, serving the original only when asked. The mock's
10282
+ * grant is readable (its asset, original access and expiry), unlike the CDN's, and only the
10283
+ * mock's CDN accepts it.
10284
+ */
10285
+ async signAssetUrl(body) {
10286
+ for (const key of [
10287
+ "assetId",
10288
+ "externalId",
10289
+ "expiresIn",
10290
+ "original"
10291
+ ]) if (body[key] === null) throw invalidField("validation/invalid-type", key);
10292
+ const { assetId, externalId } = body;
10293
+ if (assetId === void 0 === (externalId === void 0)) throw new ApiFailure(400, API_ERROR_CODES.INVALID_REQUEST, "Send either assetId or externalId", { issues: [{
10294
+ path: "",
10295
+ message: "Send either assetId or externalId",
10296
+ code: "custom"
10297
+ }] });
10298
+ const expiresIn = body.expiresIn ?? 900;
10299
+ if (typeof expiresIn !== "number" || !Number.isInteger(expiresIn)) throw invalidField("validation/invalid-type", "expiresIn");
10300
+ if (expiresIn < 1) throw invalidField("validation/too-small", "expiresIn");
10301
+ if (expiresIn > 86400) throw invalidField("validation/too-big", "expiresIn");
10302
+ const original = body.original ?? false;
10303
+ if (typeof original !== "boolean") throw invalidField("validation/invalid-type", "original");
10304
+ let asset;
10305
+ if (externalId !== void 0) {
10306
+ asset = (await this.databaseStorage.listAssets(this.projectId)).find((candidate) => candidate.externalId === externalId);
10307
+ if (!asset) throw fail(API_ERROR_CODES.ASSET_NOT_FOUND);
10308
+ } else asset = await this.findOwnAsset(String(assetId));
10309
+ if (asset.content.safetyHold) throw fail(API_ERROR_CODES.ASSET_HELD);
10310
+ const expiresAt = this.now() + expiresIn * 1e3;
10311
+ const grant = encodeMockGrant({
10312
+ assetId: asset.id,
10313
+ original,
10314
+ expiresAt
10315
+ });
9486
10316
  return {
9487
- url: `${this.options.signedUrlBaseUrl}/assets/${asset.id}/${resource}?expiresInSeconds=${expiresInSeconds}${selector}`,
9488
- expiresAt: this.now() + expiresInSeconds * 1e3
10317
+ url: `${this.cdnBaseUrl}/assets/${encodeURIComponent(this.projectId)}/${grant}`,
10318
+ expiresAt
9489
10319
  };
9490
10320
  }
9491
10321
  async retryAsset(assetId) {
@@ -9515,8 +10345,27 @@ var MockCalmLensApi = class {
9515
10345
  }
9516
10346
  if (asset.classification.moderation.manualReviews.length) throw fail(API_ERROR_CODES.ASSET_REVIEWED);
9517
10347
  if (asset.content.status === "removed") throw fail(API_ERROR_CODES.ASSET_CONTENT_UNAVAILABLE);
9518
- const rerun = await this.databaseStorage.updateAsset(await this.applyOutcome(asset, "pending"));
9519
- return this.moderateStored(rerun, "rerun");
10348
+ this.pushEvent({
10349
+ type: "asset.rerun-requested",
10350
+ actor: MOCK_API_KEY_ACTOR,
10351
+ severity: "low",
10352
+ assetId: asset.id,
10353
+ asset: toEventAsset(asset),
10354
+ facts: [
10355
+ assetNameFact(asset),
10356
+ {
10357
+ key: "asset-type",
10358
+ value: asset.type
10359
+ },
10360
+ {
10361
+ key: "moderation-status",
10362
+ value: asset.classification.moderation.status
10363
+ }
10364
+ ]
10365
+ });
10366
+ const response = structuredClone(asset);
10367
+ await this.settleRerun(asset, await this.decisionFor(asset, "rerun", true));
10368
+ return response;
9520
10369
  }
9521
10370
  /**
9522
10371
  * Checks every asset like the API (an ID that is not an asset ID is
@@ -9524,7 +10373,8 @@ var MockCalmLensApi = class {
9524
10373
  * one `asset/not-found`, and either refuses the whole batch), then applies the operation at
9525
10374
  * once instead of in the background: `delete` deletes each asset with its stored child
9526
10375
  * assets and records `asset.deleted` with the asset as it was; `remove-content` removes
9527
- * the content like `deleteContent`. Mock assets carry no safety holds, so none is skipped.
10376
+ * the content like `removeContent`. Each event carries the batch's `batch-id` fact. Mock assets
10377
+ * carry no safety holds, so none is skipped.
9528
10378
  */
9529
10379
  async batch(body) {
9530
10380
  const assetIds = Array.isArray(body.assetIds) ? body.assetIds : [];
@@ -9537,26 +10387,31 @@ var MockCalmLensApi = class {
9537
10387
  });
9538
10388
  const assets = [];
9539
10389
  for (const assetId of new Set(assetIds)) assets.push(await this.findOwnAsset(assetId));
10390
+ const batchId = this.createId("batch");
9540
10391
  for (const asset of assets) if (operation === "delete") {
9541
10392
  await this.deleteAssetTree(asset);
9542
- this.recordLifecycleEvent("asset.deleted", asset);
9543
- } else await this.removeContent(asset);
9544
- return { queued: true };
10393
+ this.recordLifecycleEvent("asset.deleted", asset, { batchId });
10394
+ } else await this.removeContent(asset, batchId);
10395
+ return {
10396
+ batchId,
10397
+ status: "queued",
10398
+ assetCount: assets.length
10399
+ };
9545
10400
  }
9546
10401
  /**
9547
10402
  * Removes an asset's content like the API: the record and report stay; stored content,
9548
10403
  * extracted text and the placeholder go. Content already removed keeps its reason, and an
9549
10404
  * `asset.content-removed` event is recorded either way.
9550
10405
  */
9551
- async removeContent(asset) {
10406
+ async removeContent(asset, batchId) {
9552
10407
  await this.imageStorage.deleteContent(asset.id);
9553
10408
  let removed = asset;
9554
10409
  if (asset.content.status === "removed") {
9555
- if (asset.content.image?.thumbhash) removed = await this.databaseStorage.updateAsset({
10410
+ if (asset.content.rendered || asset.content.preview) removed = await this.databaseStorage.updateAsset({
9556
10411
  ...asset,
9557
10412
  content: {
9558
10413
  ...asset.content,
9559
- image: withoutPlaceholder(asset.content.image)
10414
+ ...NO_RENDERING
9560
10415
  }
9561
10416
  });
9562
10417
  } else {
@@ -9570,13 +10425,13 @@ var MockCalmLensApi = class {
9570
10425
  removalReason: "requested",
9571
10426
  updatedAt: now,
9572
10427
  extractedText: null,
9573
- fileMetadata: null,
9574
- image: withoutPlaceholder(asset.content.image)
10428
+ metadata: null,
10429
+ ...NO_RENDERING
9575
10430
  },
9576
10431
  updatedAt: now
9577
10432
  });
9578
10433
  }
9579
- this.recordLifecycleEvent("asset.content-removed", removed);
10434
+ this.recordLifecycleEvent("asset.content-removed", removed, { batchId });
9580
10435
  return removed;
9581
10436
  }
9582
10437
  /** Deletes an asset, its stored child assets and their content. */
@@ -9598,7 +10453,11 @@ var MockCalmLensApi = class {
9598
10453
  /** The upload fields of `POST .../assets`: raw uploads carry them in the query. */
9599
10454
  uploadFields(request) {
9600
10455
  const upload = request.headers.get("x-calmlens-upload");
9601
- if (upload !== "content" && upload !== "part") return this.json(request);
10456
+ if (upload !== "content" && upload !== "part") {
10457
+ const body = this.json(request);
10458
+ checkMetadata(body.metadata);
10459
+ return body;
10460
+ }
9602
10461
  const { query } = request;
9603
10462
  const text = (name) => query.get(name) ?? void 0;
9604
10463
  const parsed = (name) => {
@@ -9607,16 +10466,18 @@ var MockCalmLensApi = class {
9607
10466
  try {
9608
10467
  return JSON.parse(raw);
9609
10468
  } catch {
9610
- throw invalidField("validation/invalid-json", name);
10469
+ throw invalidField("validation/invalid-value", name);
9611
10470
  }
9612
10471
  };
9613
10472
  const total = query.get("totalSizeInBytes");
10473
+ checkMetadata(parsed("metadata"));
9614
10474
  return {
9615
10475
  name: query.get("name") ?? "",
9616
10476
  description: text("description"),
9617
10477
  processingOptions: parsed("processingOptions"),
9618
10478
  visibility: text("visibility"),
9619
10479
  metadata: parsed("metadata"),
10480
+ tags: parsed("tags"),
9620
10481
  authorId: text("authorId"),
9621
10482
  context: parsed("context"),
9622
10483
  externalId: text("externalId"),
@@ -9633,22 +10494,25 @@ var MockCalmLensApi = class {
9633
10494
  };
9634
10495
  }
9635
10496
  async createAsset(request) {
9636
- return this.storeAsset(this.uploadFields(request), request.query.get("queue") === "true");
10497
+ return this.storeAsset(this.uploadFields(request), request.query.get("wait") === "false");
9637
10498
  }
9638
10499
  async storeAsset(fields, queue) {
9639
10500
  if (!fields.name) throw fail(API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Asset name is required" });
9640
10501
  const { contentType, part } = fields;
9641
10502
  const bytes = fields.bytes ?? /* @__PURE__ */ new Uint8Array(0);
9642
- if (contentType !== void 0 && isRejectedUploadMimeType(contentType)) throw fail(API_ERROR_CODES.INVALID_UPLOAD_MIME_TYPE, {
10503
+ if (contentType !== void 0 && !isAcceptedUploadMimeType(contentType)) throw fail(API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, {
9643
10504
  message: getRejectedUploadMimeTypeError(contentType),
9644
- details: { mimeType: contentType }
10505
+ details: {
10506
+ mimeType: contentType,
10507
+ source: "calmlens"
10508
+ }
9645
10509
  });
9646
10510
  const type = inferAssetType(fields.url === void 0 ? contentType ?? "" : void 0);
9647
10511
  if (part) {
9648
10512
  if (part.partNumber > 1) throw fail(API_ERROR_CODES.USE_UPLOAD_PART);
9649
10513
  const partSize = bytes.byteLength;
9650
10514
  const sizeError = (part.totalSizeInBytes === void 0 ? void 0 : this.multipartImageSizeError(type, part.totalSizeInBytes)) ?? (part.isFinal ? this.multipartTotalSizeError(part.totalSizeInBytes, partSize, true) ?? this.multipartImageSizeError(type, partSize) : void 0);
9651
- if (sizeError) throw fail(sizeError);
10515
+ if (sizeError) throw this.sizeFailure(sizeError);
9652
10516
  const validation = validateAssetPayload({ uint8Array: bytes }, {
9653
10517
  multipart: true,
9654
10518
  isFinal: part.isFinal
@@ -9668,6 +10532,7 @@ var MockCalmLensApi = class {
9668
10532
  const isOpenUpload = part !== void 0 && !part.isFinal;
9669
10533
  const processingOptions = fields.processingOptions ?? { keepContentAfterProcessing: false };
9670
10534
  const keepContent = processingOptions.keepContentAfterProcessing === true;
10535
+ this.processingOptions.set(id, processingOptions);
9671
10536
  const hasContent = fields.url === void 0;
9672
10537
  const contextItems = selectModerationContextItems(fields.context?.items ?? []);
9673
10538
  const asset = {
@@ -9683,11 +10548,10 @@ var MockCalmLensApi = class {
9683
10548
  externalId: fields.externalId ?? null,
9684
10549
  externalUrl: fields.url ?? fields.externalUrl ?? null,
9685
10550
  type,
9686
- metadata: fields.metadata ?? null,
10551
+ metadata: fields.metadata ?? [],
9687
10552
  authorId: fields.authorId ?? null,
9688
10553
  context: contextItems.length ? { items: contextItems } : null,
9689
- tags: null,
9690
- processingOptions,
10554
+ tags: fields.tags ?? [],
9691
10555
  visibility: fields.visibility ?? "private",
9692
10556
  content: {
9693
10557
  status: keepContent ? "stored" : "temporary",
@@ -9698,9 +10562,15 @@ var MockCalmLensApi = class {
9698
10562
  extension: null,
9699
10563
  sizeInBytes: hasContent ? bytes.byteLength : null,
9700
10564
  checksums: null,
9701
- image: null,
10565
+ width: null,
10566
+ height: null,
10567
+ durationSeconds: null,
10568
+ pageCount: null,
10569
+ perceptualHash: null,
10570
+ perceptualHashQuality: null,
10571
+ metadata: null,
9702
10572
  extractedText: null,
9703
- fileMetadata: null
10573
+ ...NO_RENDERING
9704
10574
  },
9705
10575
  upload: {
9706
10576
  status: isOpenUpload ? "uploading" : "completed",
@@ -9708,16 +10578,27 @@ var MockCalmLensApi = class {
9708
10578
  partsReceived: isOpenUpload ? part.partNumber : null
9709
10579
  },
9710
10580
  classification: {
9711
- status: isOpenUpload ? "pending" : "processing",
10581
+ status: isOpenUpload ? "queued" : "processing",
9712
10582
  failureReason: null,
9713
10583
  updatedAt: now,
9714
10584
  completedAt: null,
10585
+ progress: null,
10586
+ testInput: false,
9715
10587
  moderation: {
9716
10588
  status: "pending",
9717
10589
  manualReviews: [],
10590
+ automatedStatus: null,
10591
+ source: null,
10592
+ rule: null,
10593
+ explanationComplete: null,
10594
+ categories: null,
9718
10595
  flaggedCategories: [],
9719
- regions: []
9720
- }
10596
+ regions: [],
10597
+ raw: null,
10598
+ timeline: null
10599
+ },
10600
+ ocr: null,
10601
+ linkDetection: null
9721
10602
  }
9722
10603
  };
9723
10604
  if (part) {
@@ -9736,6 +10617,10 @@ var MockCalmLensApi = class {
9736
10617
  type: contentType ?? ""
9737
10618
  });
9738
10619
  if (isOpenUpload) return this.databaseStorage.createAsset(asset);
10620
+ if (hasContent) asset.content = {
10621
+ ...asset.content,
10622
+ ...mockRendering(asset, false)
10623
+ };
9739
10624
  const decision = await this.decisionFor(asset, "upload", queue, hasContent ? bytes : null);
9740
10625
  const stored = await this.databaseStorage.createAsset(decision.status === "pending" ? asset : await this.decided(asset, decision));
9741
10626
  this.recordUploaded(asset);
@@ -9760,7 +10645,7 @@ var MockCalmLensApi = class {
9760
10645
  const received = (asset.content.sizeInBytes ?? 0) + bytes.byteLength;
9761
10646
  const upload = this.openUploads.get(assetId);
9762
10647
  const sizeError = this.multipartImageSizeError(asset.type, received) ?? this.multipartTotalSizeError(upload?.totalSizeInBytes, received, isFinal);
9763
- if (sizeError) throw fail(sizeError);
10648
+ if (sizeError) throw this.sizeFailure(sizeError);
9764
10649
  const validation = validateAssetPayload({ uint8Array: bytes }, {
9765
10650
  multipart: true,
9766
10651
  isFinal
@@ -9771,8 +10656,8 @@ var MockCalmLensApi = class {
9771
10656
  partNumber,
9772
10657
  isFinal
9773
10658
  });
9774
- const queueOverride = query.get("queue");
9775
- const queue = queueOverride === null ? upload?.queue ?? false : queueOverride === "true";
10659
+ const waitOverride = query.get("wait");
10660
+ const queue = waitOverride === null ? upload?.queue ?? false : waitOverride === "false";
9776
10661
  if (isFinal) this.openUploads.delete(assetId);
9777
10662
  const now = this.now();
9778
10663
  const next = {
@@ -9799,7 +10684,14 @@ var MockCalmLensApi = class {
9799
10684
  /** Like the API: image uploads in parts total at most 20 MiB, at any size below that. */
9800
10685
  multipartImageSizeError(type, sizeInBytes) {
9801
10686
  if (type !== "image") return void 0;
9802
- if (sizeInBytes > MAX_IMAGE_UPLOAD_BYTES) return API_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE;
10687
+ if (sizeInBytes > MAX_IMAGE_UPLOAD_BYTES) return API_ERROR_CODES.UPLOAD_TOO_LARGE;
10688
+ }
10689
+ /** The failure for a size error code, with the limit `upload/too-large` carries. */
10690
+ sizeFailure(code) {
10691
+ return fail(code, code === API_ERROR_CODES.UPLOAD_TOO_LARGE ? { details: {
10692
+ limitBytes: MAX_IMAGE_UPLOAD_BYTES,
10693
+ source: "plan"
10694
+ } } : {});
9803
10695
  }
9804
10696
  /** Like the API: the parts may not overshoot a declared total, and must reach it at the end. */
9805
10697
  multipartTotalSizeError(totalSizeInBytes, receivedSizeInBytes, isFinal) {
@@ -9828,9 +10720,37 @@ var MockCalmLensApi = class {
9828
10720
  queued
9829
10721
  }));
9830
10722
  }
9831
- /** `asset` decided as `decision` says, with its report. */
9832
- decided(asset, decision) {
9833
- return this.applyOutcome(asset, decision.status, "policy", decision.report());
10723
+ /**
10724
+ * `asset` decided as `decision` says, with its report. Like the API for an image with nobody in
10725
+ * it, a decided image reports the person and face detection its upload turned on.
10726
+ */
10727
+ async decided(asset, decision) {
10728
+ const next = await this.applyOutcome(asset, decision.status, "policy", decision.report());
10729
+ const features = this.processingOptions.get(asset.id)?.features;
10730
+ if (next.classification.status !== "completed" || asset.type !== "image") return next;
10731
+ return {
10732
+ ...next,
10733
+ classification: {
10734
+ ...next.classification,
10735
+ ...features?.ocr?.enabled === true && { ocr: {
10736
+ status: "evaluated",
10737
+ textRegions: []
10738
+ } },
10739
+ ...features?.linkDetection?.enabled !== false && { linkDetection: {
10740
+ status: "evaluated",
10741
+ qrCodes: [],
10742
+ links: []
10743
+ } },
10744
+ ...features?.personDetection?.enabled === true && { personDetection: {
10745
+ status: "evaluated",
10746
+ people: []
10747
+ } },
10748
+ ...features?.faceDetection?.enabled === true && { faceDetection: {
10749
+ status: "evaluated",
10750
+ faces: []
10751
+ } }
10752
+ }
10753
+ };
9834
10754
  }
9835
10755
  /**
9836
10756
  * Stores a processing asset's `decision` and records its events; a `pending` decision leaves it
@@ -9842,6 +10762,20 @@ var MockCalmLensApi = class {
9842
10762
  this.recordProcessingEvents(stored, decision);
9843
10763
  return stored;
9844
10764
  }
10765
+ /**
10766
+ * Applies a re-run's `decision` to a decided asset like the pipeline: a `pending` decision stays
10767
+ * queued for `completeProcessing`, a `failed` one keeps the asset's decision, and any other
10768
+ * replaces it with the pipeline's events.
10769
+ */
10770
+ async settleRerun(asset, decision) {
10771
+ this.pendingReruns.delete(asset.id);
10772
+ if (decision.status === "pending") {
10773
+ this.pendingReruns.add(asset.id);
10774
+ return asset;
10775
+ }
10776
+ if (decision.status === "failed") return asset;
10777
+ return this.settle(asset, decision);
10778
+ }
9845
10779
  /** Asks `moderate` (unless `decision` is given) and settles a processing asset. */
9846
10780
  async moderateStored(asset, trigger, decision) {
9847
10781
  return this.settle(asset, decision ?? await this.decisionFor(asset, trigger, true));
@@ -9875,7 +10809,8 @@ var MockCalmLensApi = class {
9875
10809
  if (decision.status === "pending") return;
9876
10810
  const event = {
9877
10811
  assetId: asset.id,
9878
- asset: toEventAsset(asset)
10812
+ asset: toEventAsset(asset),
10813
+ actor: AUTOMATED_ACTOR
9879
10814
  };
9880
10815
  if (decision.status === "failed") {
9881
10816
  this.pushEvent({
@@ -9926,10 +10861,6 @@ var MockCalmLensApi = class {
9926
10861
  type: `asset.${decision.status}`,
9927
10862
  severity: decision.status === "allowed" || decision.status === "limited" ? "low" : "high",
9928
10863
  facts: [
9929
- {
9930
- key: "decided-by",
9931
- value: "automated"
9932
- },
9933
10864
  {
9934
10865
  key: "flagged-categories",
9935
10866
  value: flaggedCategories
@@ -9945,8 +10876,8 @@ var MockCalmLensApi = class {
9945
10876
  /**
9946
10877
  * Moves an asset to `outcome` like the pipeline would: a decision finishes processing, `purged`
9947
10878
  * deletes the content (with `purgeReason`, `policy` for the pipeline), and finished processing
9948
- * removes content kept only temporarily (`keepContentAfterProcessing` off). A classified image
9949
- * gets a ThumbHash for its placeholder, which goes with purged content.
10879
+ * removes content kept only temporarily (`keepContentAfterProcessing` off). A decided asset gets
10880
+ * its rendered file and preview (with a ThumbHash for its placeholder), which go with its content.
9950
10881
  */
9951
10882
  async applyOutcome(asset, outcome, purgeReason = "policy", report) {
9952
10883
  const now = this.now();
@@ -9955,15 +10886,7 @@ var MockCalmLensApi = class {
9955
10886
  const purge = outcome === "purged" && asset.content.status !== "removed";
9956
10887
  const removeContent = purge || classificationStatus === "completed" && asset.content.status === "temporary";
9957
10888
  if (removeContent) await this.imageStorage.deleteContent(asset.id);
9958
- const image = decided && asset.type === "image" && asset.content.status !== "removed" && !purge ? {
9959
- width: null,
9960
- height: null,
9961
- perceptualHash: null,
9962
- perceptualHashQuality: null,
9963
- ...asset.content.image,
9964
- thumbhash: MOCK_THUMBHASH,
9965
- averageColor: asset.content.image?.averageColor ?? "#7f7f7f"
9966
- } : outcome === "purged" ? withoutPlaceholder(asset.content.image) : asset.content.image;
10889
+ const rendering = asset.content.status !== "removed" && !purge && !asset.content.safetyHold ? mockRendering(asset, decided) : NO_RENDERING;
9967
10890
  return {
9968
10891
  ...asset,
9969
10892
  updatedAt: now,
@@ -9974,11 +10897,11 @@ var MockCalmLensApi = class {
9974
10897
  removalReason: purge ? purgeReason : "retention",
9975
10898
  updatedAt: now,
9976
10899
  extractedText: null,
9977
- fileMetadata: null,
9978
- image: withoutPlaceholder(image)
10900
+ metadata: null,
10901
+ ...NO_RENDERING
9979
10902
  } : {
9980
10903
  ...asset.content,
9981
- image
10904
+ ...rendering
9982
10905
  },
9983
10906
  upload: {
9984
10907
  ...asset.upload,
@@ -10000,20 +10923,29 @@ var MockCalmLensApi = class {
10000
10923
  };
10001
10924
  }
10002
10925
  /** Adds an `asset.deleted`, `asset.content-removed` or `asset.retried` event, like the API. */
10003
- recordLifecycleEvent(type, asset) {
10926
+ recordLifecycleEvent(type, asset, options = {}) {
10927
+ const { batchId, actor = MOCK_API_KEY_ACTOR } = options;
10004
10928
  this.pushEvent({
10005
10929
  type,
10930
+ actor,
10006
10931
  severity: "low",
10007
10932
  assetId: asset.id,
10008
10933
  asset: toEventAsset(asset),
10009
- facts: [{
10010
- key: "asset-name",
10011
- value: asset.name,
10012
- ...type === "asset.deleted" ? {} : { url: `https://calmlens.com/go/asset/${asset.id}` }
10013
- }, {
10014
- key: "asset-type",
10015
- value: asset.type
10016
- }]
10934
+ facts: [
10935
+ {
10936
+ key: "asset-name",
10937
+ value: asset.name,
10938
+ ...type === "asset.deleted" ? {} : { url: `https://calmlens.com/go/asset/${asset.id}` }
10939
+ },
10940
+ {
10941
+ key: "asset-type",
10942
+ value: asset.type
10943
+ },
10944
+ ...batchId ? [{
10945
+ key: "batch-id",
10946
+ value: batchId
10947
+ }] : []
10948
+ ]
10017
10949
  });
10018
10950
  }
10019
10951
  /**
@@ -10028,7 +10960,15 @@ var MockCalmLensApi = class {
10028
10960
  name: asset.name,
10029
10961
  uploadPresetId,
10030
10962
  createdAt: asset.createdAt,
10031
- ...preset.showDecisions !== false && { status: asset.classification.moderation.status }
10963
+ upload: {
10964
+ status: asset.upload.status,
10965
+ partsReceived: asset.upload.partsReceived
10966
+ },
10967
+ classification: {
10968
+ status: asset.classification.status,
10969
+ failureReason: asset.classification.failureReason,
10970
+ ...preset.showDecisions !== false && { moderation: { status: asset.classification.moderation.status } }
10971
+ }
10032
10972
  });
10033
10973
  const [assetId, action] = rest;
10034
10974
  if (assetId !== void 0) {
@@ -10042,19 +10982,32 @@ var MockCalmLensApi = class {
10042
10982
  const fields = this.uploadFields(request);
10043
10983
  const token = request.headers.get("authorization");
10044
10984
  if (preset.requireToken && !token) throw fail(API_ERROR_CODES.UPLOAD_PRESET_TOKEN_REQUIRED);
10985
+ const tokenExternalId = token ? decodeUploadToken(token.replace(/^Bearer /, ""))?.claims.x : void 0;
10986
+ if (fields.externalId && fields.externalId !== tokenExternalId) throw fail(API_ERROR_CODES.UPLOAD_PRESET_FIELD_NOT_ALLOWED, { details: { field: "externalId" } });
10987
+ for (const field of [
10988
+ "metadata",
10989
+ "tags",
10990
+ "authorId",
10991
+ "context",
10992
+ "processingOptions"
10993
+ ]) if (fields[field] !== void 0 && fields[field] !== null) throw fail(API_ERROR_CODES.UPLOAD_PRESET_FIELD_NOT_ALLOWED, { details: { field } });
10045
10994
  if (preset.allowedContentTypes && !isFileAccepted({
10046
10995
  name: fields.name,
10047
10996
  type: fields.contentType ?? ""
10048
- }, preset.allowedContentTypes.join(","))) throw fail(API_ERROR_CODES.UPLOAD_PRESET_CONTENT_TYPE_NOT_ALLOWED);
10997
+ }, preset.allowedContentTypes.join(","))) throw fail(API_ERROR_CODES.UNSUPPORTED_UPLOAD_TYPE, { details: { source: "preset" } });
10049
10998
  const size = fields.part?.totalSizeInBytes ?? fields.bytes?.byteLength;
10050
- if (preset.maxFileSizeInBytes !== void 0 && size !== void 0 && size > preset.maxFileSizeInBytes) throw fail(API_ERROR_CODES.UPLOAD_PRESET_TOO_LARGE);
10999
+ if (preset.maxFileSizeInBytes !== void 0 && size !== void 0 && size > preset.maxFileSizeInBytes) throw fail(API_ERROR_CODES.UPLOAD_TOO_LARGE, { details: {
11000
+ limitBytes: preset.maxFileSizeInBytes,
11001
+ source: "preset"
11002
+ } });
10051
11003
  const asset = await this.storeAsset({
10052
11004
  ...fields,
11005
+ externalId: tokenExternalId,
10053
11006
  uploadPresetId,
10054
11007
  visibility: preset.visibility ?? "public",
10055
11008
  folderId: preset.folderId ?? void 0,
10056
11009
  processingOptions: { keepContentAfterProcessing: preset.keepContentAfterProcessing ?? true }
10057
- }, request.query.get("queue") === "true");
11010
+ }, request.query.get("wait") === "false");
10058
11011
  session.uploads.add(asset.id);
10059
11012
  return toUploaded(asset);
10060
11013
  }
@@ -10067,22 +11020,33 @@ var MockCalmLensApi = class {
10067
11020
  const pageSize = this.integer(query, "pageSize", 50);
10068
11021
  if (pageSize < 1) throw invalidField("validation/too-small", "pageSize");
10069
11022
  if (pageSize > MAX_PAGE_SIZE) throw invalidField("validation/too-big", "pageSize");
11023
+ const typesValue = query.get("types");
11024
+ const types = typesValue === null ? [] : typesValue.split(",");
11025
+ if (typesValue !== null && (types.length === 0 || types.some((type) => !EVENT_TYPE_PATTERN.test(type)))) throw invalidField("validation/invalid-value", "types");
11026
+ const assetId = query.get("assetId");
11027
+ if (assetId !== null && !isId(assetId, "asset")) throw invalidField("validation/invalid-format", "assetId");
11028
+ const filter = btoa(JSON.stringify([[...new Set(types)].sort(), assetId]));
11029
+ const matches = (event) => (!types.length || types.includes(event.type)) && (assetId === null || event.assetId === assetId);
10070
11030
  const cursor = query.get("cursor");
10071
11031
  if (!cursor) return {
10072
11032
  items: [],
10073
- nextCursor: `mock_${this.eventFeed.length}`,
11033
+ nextCursor: `mock_${this.eventFeed.length}~${filter}`,
10074
11034
  hasMore: false,
10075
11035
  excludedTypes: []
10076
11036
  };
10077
- const match = /^mock_(\d+)$/.exec(cursor);
10078
- const position = match ? Number(match[1]) : NaN;
11037
+ const match = /^mock_(\d+)~(.*)$/.exec(cursor);
11038
+ const position = match && match[2] === filter ? Number(match[1]) : NaN;
10079
11039
  if (!Number.isSafeInteger(position) || position > this.eventFeed.length) throw fail(API_ERROR_CODES.INVALID_CURSOR);
10080
- const items = this.eventFeed.slice(position, position + pageSize);
10081
- const next = position + items.length;
11040
+ const items = [];
11041
+ let next = position;
11042
+ while (next < this.eventFeed.length && items.length < pageSize) {
11043
+ const event = this.eventFeed[next++];
11044
+ if (matches(event)) items.push(event);
11045
+ }
10082
11046
  return {
10083
11047
  items,
10084
- nextCursor: `mock_${next}`,
10085
- hasMore: next < this.eventFeed.length,
11048
+ nextCursor: `mock_${next}~${filter}`,
11049
+ hasMore: this.eventFeed.slice(next).some(matches),
10086
11050
  excludedTypes: []
10087
11051
  };
10088
11052
  }
@@ -10094,12 +11058,12 @@ var MockCalmLensApi = class {
10094
11058
  const all = await this.databaseStorage.listFolders?.(this.projectId) ?? [];
10095
11059
  const parentId = query.get("parentId");
10096
11060
  const search = query.get("search")?.trim() || null;
10097
- const ordering = this.folderOrdering(query);
11061
+ const sort = this.sort(query, ["name", "createdAt"], 1);
10098
11062
  const matching = all.filter((folder) => (folder.parentId ?? null) === parentId && (!search || folder.name.toLowerCase().includes(search.toLowerCase())));
10099
11063
  const page = createPage(matching, {
10100
11064
  cursor: query.get("cursor") ?? void 0,
10101
11065
  pageSize: this.integer(query, "pageSize", 50),
10102
- ordering
11066
+ sort
10103
11067
  }, {
10104
11068
  scope: JSON.stringify([
10105
11069
  this.projectId,
@@ -10107,7 +11071,7 @@ var MockCalmLensApi = class {
10107
11071
  search
10108
11072
  ]),
10109
11073
  fail: this.pageFailure,
10110
- defaultOrdering: [{
11074
+ defaultSort: [{
10111
11075
  field: "name",
10112
11076
  direction: "asc"
10113
11077
  }]
@@ -10123,21 +11087,9 @@ var MockCalmLensApi = class {
10123
11087
  items: folders,
10124
11088
  ancestors: all.filter((folder) => ids.has(folder.id) && !folders.some((item) => item.id === folder.id)),
10125
11089
  nextCursor: page.nextCursor,
10126
- pageSize: page.pageSize,
10127
- hasMore: page.hasMore,
10128
- ordering: page.ordering
11090
+ hasMore: page.hasMore
10129
11091
  };
10130
11092
  }
10131
- /** The folder list's `ordering`: at most one rule, by `name` or `createdAt`. */
10132
- folderOrdering(query) {
10133
- const ordering = this.ordering(query);
10134
- if (ordering.length > 1) throw invalidField("validation/too-big", "ordering");
10135
- for (const [index, rule] of ordering.entries()) {
10136
- if (rule.field !== "name" && rule.field !== "createdAt") throw invalidField("validation/invalid-value", `ordering.${index}.field`);
10137
- if (rule.direction !== "asc" && rule.direction !== "desc") throw invalidField("validation/invalid-value", `ordering.${index}.direction`);
10138
- }
10139
- return ordering;
10140
- }
10141
11093
  async createFolder(body) {
10142
11094
  const name = body.name;
10143
11095
  if (typeof name !== "string" || !name) throw fail(API_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Folder name is required" });
@@ -10208,7 +11160,7 @@ var MockCalmLensApi = class {
10208
11160
  async assertUniqueFolderName(name, parentId, excludeFolderId) {
10209
11161
  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.` });
10210
11162
  }
10211
- /** Saves each lens in order, like the API: new ones, or changes with a greater version. */
11163
+ /** Saves each lens in order, like the API: new ones, or a changed definition. */
10212
11164
  ensureLenses(body) {
10213
11165
  const lenses = Array.isArray(body.lenses) ? body.lenses : [];
10214
11166
  if (lenses.length === 0) throw invalidField("validation/too-small", "lenses");
@@ -10216,50 +11168,124 @@ var MockCalmLensApi = class {
10216
11168
  }
10217
11169
  ensureLens(options) {
10218
11170
  const existing = this.lenses.get(options.identifier);
10219
- if (!existing) {
10220
- const now = this.now();
10221
- const lens = {
10222
- id: this.createId("lens"),
10223
- projectId: this.projectId,
10224
- ...options,
10225
- createdAt: now,
10226
- updatedAt: now
10227
- };
10228
- this.lenses.set(lens.identifier, lens);
10229
- return lens;
10230
- }
10231
- 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) && existing.version === options.version) return existing;
10232
- if (options.version > existing.version) {
10233
- const lens = {
10234
- ...existing,
10235
- ...options,
10236
- updatedAt: this.now()
10237
- };
10238
- this.lenses.set(lens.identifier, lens);
10239
- return lens;
10240
- }
10241
- throw fail(API_ERROR_CODES.LENS_VERSION_CONFLICT, { details: {
10242
- currentVersion: existing.version,
10243
- minimumVersion: existing.version + 1,
10244
- requestedVersion: options.version
10245
- } });
11171
+ 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;
11173
+ const lens = {
11174
+ ...existing,
11175
+ ...options,
11176
+ updatedAt: this.now()
11177
+ };
11178
+ this.lenses.set(lens.identifier, lens);
11179
+ return lens;
11180
+ }
11181
+ saveNewLens(options) {
11182
+ const now = this.now();
11183
+ const lens = {
11184
+ id: this.createId("lens"),
11185
+ projectId: this.projectId,
11186
+ ...options,
11187
+ createdAt: now,
11188
+ updatedAt: now
11189
+ };
11190
+ this.lenses.set(lens.identifier, lens);
11191
+ return lens;
11192
+ }
11193
+ /** A page of the project's lenses, newest first unless `sort` says otherwise. */
11194
+ listLenses(query) {
11195
+ return createPage([...this.lenses.values()], this.pageQuery(query), {
11196
+ scope: `lenses:${this.projectId}`,
11197
+ fail: this.pageFailure
11198
+ });
11199
+ }
11200
+ createLens(body) {
11201
+ const definition = body;
11202
+ if (typeof definition.identifier !== "string" || !definition.identifier) throw invalidField("validation/invalid-type", "identifier");
11203
+ if (this.lenses.has(definition.identifier)) throw fail(API_ERROR_CODES.LENS_IDENTIFIER_TAKEN, { details: { identifier: definition.identifier } });
11204
+ return this.saveNewLens(definition);
11205
+ }
11206
+ findLens(lensId) {
11207
+ const lens = [...this.lenses.values()].find((candidate) => candidate.id === lensId);
11208
+ if (!lens) throw fail(API_ERROR_CODES.LENS_NOT_FOUND);
11209
+ return lens;
11210
+ }
11211
+ updateLens(lensId, body) {
11212
+ const lens = this.findLens(lensId);
11213
+ const { identifier: _identifier, ...changes } = body;
11214
+ return this.ensureLens({
11215
+ ...lens,
11216
+ ...changes
11217
+ });
11218
+ }
11219
+ deleteLens(lensId) {
11220
+ this.lenses.delete(this.findLens(lensId).identifier);
11221
+ return {};
10246
11222
  }
10247
11223
  /**
10248
- * Serves stored content like the CDN (`/assets/:projectId/:asset/:resource`): `200` with
11224
+ * Serves an asset's resources like the CDN (`/assets/:projectId/:asset/:resource`): `200` with
10249
11225
  * `Content-Type`, `Content-Length`, `Cache-Control`, `Cache-Tag`, the CDN's protection headers
10250
- * and, for images, `ETag` and `Expires`; or a JSON error body with `404`/`403`. A
10251
- * `placeholder` is the asset's ThumbHash as a PNG.
11226
+ * and, for still images, `ETag` and `Expires`; or a JSON error body with `400`, `403` or `404`.
11227
+ * `original` is the upload; `rendered` the image, PDF, video or audio file `content.rendered`
11228
+ * describes; `preview` the still `content.preview` describes; and `placeholder` its ThumbHash as a
11229
+ * PNG. The mock converts nothing: an upload stands in for its rendered file, an image for its own
11230
+ * preview, and the placeholder PNG for a screenshot, page, poster or waveform.
10252
11231
  */
10253
11232
  async serveCdn(request) {
10254
11233
  const { url, segments, query } = request;
10255
- const [root, projectId, assetIdentifier, resource] = segments;
11234
+ const [root, projectId, , resource] = segments;
11235
+ const assetSegment = request.rawSegments[2] ?? "";
11236
+ const selectorPath = request.rawSegments.slice(4);
10256
11237
  const notFound = () => this.jsonResponse(404, {
10257
11238
  code: "asset/not-found",
10258
11239
  message: "Asset not found"
10259
11240
  }, url);
10260
- if (root !== "assets" || projectId !== this.projectId || !assetIdentifier) return notFound();
10261
- const asset = (await this.databaseStorage.listAssets(this.projectId)).find((asset) => asset.id === assetIdentifier || asset.externalId === assetIdentifier);
11241
+ const noRenderedVersion = () => this.jsonResponse(404, {
11242
+ code: "asset/no-rendered-version",
11243
+ message: "This asset has no such resource"
11244
+ }, url);
11245
+ const invalidTransform = () => this.jsonResponse(400, {
11246
+ code: "transform/invalid",
11247
+ message: "Invalid transform selector"
11248
+ }, url);
11249
+ const isHls = resource === "hls";
11250
+ let selector;
11251
+ try {
11252
+ selector = parseTransformSelector(isHls ? "" : selectorPath.join("/"));
11253
+ } catch {
11254
+ return invalidTransform();
11255
+ }
11256
+ const hasSelector = Boolean(selector.lens || selector.options);
11257
+ if ((resource === "original" || resource === "embed" || resource === "info") && hasSelector) return invalidTransform();
11258
+ if (root !== "assets" || projectId !== this.projectId || !assetSegment) return notFound();
11259
+ const assets = await this.databaseStorage.listAssets(this.projectId);
11260
+ let grant;
11261
+ let asset;
11262
+ if (assetSegment.startsWith("sig_")) {
11263
+ grant = decodeMockGrant(assetSegment);
11264
+ if (!grant) return this.jsonResponse(403, {
11265
+ code: "signed-url/invalid",
11266
+ message: "The signed asset URL's grant is invalid"
11267
+ }, url);
11268
+ if (grant.expiresAt <= this.now()) return this.jsonResponse(403, {
11269
+ code: "signed-url/expired",
11270
+ message: "The signed URL has expired"
11271
+ }, url);
11272
+ const grantedId = grant.assetId;
11273
+ asset = assets.find((candidate) => candidate.id === grantedId);
11274
+ } else if (assetSegment.startsWith("ext:")) {
11275
+ let externalId;
11276
+ try {
11277
+ externalId = decodeURIComponent(assetSegment.slice(4));
11278
+ } catch {}
11279
+ asset = externalId ? assets.find((candidate) => candidate.externalId === externalId) : void 0;
11280
+ } else {
11281
+ const assetId = decodeSegment(assetSegment);
11282
+ asset = assets.find((candidate) => candidate.id === assetId);
11283
+ }
10262
11284
  if (!asset) return notFound();
11285
+ if (resource === "original" && grant && !grant.original) return this.jsonResponse(403, {
11286
+ code: "signed-url/original-not-granted",
11287
+ message: "This signed asset URL doesn't grant the original file"
11288
+ }, url);
10263
11289
  const notAvailable = () => this.jsonResponse(403, {
10264
11290
  code: "asset/not-available",
10265
11291
  message: "Asset is not available"
@@ -10269,11 +11295,13 @@ var MockCalmLensApi = class {
10269
11295
  const canDownload = () => permits(grants, "assets:download", asset.folderId ?? null, folders);
10270
11296
  const status = asset.classification.moderation.status;
10271
11297
  const isHead = request.method === "HEAD";
11298
+ const { rendered, preview } = asset.content;
11299
+ if (resource === "info") return this.serveInfo(request, asset, Boolean(grant) || canDownload());
11300
+ if (asset.content.safetyHold) return notAvailable();
10272
11301
  if (resource === "placeholder") {
10273
- const thumbhash = asset.content.image?.thumbhash;
11302
+ const thumbhash = preview?.thumbhash;
10274
11303
  if (!thumbhash || status === "purged") return notAvailable();
10275
- const png = Uint8Array.from(atob(placeholderHashToDataURL(thumbhash).split(",", 2)[1]), (char) => char.charCodeAt(0));
10276
- return this.cdnResponse(isHead, png, url, {
11304
+ return this.cdnResponse(isHead, mockPlaceholderPng(thumbhash), url, {
10277
11305
  "Content-Type": "image/png",
10278
11306
  "Cache-Control": "public, max-age=3600",
10279
11307
  "Cache-Tag": `asset-${asset.id}`,
@@ -10281,33 +11309,59 @@ var MockCalmLensApi = class {
10281
11309
  });
10282
11310
  }
10283
11311
  const storedContent = await this.imageStorage.getContent(asset.id);
10284
- if (asset.upload.status === "uploading" || status === "purged" || status === "blocked" || asset.classification.status === "failed" || asset.content.status === "removed" || !storedContent) return notAvailable();
11312
+ if (asset.upload.status === "uploading" || status === "purged" || status === "blocked" || asset.classification.status === "failed" || asset.content.status === "removed" || resource === "original" && !storedContent) return notAvailable();
10285
11313
  let claims = {};
10286
11314
  try {
10287
11315
  claims = JSON.parse(query.get("viewerClaims") ?? request.headers.get("X-CalmLens-Viewer-Claims") ?? "{}");
10288
11316
  } catch {
10289
- return this.jsonResponse(400, { code: "viewer/invalid-claims" }, url);
11317
+ return this.jsonResponse(400, { code: "viewer-claims/invalid" }, url);
10290
11318
  }
10291
11319
  if (status === "age-restricted" && claims.ageConfirmed !== true) return this.jsonResponse(403, { code: "viewer/age-confirmation-required" }, url);
10292
11320
  const isPrivate = asset.visibility !== "public";
10293
- if (isPrivate && !canDownload()) return this.jsonResponse(403, {
10294
- code: "asset/api-key-missing-permission",
11321
+ if (isPrivate && !grant && !canDownload()) return this.jsonResponse(403, {
11322
+ code: "auth/permission-denied",
10295
11323
  message: "This API key needs assets:download permission for this asset’s folder."
10296
11324
  }, url);
10297
- const parts = [...storedContent.parts.entries()].sort(([left], [right]) => left - right).map(([, value]) => value);
10298
- const bytes = new Uint8Array(parts.reduce((sum, value) => sum + value.byteLength, 0));
10299
- let offset = 0;
10300
- for (const part of parts) {
10301
- bytes.set(part, offset);
10302
- offset += part.byteLength;
10303
- }
10304
- const contentType = storedContent.type ?? "application/octet-stream";
10305
- const isImage = asset.type === "image";
11325
+ if (resource === "embed") return this.cdnResponse(isHead, new TextEncoder().encode(MOCK_EMBED_HTML), url, {
11326
+ "Content-Type": "text/html; charset=utf-8",
11327
+ "Cache-Control": Object.keys(claims).length ? "private, no-store" : `${isPrivate ? "private" : "public"}, max-age=3600`,
11328
+ "Cache-Tag": `asset-${asset.id}`,
11329
+ "X-Content-Type-Options": "nosniff"
11330
+ });
11331
+ if (resource === "rendered" && !rendered || resource === "preview" && !preview) return noRenderedVersion();
11332
+ if (isHls && !asset.content.hls) return noRenderedVersion();
11333
+ const stillImage = resource === "preview" || resource === "rendered" && rendered?.kind === "image";
11334
+ if (!stillImage && hasSelector) return invalidTransform();
11335
+ if (selector.options) {
11336
+ const { unknownKeys, invalidKeys } = checkTransformOptions(selector.options);
11337
+ if (unknownKeys.length || invalidKeys.length) return this.jsonResponse(400, {
11338
+ code: "transform-options/invalid",
11339
+ message: `Invalid transform options: ${[...unknownKeys, ...invalidKeys].join(", ")}`
11340
+ }, url);
11341
+ }
11342
+ const servesUpload = resource === "original" || resource === "rendered" && rendered?.kind !== "image" || asset.type === "image";
11343
+ let bytes;
11344
+ let contentType;
11345
+ if (servesUpload) {
11346
+ if (!storedContent) return notAvailable();
11347
+ const parts = [...storedContent.parts.entries()].sort(([left], [right]) => left - right).map(([, value]) => value);
11348
+ bytes = new Uint8Array(parts.reduce((sum, value) => sum + value.byteLength, 0));
11349
+ let offset = 0;
11350
+ for (const part of parts) {
11351
+ bytes.set(part, offset);
11352
+ offset += part.byteLength;
11353
+ }
11354
+ contentType = resource === "rendered" && rendered ? rendered.format : storedContent.type ?? "application/octet-stream";
11355
+ } else {
11356
+ bytes = mockPlaceholderPng(preview?.thumbhash ?? MOCK_THUMBHASH);
11357
+ contentType = "image/png";
11358
+ }
11359
+ const immutable = stillImage || resource === "original" && asset.type === "image";
10306
11360
  return this.cdnResponse(isHead, bytes, url, {
10307
11361
  "Content-Type": contentType,
10308
- "Cache-Control": Object.keys(claims).length ? "private, no-store" : `${isPrivate ? "private" : "public"}, ${isImage ? "max-age=31536000, immutable" : "max-age=3600"}`,
11362
+ "Cache-Control": Object.keys(claims).length ? "private, no-store" : `${isPrivate ? "private" : "public"}, ${immutable ? "max-age=31536000, immutable" : "max-age=3600"}`,
10309
11363
  "Cache-Tag": `asset-${asset.id}`,
10310
- ...isImage ? {
11364
+ ...immutable ? {
10311
11365
  ETag: `"${asset.id}"`,
10312
11366
  Expires: new Date(this.now() + 31536e6).toUTCString()
10313
11367
  } : {},
@@ -10316,6 +11370,51 @@ var MockCalmLensApi = class {
10316
11370
  ...isActiveContentType(contentType) ? { "Content-Disposition": "attachment" } : {}
10317
11371
  });
10318
11372
  }
11373
+ /**
11374
+ * The display info at `/info`, like the CDN's (AssetInfo.ts): the allowlisted fields and whether
11375
+ * the viewer the claims describe can see the content, decided as the other resources decide it.
11376
+ * A private asset's needs a grant or an API key with `assets:download`.
11377
+ */
11378
+ serveInfo(request, asset, authorised) {
11379
+ const { url, query } = request;
11380
+ const isPrivate = asset.visibility !== "public";
11381
+ if (isPrivate && !authorised) return this.jsonResponse(404, {
11382
+ code: "asset/not-available",
11383
+ message: "Asset is not available"
11384
+ }, url);
11385
+ let claims = {};
11386
+ try {
11387
+ claims = JSON.parse(query.get("viewerClaims") ?? request.headers.get("X-CalmLens-Viewer-Claims") ?? "{}");
11388
+ } catch {
11389
+ return this.jsonResponse(400, { code: "viewer-claims/invalid" }, url);
11390
+ }
11391
+ const status = asset.classification.moderation.status;
11392
+ const availability = asset.content.safetyHold || asset.upload.status === "uploading" || status === "blocked" || status === "purged" || asset.classification.status === "failed" || asset.content.status === "removed" ? "unavailable" : status === "age-restricted" && claims.ageConfirmed !== true ? "age-restricted" : "available";
11393
+ const { content } = asset;
11394
+ const info = {
11395
+ id: asset.id,
11396
+ projectId: asset.projectId,
11397
+ type: asset.type,
11398
+ externalUrl: asset.externalUrl ?? null,
11399
+ content: {
11400
+ format: content.format,
11401
+ width: content.width,
11402
+ height: content.height,
11403
+ durationSeconds: content.durationSeconds,
11404
+ pageCount: content.pageCount,
11405
+ rendered: content.rendered,
11406
+ preview: content.preview,
11407
+ hls: content.hls
11408
+ },
11409
+ availability
11410
+ };
11411
+ const bytes = new TextEncoder().encode(JSON.stringify(info));
11412
+ return this.cdnResponse(request.method === "HEAD", bytes, url, {
11413
+ "Content-Type": "application/json",
11414
+ "Cache-Control": `${isPrivate ? "private" : "public"}, max-age=60`,
11415
+ "Cache-Tag": `asset-${asset.id}`
11416
+ });
11417
+ }
10319
11418
  cdnResponse(isHead, bytes, url, headers) {
10320
11419
  return this.response(200, isHead ? null : bytes, url, {
10321
11420
  ...headers,
@@ -10402,7 +11501,6 @@ var InMemoryMockDatabaseStorage = class {
10402
11501
  this.folders.delete(folderId);
10403
11502
  }
10404
11503
  };
10405
- // src/testing/MockCalmLensServerClient.ts
10406
11504
  const apis = /* @__PURE__ */ new WeakMap();
10407
11505
  /** The in-memory API a mock server client runs against, for `MockCalmLensAppClient`. */
10408
11506
  const getMockApi = (client) => {
@@ -10444,13 +11542,18 @@ const mockClientOptions = (api, endpoints, session) => {
10444
11542
  */
10445
11543
  var MockCalmLensServerClient = class extends CalmLensServerClient {
10446
11544
  #api;
11545
+ #fetch;
10447
11546
  #projectId;
10448
11547
  /**
10449
11548
  * Accepts the same options as `CalmLensServerClient` (validated the same way), plus
10450
11549
  * `mockOptions`. `maxRetries` defaults to 0, so a failed request fails once; retry backoff and
10451
11550
  * `assets.waitForDecision` take no real time.
10452
11551
  */
10453
- constructor(options) {
11552
+ constructor(input) {
11553
+ const options = {
11554
+ ...input,
11555
+ projectId: input.projectId ?? "project-1"
11556
+ };
10454
11557
  validateServerClientOptions(options);
10455
11558
  const { mockOptions = {}, ...clientOptions } = options;
10456
11559
  const api = new MockCalmLensApi({
@@ -10461,8 +11564,7 @@ var MockCalmLensServerClient = class extends CalmLensServerClient {
10461
11564
  imageStorage: mockOptions.imageStorage ?? new InMemoryMockImageStorage(),
10462
11565
  createId: mockOptions.createId ?? newId,
10463
11566
  now: mockOptions.now ?? createMonotonicClock(),
10464
- moderate: mockOptions.moderate ?? defaultModerate,
10465
- signedUrlBaseUrl: mockOptions.signedUrlBaseUrl ?? "mock://calmlens"
11567
+ moderate: mockOptions.moderate ?? defaultModerate
10466
11568
  });
10467
11569
  let endpoints;
10468
11570
  super({
@@ -10477,6 +11579,7 @@ var MockCalmLensServerClient = class extends CalmLensServerClient {
10477
11579
  cdnBaseUrl
10478
11580
  };
10479
11581
  this.#api = api;
11582
+ this.#fetch = api.createFetch(() => endpoints);
10480
11583
  this.#projectId = options.projectId;
10481
11584
  this.databaseStorage = api.databaseStorage;
10482
11585
  this.imageStorage = api.imageStorage;
@@ -10501,6 +11604,14 @@ var MockCalmLensServerClient = class extends CalmLensServerClient {
10501
11604
  callsTo(operation) {
10502
11605
  return this.#api.calls.filter(({ operations }) => operations.includes(operation)).map(({ call }) => call);
10503
11606
  }
11607
+ /**
11608
+ * Fetches a URL of the mock's CDN as a browser would, without the API key: a signed asset URL
11609
+ * from `cdn.signAssetUrl` (with a resource appended), or a public one from `cdn.getAssetUrl`.
11610
+ * The request is recorded like any other.
11611
+ */
11612
+ fetchCdn(url, init) {
11613
+ return this.#fetch(url, init);
11614
+ }
10504
11615
  /** Forgets the requests recorded so far, so `calls` lists only later ones. */
10505
11616
  clearCalls() {
10506
11617
  this.#api.calls.length = 0;
@@ -10533,7 +11644,7 @@ var MockCalmLensServerClient = class extends CalmLensServerClient {
10533
11644
  * Applies a reviewer's decision to a stored asset, as the portal or API would: the moderation
10534
11645
  * status changes (`purged` also removes the content, with reason `requested` and an
10535
11646
  * `asset.content-removed` event), the review joins `manualReviews`, and an `asset.<decision>`
10536
- * event with a `decided-by: reviewer` fact joins the events feed. Rejects with
11647
+ * event whose `actor` is a `user` joins the events feed. Rejects with
10537
11648
  * `asset/not-found` for an unknown asset. It sends no request.
10538
11649
  */
10539
11650
  decide(assetId, decision) {
@@ -10544,15 +11655,17 @@ var MockCalmLensServerClient = class extends CalmLensServerClient {
10544
11655
  * else what `mockOptions.moderate` returns for the `complete` trigger (`allowed` by default).
10545
11656
  * The asset gets the decision's report, and `asset.classified` and the automated
10546
11657
  * `asset.<status>` (or `asset.failed`) join the events feed. No review is recorded, so the
10547
- * asset can still be moderated again. Rejects with `asset/not-found` for an unknown asset and
10548
- * `sdk/invalid-argument` for one that isn't processing. It sends no request.
11658
+ * asset can still be moderated again. A decided asset whose re-run (`assets.explain` with
11659
+ * `rerun: true`) is still pending gets the decision in place of its old one, unless it is
11660
+ * `pending` or `failed`. Rejects with `asset/not-found` for an unknown asset and
11661
+ * `sdk/invalid-argument` for one that isn't processing or awaiting a pending re-run. It sends
11662
+ * no request.
10549
11663
  */
10550
11664
  completeProcessing(assetId, decision) {
10551
11665
  return this.#api.completeProcessing(assetId, decision);
10552
11666
  }
10553
11667
  };
10554
11668
  // src/testing/MockCalmLensAppClient.ts
10555
- const MOCK_PROJECT_ID = "proj_0000000000000000c1a5";
10556
11669
  /**
10557
11670
  * The real `CalmLensAppClient`, answered by the in-memory API of a `MockCalmLensServerClient`.
10558
11671
  * The API applies `mockOptions.preset` to this client's uploads like CalmLens applies an upload
@@ -10575,7 +11688,6 @@ var MockCalmLensAppClient = class extends CalmLensAppClient {
10575
11688
  folderId: null,
10576
11689
  includeSubfolders: true
10577
11690
  }]),
10578
- projectId: MOCK_PROJECT_ID,
10579
11691
  mockOptions: { moderate: mockOptions.moderate }
10580
11692
  });
10581
11693
  let endpoints;
@@ -10608,11 +11720,13 @@ var MockCalmLensAppClient = class extends CalmLensAppClient {
10608
11720
  const toWebhookEventPayload = (event) => ({
10609
11721
  id: event.id,
10610
11722
  projectId: event.projectId,
11723
+ actor: event.actor,
10611
11724
  type: event.type,
10612
11725
  severity: event.severity,
10613
11726
  title: event.title,
10614
11727
  description: event.description ?? null,
10615
11728
  assetId: event.assetId ?? null,
11729
+ assetSequence: event.assetSequence ?? null,
10616
11730
  asset: event.asset ?? null,
10617
11731
  facts: event.facts,
10618
11732
  createdAt: event.createdAt