calmlens 0.20.0 → 0.22.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 (110) hide show
  1. package/README.md +15 -10
  2. package/bin/calmlens.js +1848 -679
  3. package/cjs/{BrowserUpload-C07aL9Vq.d.ts → BrowserUpload-BWjZ9ntu.d.ts} +2 -2
  4. package/cjs/{BrowserUpload-CjSHjx3C.js → BrowserUpload-Bwlib4Zc.js} +1 -1
  5. package/cjs/{CalmLensAppClient-DDLojj0P.d.ts → CalmLensAppClient-BaW3ddUR.d.ts} +13 -3
  6. package/cjs/{CalmLensAppClient-NaCxOVlM.js → CalmLensAppClient-DUYMo9PZ.js} +30 -10
  7. package/cjs/{CalmLensOptionKeys-p2QK687A.js → CalmLensOptionKeys-YvgV995V.js} +318 -374
  8. package/cjs/{CalmLensServerClient-BDzTthxE.js → CalmLensServerClient-3N-gdsxC.js} +346 -89
  9. package/cjs/CalmLensServerClient-BKzn8zmp.d.ts +353 -0
  10. package/cjs/{CalmLensTypes-COJbOuiv.d.ts → CalmLensTypes-BDKwThbO.d.ts} +26993 -27187
  11. package/cjs/{Classification-D3SkprrQ-CMnQKW13.d.ts → Classification-Q5zGpR8l-CEWjnE39.d.ts} +731 -607
  12. package/cjs/Core-C33pkBmf.d.ts +826 -0
  13. package/cjs/Core-Cm5Z1oJ9.js +1001 -0
  14. package/cjs/FileIcons-4qSX7DW2.d.ts +67 -0
  15. package/cjs/{ModerationContextLimits-2nIv7Zh3.js → ModerationContextLimits-ud1xpZRK.js} +727 -268
  16. package/cjs/{ReactUpload-BdTRCTGA.js → ReactUpload-DQ0BYISX.js} +1 -1
  17. package/cjs/{ReactUpload-CRJNPB5T.d.ts → ReactUpload-DhF8mm51.d.ts} +1 -1
  18. package/{esm/TestTriggers-D-fwfhEP-hlaP1oW2.d.ts → cjs/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts} +146 -8
  19. package/cjs/{TestTriggers-DbhsNPdg-DjvVuc2h.js → TestTriggers-D29T_R0M-D6Bu-Mln.js} +355 -47
  20. package/cjs/{UploadController-MLVs97Zt.js → UploadController-l8fZM2qT.js} +34 -14
  21. package/{esm/WebhookPayload-DkukERKE.d.ts → cjs/WebhookPayload-Dt6DttS0.d.ts} +120 -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-Bde1wjiw.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 -15
  39. package/cjs/testing.js +1722 -433
  40. package/cjs/ui-BRA4HQ8r.js +1359 -0
  41. package/cjs/ui-YQuvbidU.d.ts +139 -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/esm/{BrowserUpload-C07aL9Vq.d.ts → BrowserUpload-BWjZ9ntu.d.ts} +2 -2
  47. package/esm/{BrowserUpload-CAVkRotw.js → BrowserUpload-GRZVB0G_.js} +1 -1
  48. package/esm/{CalmLensAppClient-PQ9VBvlW.js → CalmLensAppClient-B5QIJ6KS.js} +30 -10
  49. package/esm/{CalmLensAppClient-DDLojj0P.d.ts → CalmLensAppClient-BaW3ddUR.d.ts} +13 -3
  50. package/esm/{CalmLensOptionKeys-Do2mPP6w.js → CalmLensOptionKeys-BG7Qrh8-.js} +317 -367
  51. package/esm/CalmLensServerClient-BKzn8zmp.d.ts +353 -0
  52. package/esm/{CalmLensServerClient-C_H5aAsV.js → CalmLensServerClient-bRUAebi-.js} +323 -90
  53. package/esm/{CalmLensTypes-COJbOuiv.d.ts → CalmLensTypes-BDKwThbO.d.ts} +26993 -27187
  54. package/esm/{Classification-D3SkprrQ-CMnQKW13.d.ts → Classification-Q5zGpR8l-CEWjnE39.d.ts} +731 -607
  55. package/esm/Core-BvQe4moS.js +846 -0
  56. package/esm/Core-C33pkBmf.d.ts +826 -0
  57. package/esm/FileIcons-4qSX7DW2.d.ts +67 -0
  58. package/esm/{ModerationContextLimits-Chw-AzgL.js → ModerationContextLimits-CrxSnVZ3.js} +682 -253
  59. package/esm/{ReactUpload-CMmL0R5Q.js → ReactUpload-BMO8saxT.js} +1 -1
  60. package/esm/{ReactUpload-CRJNPB5T.d.ts → ReactUpload-DhF8mm51.d.ts} +1 -1
  61. package/{cjs/TestTriggers-D-fwfhEP-hlaP1oW2.d.ts → esm/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts} +146 -8
  62. package/esm/{TestTriggers-DbhsNPdg-CUdrv8Nm.js → TestTriggers-D29T_R0M-Ztc74ucs.js} +332 -48
  63. package/esm/{UploadController-BJZghJpg.js → UploadController-DnJrWiE4.js} +34 -14
  64. package/{cjs/WebhookPayload-DkukERKE.d.ts → esm/WebhookPayload-Dt6DttS0.d.ts} +120 -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-Bde1wjiw.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 -15
  92. package/esm/testing.js +1718 -429
  93. package/esm/ui-YQuvbidU.d.ts +139 -0
  94. package/esm/ui-heryDd6g.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 +4 -2
  100. package/cjs/CalmLensServerClient-C-jsjn8m.d.ts +0 -259
  101. package/cjs/ModerationContext-9lGm-Mna-CcmbRnOy.d.ts +0 -67
  102. package/cjs/index-DxbJ_Xaa.d.ts +0 -253
  103. package/cjs/ui-BSqPGKrZ.d.ts +0 -539
  104. package/cjs/ui-CX1z2pD9.js +0 -586
  105. package/esm/CalmLensServerClient-C-jsjn8m.d.ts +0 -259
  106. package/esm/ModerationContext-9lGm-Mna-CcmbRnOy.d.ts +0 -67
  107. package/esm/index-DxbJ_Xaa.d.ts +0 -253
  108. package/esm/svelte/CalmLensMedia.svelte +0 -134
  109. package/esm/ui-BSqPGKrZ.d.ts +0 -539
  110. package/esm/ui-CXH7xJpb.js +0 -461
@@ -33,66 +33,66 @@ const CLASSIFICATION_CATEGORIES = [
33
33
  "personal-information",
34
34
  "profanity"
35
35
  ];
36
- // src/contract/Jurisdiction-DF7spSE4.js
36
+ // src/contract/Jurisdiction-LWQvqyxL.js
37
37
  /**
38
- * Jurisdictions with legal rules always apply to every project. An opt-in jurisdiction is a product
39
- * standard rather than a legal floor, so a project chooses whether to serve it.
38
+ * Jurisdictions with legal rules always apply to every project. An optional jurisdiction is a
39
+ * product standard rather than a legal floor: every project serves it unless it opts out.
40
40
  */
41
41
  const JURISDICTIONS = {
42
42
  global: {
43
43
  name: "Global",
44
44
  ageCheckStandard: "any",
45
- optIn: false
45
+ optional: false
46
46
  },
47
47
  DE: {
48
48
  name: "Germany",
49
49
  ageCheckStandard: "any",
50
- optIn: false
50
+ optional: false
51
51
  },
52
52
  AT: {
53
53
  name: "Austria",
54
54
  ageCheckStandard: "any",
55
- optIn: false
55
+ optional: false
56
56
  },
57
57
  FR: {
58
58
  name: "France",
59
59
  ageCheckStandard: "any",
60
- optIn: false
60
+ optional: false
61
61
  },
62
62
  GB: {
63
63
  name: "United Kingdom",
64
64
  ageCheckStandard: "verified",
65
- optIn: false
65
+ optional: false
66
66
  },
67
67
  EU: {
68
68
  name: "European Union",
69
69
  ageCheckStandard: "verified",
70
- optIn: true
70
+ optional: true
71
71
  },
72
72
  AU: {
73
73
  name: "Australia",
74
74
  ageCheckStandard: "verified",
75
- optIn: false
75
+ optional: false
76
76
  },
77
77
  BR: {
78
78
  name: "Brazil",
79
79
  ageCheckStandard: "verified",
80
- optIn: false
80
+ optional: false
81
81
  }
82
82
  };
83
83
  const JURISDICTION_SCHEMA = zod.enum(Object.keys(JURISDICTIONS));
84
- Object.keys(JURISDICTIONS).filter((code) => !JURISDICTIONS[code].optIn);
85
- const OPT_IN_JURISDICTIONS = Object.keys(JURISDICTIONS).filter((code) => JURISDICTIONS[code].optIn);
86
- zod.enum(OPT_IN_JURISDICTIONS).array().refine((codes) => new Set(codes).size === codes.length, { message: "jurisdiction/duplicate" });
84
+ Object.keys(JURISDICTIONS).filter((code) => !JURISDICTIONS[code].optional);
85
+ const OPTIONAL_JURISDICTIONS = Object.keys(JURISDICTIONS).filter((code) => JURISDICTIONS[code].optional);
86
+ zod.enum(OPTIONAL_JURISDICTIONS).array().refine((codes) => new Set(codes).size === codes.length, { message: "jurisdiction/duplicate" });
87
87
  JURISDICTION_SCHEMA.array().min(1).refine((regions) => regions.includes("global") && new Set(regions).size === regions.length, { message: "jurisdiction/global-required-or-duplicate" });
88
88
  const COUNTRIES = new Set("AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW".split(" "));
89
89
  const VIEWER_REGION_SCHEMA = zod.enum([...COUNTRIES]).describe("Viewer's ISO 3166-1 alpha-2 country, supplied by your integration; not the proxy server's country. EU is not a viewer country.");
90
90
  new Set("AT BE BG HR CY CZ DK EE FI FR DE GR HU IE IT LV LT LU MT NL PL PT RO SK SI ES SE".split(" "));
91
91
  zod.object({
92
92
  region: VIEWER_REGION_SCHEMA.optional().describe("Viewer country. Defaults to the country of the connection reaching CalmLens; proxies should forward the viewer country explicitly."),
93
- ageConfirmed: zod.boolean().optional().describe("Your platform's confirmation that the viewer passed its age check, so age-restricted content may be delivered. Defaults to false. Your platform confirms the viewer's age; CalmLens does not verify this claim. Anyone requesting a public asset's URL can set it, so it is not an access control: to restrict who can load an age-restricted asset, make the asset private and include the claim in a signed URL, whose signature covers it.")
93
+ ageConfirmed: zod.boolean().optional().describe("Your platform's confirmation that the viewer passed its age check, so age-restricted content may be delivered. Defaults to false. Your platform confirms the viewer's age; CalmLens does not verify this claim. Anyone requesting an asset's URL, public or signed, can set it: a signed URL's signature does not cover viewer claims, so the claim is not an access control. To restrict who can load an age-restricted asset, make it private and issue signed URLs only to viewers who passed your age check.")
94
94
  }).strict();
95
- // src/contract/TestRegionalActions-6yfnXdpa.js
95
+ // src/contract/TestRegionalActions-C2mw3ntb.js
96
96
  /**
97
97
  * Marks English text in shared, backend and data modules that the portal shows, so the app's
98
98
  * message catalog (packages/app/vite/messageCatalog.ts) extracts it and the portal can translate it
@@ -395,6 +395,24 @@ const MODERATION_QUALIFIER_INFO = {
395
395
  description: msg("Pornographic content showing or describing sex with an animal or with a dead body, or a sexual act that threatens a person's life or is likely to cause serious injury to the anus, breasts or genitals, including realistic drawn or generated depictions."),
396
396
  exclusions: "Consensual adult content without such an act, including bondage, role play or rough play; non-sexual images of animals, death or injury; reports, education, support or discussion that present no such material."
397
397
  },
398
+ "sexual-strangulation": {
399
+ category: "sexual",
400
+ kind: "harm",
401
+ harmOption: false,
402
+ displayName: msg("Pornographic strangulation or suffocation"),
403
+ description: msg("A pornographic image or video frame showing a person strangling, choking or suffocating another: pressure on the neck from a hand, arm or ligature, or breathing blocked by covering the mouth and nose, smothering or compressing the chest. Realistic staged, generated or computer-made depictions count."),
404
+ exclusions: "A person alone in the image holding their own throat or miming being choked; a hand resting on the shoulder, jaw or chest without gripping the throat; collars and choker jewellery; oral sex, including gagging, without breathing deliberately held off; non-sexual violence, combat sport or medical images; drawings or animation that don't look real; reports, education or support that show no such image.",
405
+ inputs: ["image"]
406
+ },
407
+ "sexual-incest": {
408
+ category: "sexual",
409
+ kind: "harm",
410
+ harmOption: false,
411
+ displayName: msg("Pornographic incest"),
412
+ description: msg("A pornographic image or video frame showing sexual activity between people who are, or are presented as, related as parent, grandparent, child, grandchild, brother, sister, half-brother, half-sister, uncle, aunt, nephew or niece, including by adoption. The relationship can be shown by the image or by its caption, title, dialogue or other accompanying text. Realistic staged, generated or computer-made depictions count."),
413
+ exclusions: "Step, foster and in-law relationships between adults; a family word that is plainly a nickname or fanciful, such as daddy between adult partners; drawings or animation that don't look real; non-sexual family images; reports or discussion that show no such image. Someone presented as under 18 is Sexualised minors.",
414
+ inputs: ["image"]
415
+ },
398
416
  "sexual-minors": {
399
417
  category: "sexual",
400
418
  kind: "harm",
@@ -1098,7 +1116,7 @@ const TEST_REGIONAL_ACTIONS_SCHEMA = zod.array(zod.object({
1098
1116
  "block"
1099
1117
  ])
1100
1118
  }).strict()).max(7).refine((entries) => new Set(entries.map((entry) => entry.region)).size === entries.length, "Choose each region once");
1101
- // src/contract/TestTriggers-DbhsNPdg.js
1119
+ // src/contract/TestTriggers-D29T_R0M.js
1102
1120
  /**
1103
1121
  * The visual encoding of test images (shared by images and video frames), independent of what the
1104
1122
  * bytes mean. An odd N×N grid of square cells fills the image. Its outer ring alternates black and
@@ -1345,7 +1363,8 @@ function paintTestImageGrid(data, palette = [TEST_IMAGE_GRID_NEUTRAL]) {
1345
1363
  /**
1346
1364
  * Reads the bytes a grid carries, or undefined when the image holds no readable grid. The grid
1347
1365
  * may be scaled (also unevenly) and surrounded by a uniform border, such as video letterboxing.
1348
- * Cost is bounded by sampling, not by the image size, so every video frame can be checked.
1366
+ * Cost is bounded by sampling, not by the image size, so every video frame can be checked. Reading
1367
+ * only samples cells: `matchesTestImageGrid` checks that nothing else is in the image.
1349
1368
  */
1350
1369
  function readTestImageGrid({ width, height, rgba }) {
1351
1370
  if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 30 || height < 30 || rgba.length !== width * height * 4) return;
@@ -1401,8 +1420,93 @@ function readTestImageGrid({ width, height, rgba }) {
1401
1420
  let position = 0;
1402
1421
  for (let i = 0; i < Math.max(...lengths); i++) for (const codeword of codewords) if (i < codeword.length) codeword[i] = stream[position++];
1403
1422
  if (!codewords.every(rsDecode)) continue;
1404
- return new Uint8Array(codewords.flatMap((codeword) => [...codeword.subarray(0, codeword.length - 32)]));
1423
+ return {
1424
+ data: new Uint8Array(codewords.flatMap((codeword) => [...codeword.subarray(0, codeword.length - 32)])),
1425
+ cells,
1426
+ left,
1427
+ top,
1428
+ gridWidth,
1429
+ gridHeight
1430
+ };
1431
+ }
1432
+ }
1433
+ /** BT.601 full-range Y, Cb and Cr, as JPEG and WebP store colour. */
1434
+ const ycbcr = (r, g, b) => [
1435
+ .299 * r + .587 * g + .114 * b,
1436
+ 128 - .168736 * r - .331264 * g + .5 * b,
1437
+ 128 + .5 * r - .418688 * g - .081312 * b
1438
+ ];
1439
+ /**
1440
+ * Whether the whole image is the grid `expected` (painted from the bytes `found` read) on a
1441
+ * uniform border: every pixel is opaque and its luma and chroma lie within the tolerances of those
1442
+ * of the repainted cells (or the border) near its place. "Near" is a few pixels, which absorbs the
1443
+ * blur scaling and compression put on cell edges. Damage the reader's error correction repaired,
1444
+ * an overlay and anything drawn in chroma alone all fail.
1445
+ */
1446
+ function matchesTestImageGrid({ width, height, rgba }, found, expected) {
1447
+ const { cells, left, top, gridWidth, gridHeight } = found;
1448
+ if (rgba.length !== width * height * 4 || expected.width % cells) return false;
1449
+ const cellSize = expected.width / cells;
1450
+ if (cellSize < 1 || expected.height !== expected.width) return false;
1451
+ const colours = [];
1452
+ for (let row = 0; row < cells; row++) for (let column = 0; column < cells; column++) {
1453
+ const offset = ((row * cellSize + (cellSize >> 1)) * expected.width + column * cellSize + (cellSize >> 1)) * 4;
1454
+ colours.push(ycbcr(expected.rgba[offset], expected.rgba[offset + 1], expected.rgba[offset + 2]));
1455
+ }
1456
+ const border = ycbcr(rgba[0], rgba[1], rgba[2]);
1457
+ const radius = 2 + Math.ceil(Math.max(gridWidth, gridHeight) / expected.width);
1458
+ const right = left + gridWidth - 1;
1459
+ const bottom = top + gridHeight - 1;
1460
+ const span = (from, to, start, end, size) => {
1461
+ const outside = from < start || to > end;
1462
+ if (to < start || from > end) return {
1463
+ outside,
1464
+ first: 0,
1465
+ last: -1
1466
+ };
1467
+ return {
1468
+ outside,
1469
+ first: Math.max(0, Math.floor((Math.max(from, start) - start) * cells / size)),
1470
+ last: Math.min(cells - 1, Math.floor((Math.min(to, end) - start) * cells / size))
1471
+ };
1472
+ };
1473
+ const columns = Array.from({ length: width }, (_, x) => span(x - radius, x + radius, left, right, gridWidth));
1474
+ const tolerance = [
1475
+ 48,
1476
+ 40,
1477
+ 40
1478
+ ];
1479
+ const low = [
1480
+ 0,
1481
+ 0,
1482
+ 0
1483
+ ];
1484
+ const high = [
1485
+ 0,
1486
+ 0,
1487
+ 0
1488
+ ];
1489
+ const include = (colour) => {
1490
+ for (let channel = 0; channel < 3; channel++) {
1491
+ low[channel] = Math.min(low[channel], colour[channel]);
1492
+ high[channel] = Math.max(high[channel], colour[channel]);
1493
+ }
1494
+ };
1495
+ for (let y = 0; y < height; y++) {
1496
+ const rows = span(y - radius, y + radius, top, bottom, gridHeight);
1497
+ for (let x = 0; x < width; x++) {
1498
+ const offset = (y * width + x) * 4;
1499
+ if (rgba[offset + 3] < 250) return false;
1500
+ const near = columns[x];
1501
+ low.fill(Number.POSITIVE_INFINITY);
1502
+ high.fill(Number.NEGATIVE_INFINITY);
1503
+ if (rows.outside || near.outside) include(border);
1504
+ for (let row = rows.first; row <= rows.last; row++) for (let column = near.first; column <= near.last; column++) include(colours[row * cells + column]);
1505
+ const pixel = ycbcr(rgba[offset], rgba[offset + 1], rgba[offset + 2]);
1506
+ for (let channel = 0; channel < 3; channel++) if (pixel[channel] < low[channel] - tolerance[channel] || pixel[channel] > high[channel] + tolerance[channel]) return false;
1507
+ }
1405
1508
  }
1509
+ return true;
1406
1510
  }
1407
1511
  const ringMatches = (samples) => {
1408
1512
  let black = 0;
@@ -1453,6 +1557,48 @@ function testInputForSignal(signal, kind = "text") {
1453
1557
  }
1454
1558
  }
1455
1559
  const getImageTestCategories = () => [...TEXT_CODE_SIGNALS];
1560
+ /** Each detection list holds at most this many entries; 32 faces fit a test image. */
1561
+ const TEST_DETECTIONS_MAX = 32;
1562
+ /** Box values are integer basis points of the image width and height: 10000 is the full side. */
1563
+ const TEST_DETECTION_BOX_MAX = 1e4;
1564
+ /** Age presets and the range a custom estimate may use. */
1565
+ const TEST_FACE_AGE_PRESETS = {
1566
+ adult: {
1567
+ low: 25,
1568
+ high: 35
1569
+ },
1570
+ minor: {
1571
+ low: 12,
1572
+ high: 16
1573
+ }
1574
+ };
1575
+ const TEST_FACE_AGE_MAX = 120;
1576
+ const basisPoints = zod.number().int().min(0).max(TEST_DETECTION_BOX_MAX);
1577
+ const detectionShape = {
1578
+ box: zod.tuple([
1579
+ basisPoints,
1580
+ basisPoints,
1581
+ basisPoints,
1582
+ basisPoints
1583
+ ]),
1584
+ confidence: zod.number().int().min(0).max(100).optional()
1585
+ };
1586
+ const fitsImage = ({ box: [left, top, width, height] }) => left + width <= 1e4 && top + height <= 1e4;
1587
+ const BOX_MESSAGE = msg("A box must lie inside the image: left + width and top + height are at most 10000.");
1588
+ const ageYears = zod.number().int().min(0).max(120);
1589
+ const TEST_DETECTED_PERSON_SCHEMA = zod.object(detectionShape).strict().refine(fitsImage, BOX_MESSAGE);
1590
+ const TEST_DETECTED_FACE_SCHEMA = zod.object({
1591
+ ...detectionShape,
1592
+ age: zod.union([zod.enum(["adult", "minor"]), zod.object({
1593
+ low: ageYears,
1594
+ high: ageYears
1595
+ }).strict().refine(({ low, high }) => low <= high, msg("An age range's low must not be above its high."))]).optional()
1596
+ }).strict().refine(fitsImage, BOX_MESSAGE);
1597
+ /** Person and face detection results a test image reports instead of running detection. */
1598
+ const TEST_DETECTIONS_SCHEMA = zod.object({
1599
+ people: zod.union([zod.array(TEST_DETECTED_PERSON_SCHEMA).max(32), zod.literal("unavailable")]).optional(),
1600
+ faces: zod.union([zod.array(TEST_DETECTED_FACE_SCHEMA).max(32), zod.literal("unavailable")]).optional()
1601
+ }).strict();
1456
1602
  /** Each row is one qualifying instance. Unselected qualifiers are explicitly absent. */
1457
1603
  const TEST_INPUT_SCHEMA = zod.object({
1458
1604
  regionalActions: TEST_REGIONAL_ACTIONS_SCHEMA.optional(),
@@ -1472,7 +1618,8 @@ const TEST_INPUT_SCHEMA = zod.object({
1472
1618
  code: "custom",
1473
1619
  message: "Choose unique content qualifiers from this category; input-type facts are automatic."
1474
1620
  });
1475
- })).max(128)
1621
+ })).max(128),
1622
+ detections: TEST_DETECTIONS_SCHEMA.optional()
1476
1623
  }).strict().superRefine((scenario, context) => {
1477
1624
  if (scenario.instances.some((instance) => instance.action !== void 0) && scenario.instances.some((instance) => instance.action === void 0)) context.addIssue({
1478
1625
  code: "custom",
@@ -1525,24 +1672,152 @@ const TEST_INPUT_PRESETS = {
1525
1672
  }, {
1526
1673
  category: "harassment",
1527
1674
  qualifiers: ["harassment-threat"]
1528
- }] }
1675
+ }] },
1676
+ oneFace: {
1677
+ instances: [],
1678
+ detections: {
1679
+ people: [{ box: [
1680
+ 2500,
1681
+ 1500,
1682
+ 5e3,
1683
+ 8500
1684
+ ] }],
1685
+ faces: [{ box: [
1686
+ 3500,
1687
+ 2e3,
1688
+ 3e3,
1689
+ 3500
1690
+ ] }]
1691
+ }
1692
+ },
1693
+ noFace: {
1694
+ instances: [],
1695
+ detections: {
1696
+ people: [],
1697
+ faces: []
1698
+ }
1699
+ },
1700
+ adultFace: {
1701
+ instances: [],
1702
+ detections: {
1703
+ people: [{ box: [
1704
+ 2500,
1705
+ 1500,
1706
+ 5e3,
1707
+ 8500
1708
+ ] }],
1709
+ faces: [{
1710
+ box: [
1711
+ 3500,
1712
+ 2e3,
1713
+ 3e3,
1714
+ 3500
1715
+ ],
1716
+ age: "adult"
1717
+ }]
1718
+ }
1719
+ },
1720
+ minorFace: {
1721
+ instances: [],
1722
+ detections: {
1723
+ people: [{ box: [
1724
+ 2500,
1725
+ 1500,
1726
+ 5e3,
1727
+ 8500
1728
+ ] }],
1729
+ faces: [{
1730
+ box: [
1731
+ 3500,
1732
+ 2e3,
1733
+ 3e3,
1734
+ 3500
1735
+ ],
1736
+ age: "minor"
1737
+ }]
1738
+ }
1739
+ },
1740
+ group: {
1741
+ instances: [],
1742
+ detections: {
1743
+ people: [
1744
+ { box: [
1745
+ 500,
1746
+ 2e3,
1747
+ 2800,
1748
+ 8e3
1749
+ ] },
1750
+ { box: [
1751
+ 3600,
1752
+ 2e3,
1753
+ 2800,
1754
+ 8e3
1755
+ ] },
1756
+ { box: [
1757
+ 6700,
1758
+ 2e3,
1759
+ 2800,
1760
+ 8e3
1761
+ ] }
1762
+ ],
1763
+ faces: [
1764
+ { box: [
1765
+ 1200,
1766
+ 2500,
1767
+ 1400,
1768
+ 2e3
1769
+ ] },
1770
+ { box: [
1771
+ 4300,
1772
+ 2500,
1773
+ 1400,
1774
+ 2e3
1775
+ ] },
1776
+ { box: [
1777
+ 7400,
1778
+ 2500,
1779
+ 1400,
1780
+ 2e3
1781
+ ] }
1782
+ ]
1783
+ }
1784
+ }
1529
1785
  };
1530
- const pattern = /<!calmlens-test ([a-f0-9]{32}) ([A-Za-z0-9_-]+)>/g;
1531
- const tag = async (payload, key) => (await require_CryptoUtils_B_x8lMIx.hmacSha256Hex(key, `calmlens-test:v1:${payload}`)).slice(0, 32);
1786
+ /**
1787
+ * A text code: the tag, then the signed payload, base64url of the scenario's canonical JSON. Text
1788
+ * extracted from a document (a PDF, or a Word file converted to one) breaks a code that its layout wrapped: a line break between its parts, after a
1789
+ * hyphen or anywhere in a long payload. Whitespace inside a code is layout, not content, so it is
1790
+ * removed before the signature is checked.
1791
+ */
1792
+ const WHOLE_CODE = /^<!calmlens-\s*test\s+([A-Za-z0-9_\s-]{33,16384})>$/;
1793
+ const tag = async (payload, key) => (await require_CryptoUtils_B_x8lMIx.hmacSha256Hex(key, `calmlens-test:v2:${payload}`)).slice(0, 32);
1794
+ const toBase64Url = (bytes) => btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
1795
+ const fromBase64Url = (text) => Uint8Array.from(atob(text.replaceAll("-", "+").replaceAll("_", "/")), (char) => char.charCodeAt(0));
1796
+ /** The signed bytes: the scenario's canonical JSON (ASCII). */
1797
+ const envelope = (scenario) => new TextEncoder().encode(JSON.stringify(TEST_INPUT_SCHEMA.parse(scenario)));
1532
1798
  async function generateTestTextCode(scenario, key) {
1533
1799
  if (!/^[a-f0-9]{32}$/.test(key)) throw new TypeError("Invalid test input key");
1534
- const payload = btoa(JSON.stringify(TEST_INPUT_SCHEMA.parse(typeof scenario === "string" ? testInputForSignal(scenario) : scenario))).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
1800
+ const payload = toBase64Url(envelope(typeof scenario === "string" ? testInputForSignal(scenario) : scenario));
1535
1801
  if (payload.length > 8e3) throw new RangeError("Test scenario is too large");
1536
1802
  return `<!calmlens-test ${await tag(payload, key)} ${payload}>`;
1537
1803
  }
1804
+ /**
1805
+ * The scenario a text declares when the whole text is one code signed with `key`; surrounding
1806
+ * text, a second code or an altered code all return undefined, so the text is moderated as
1807
+ * ordinary content.
1808
+ */
1538
1809
  async function detectTestTrigger(text, key) {
1539
1810
  if (!/^[a-f0-9]{32}$/.test(key)) return;
1540
- const matches = [...text.matchAll(pattern)];
1541
- if (matches.length !== 1) return;
1542
- const [, signature, payload] = matches[0];
1543
- if (payload.length > 8e3 || !require_CryptoUtils_B_x8lMIx.timingSafeEqual(signature, await tag(payload, key))) return;
1811
+ const match = WHOLE_CODE.exec(text.trim());
1812
+ if (!match) return;
1813
+ const code = match[1].replace(/\s+/g, "");
1814
+ const signature = code.slice(0, 32);
1815
+ const payload = code.slice(32);
1816
+ if (!/^[a-f0-9]{32}$/.test(signature) || !payload || payload.length > 8e3 || !require_CryptoUtils_B_x8lMIx.timingSafeEqual(signature, await tag(payload, key))) return;
1544
1817
  try {
1545
- const parsed = TEST_INPUT_SCHEMA.safeParse(JSON.parse(atob(payload.replaceAll("-", "+").replaceAll("_", "/"))));
1818
+ const json = fromBase64Url(payload);
1819
+ if (json.some((byte) => byte > 127)) return;
1820
+ const parsed = TEST_INPUT_SCHEMA.safeParse(JSON.parse(new TextDecoder().decode(json)));
1546
1821
  return parsed.success ? parsed.data : void 0;
1547
1822
  } catch {
1548
1823
  return;
@@ -1592,32 +1867,41 @@ const TEST_INPUT_CATEGORY_COLORS = {
1592
1867
  ]
1593
1868
  };
1594
1869
  /**
1595
- * The text code's signed bytes as a grid (TestImageGrid.ts): the scenario JSON's length (two
1596
- * bytes, big-endian), the 16-byte tag, then the JSON. The reader rebuilds the text code, so images
1597
- * and text share one verification.
1870
+ * The text code's signed bytes as a grid (TestImageGrid.ts): the signed payload's length (two
1871
+ * bytes, big-endian), the 16-byte tag, then the payload (the scenario JSON). The reader rebuilds
1872
+ * the text code, so images and text share one verification.
1598
1873
  */
1599
1874
  async function paintTestImage(scenario, key) {
1600
1875
  const input = TEST_INPUT_SCHEMA.parse(typeof scenario === "string" ? testInputForSignal(scenario, "image") : scenario);
1601
1876
  const [, signature, payload] = (await generateTestTextCode(input, key)).slice(0, -1).split(" ");
1602
- const json = Uint8Array.from(atob(payload.replaceAll("-", "+").replaceAll("_", "/")), (char) => char.charCodeAt(0));
1603
- const data = new Uint8Array(18 + json.length);
1604
- data.set([json.length >> 8, json.length & 255]);
1877
+ const signed = fromBase64Url(payload);
1878
+ const data = new Uint8Array(18 + signed.length);
1879
+ data.set([signed.length >> 8, signed.length & 255]);
1605
1880
  data.set(signature.match(/../g).map((hex) => Number.parseInt(hex, 16)), 2);
1606
- data.set(json, 18);
1607
- const categories = [...new Set(input.instances.map((instance) => instance.category))];
1608
- return paintTestImageGrid(data, categories.length ? categories.map((category) => TEST_INPUT_CATEGORY_COLORS[category]) : void 0);
1881
+ data.set(signed, 18);
1882
+ return paintTestImageGrid(data, testImagePalette(input));
1609
1883
  }
1610
- const base64Url = (bytes) => btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
1611
- /** The test input a project's test image carries, also after video encoding and resizing. */
1612
- async function detectTestImage(image, key) {
1884
+ const testImagePalette = (input) => {
1885
+ const categories = [...new Set(input.instances.map((instance) => instance.category))];
1886
+ return categories.length ? categories.map((category) => TEST_INPUT_CATEGORY_COLORS[category]) : void 0;
1887
+ };
1888
+ /**
1889
+ * The test input an image declares when the whole image is one of the project's test images,
1890
+ * also after lossy formats and resizing: the grid, optionally on a uniform border. Every pixel
1891
+ * must match the grid repainted from the bytes it carries (TestImageGrid.ts,
1892
+ * `matchesTestImageGrid`), so nothing else can be drawn on or around it.
1893
+ */
1894
+ async function detectTestImage(image, key, { whole = true } = {}) {
1613
1895
  if (!TEST_INPUT_KEY_PATTERN.test(key)) return;
1614
- const data = readTestImageGrid(image);
1615
- if (!data) return;
1896
+ const grid = readTestImageGrid(image);
1897
+ if (!grid) return;
1898
+ const { data } = grid;
1616
1899
  const length = data[0] << 8 | data[1];
1617
- if (18 + length > data.length) return;
1618
- const json = data.subarray(18, 18 + length);
1619
- if (json.some((byte) => byte > 127)) return;
1620
- return detectTestTrigger(`<!calmlens-test ${[...data.subarray(2, 18)].map((byte) => byte.toString(16).padStart(2, "0")).join("")} ${base64Url(json)}>`, key);
1900
+ if (!length || 18 + length > data.length) return;
1901
+ const signed = data.subarray(18, 18 + length);
1902
+ const scenario = await detectTestTrigger(`<!calmlens-test ${[...data.subarray(2, 18)].map((byte) => byte.toString(16).padStart(2, "0")).join("")} ${toBase64Url(signed)}>`, key);
1903
+ if (!scenario || !whole) return scenario;
1904
+ return matchesTestImageGrid(image, grid, paintTestImageGrid(data.subarray(0, 18 + length), testImagePalette(scenario))) ? scenario : void 0;
1621
1905
  }
1622
1906
  Object.defineProperty(exports, "CLASSIFICATION_CATEGORIES", {
1623
1907
  enumerable: true,
@@ -1625,6 +1909,30 @@ Object.defineProperty(exports, "CLASSIFICATION_CATEGORIES", {
1625
1909
  return CLASSIFICATION_CATEGORIES;
1626
1910
  }
1627
1911
  });
1912
+ Object.defineProperty(exports, "TEST_DETECTIONS_MAX", {
1913
+ enumerable: true,
1914
+ get: function() {
1915
+ return TEST_DETECTIONS_MAX;
1916
+ }
1917
+ });
1918
+ Object.defineProperty(exports, "TEST_DETECTION_BOX_MAX", {
1919
+ enumerable: true,
1920
+ get: function() {
1921
+ return TEST_DETECTION_BOX_MAX;
1922
+ }
1923
+ });
1924
+ Object.defineProperty(exports, "TEST_FACE_AGE_MAX", {
1925
+ enumerable: true,
1926
+ get: function() {
1927
+ return TEST_FACE_AGE_MAX;
1928
+ }
1929
+ });
1930
+ Object.defineProperty(exports, "TEST_FACE_AGE_PRESETS", {
1931
+ enumerable: true,
1932
+ get: function() {
1933
+ return TEST_FACE_AGE_PRESETS;
1934
+ }
1935
+ });
1628
1936
  Object.defineProperty(exports, "TEST_INPUT_KEY_PATTERN", {
1629
1937
  enumerable: true,
1630
1938
  get: function() {
@@ -1,5 +1,5 @@
1
- const require_ModerationContextLimits = require("./ModerationContextLimits-2nIv7Zh3.js");
2
- const require_CalmLensAppClient = require("./CalmLensAppClient-NaCxOVlM.js");
1
+ const require_ModerationContextLimits = require("./ModerationContextLimits-ud1xpZRK.js");
2
+ const require_CalmLensAppClient = require("./CalmLensAppClient-DUYMo9PZ.js");
3
3
  // src/contract/PlaceholderHashDecode.js
4
4
  /**
5
5
  * Decodes a ThumbHash to an RGBA image. RGB is not be premultiplied by A.
@@ -307,6 +307,22 @@ const sleep = (ms, signal) => new Promise((resolve) => {
307
307
  resolve();
308
308
  });
309
309
  });
310
+ /** A custom upload is settled once it has a status other than `pending`, or reports none. */
311
+ const checkedCustomUpload = (id, status) => ({
312
+ id,
313
+ status,
314
+ settled: status !== "pending"
315
+ });
316
+ /**
317
+ * An upload preset's upload is settled once its processing is `completed` or `failed`; its
318
+ * moderation status is present only when the preset shows decisions.
319
+ */
320
+ const checkedPresetUpload = ({ id, classification }) => ({
321
+ id,
322
+ status: classification.moderation?.status,
323
+ settled: classification.status === "completed" || classification.status === "failed",
324
+ failed: classification.status === "failed"
325
+ });
310
326
  let nextKey = 0;
311
327
  /**
312
328
  * Uploads files through an upload preset and tracks each one until it has a moderation
@@ -498,12 +514,22 @@ var UploadController = class {
498
514
  });
499
515
  }
500
516
  const deadline = Date.now() + (options.decisionTimeoutMs ?? DEFAULT_DECISION_TIMEOUT_MS);
501
- for (let delay = 1e3; asset.status === "pending" && check && Date.now() < deadline; delay *= 2) {
517
+ for (let delay = 1e3; !asset.settled && check && Date.now() < deadline; delay *= 2) {
502
518
  await sleep(Math.min(delay, Math.max(0, deadline - Date.now())), abort.signal);
503
519
  if (abort.signal.aborted) return;
504
520
  asset = await check(asset.id);
505
521
  }
506
522
  if (abort.signal.aborted) return;
523
+ if (asset.failed) {
524
+ this.#checks.delete(key);
525
+ this.#update(key, {
526
+ stage: "failed",
527
+ progress: null
528
+ });
529
+ const item = this.#find(key);
530
+ if (item) options.onFailed?.(item);
531
+ return;
532
+ }
507
533
  this.#update(key, {
508
534
  stage: "complete",
509
535
  status: asset.status
@@ -540,15 +566,9 @@ var UploadController = class {
540
566
  signal,
541
567
  onProgress
542
568
  });
543
- return {
544
- id: assetId,
545
- status
546
- };
569
+ return checkedCustomUpload(assetId, status);
547
570
  },
548
- retrieve: checkStatus ? async (assetId) => ({
549
- id: assetId,
550
- status: await checkStatus(assetId, { signal })
551
- }) : void 0
571
+ retrieve: checkStatus ? async (assetId) => checkedCustomUpload(assetId, await checkStatus(assetId, { signal })) : void 0
552
572
  };
553
573
  if (!uploadPresetId) throw new require_ModerationContextLimits.CalmLensError(require_ModerationContextLimits.SDK_ERROR_CODES.INVALID_CONFIG, { message: "The uploader needs an uploadPresetId or an upload function" });
554
574
  const options = {
@@ -562,7 +582,7 @@ var UploadController = class {
562
582
  return {
563
583
  create: async () => {
564
584
  const type = file.type || "application/octet-stream";
565
- return client.assets.create({
585
+ return checkedPresetUpload(await client.assets.create({
566
586
  name: file.name,
567
587
  content: isBlob(file) ? {
568
588
  data: file,
@@ -571,9 +591,9 @@ var UploadController = class {
571
591
  uint8Array: new Uint8Array(await file.arrayBuffer()),
572
592
  type
573
593
  }
574
- });
594
+ }));
575
595
  },
576
- retrieve: (assetId) => client.assets.retrieve({ assetId })
596
+ retrieve: async (assetId) => checkedPresetUpload(await client.assets.retrieve({ assetId }))
577
597
  };
578
598
  }
579
599
  async #tokenFor(file, signal) {