calmlens 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +3 -2
  2. package/bin/calmlens.js +594 -88
  3. package/{esm/BrowserUpload-D-NnAN7g.d.ts → cjs/BrowserUpload-B2kmc3Y_.d.ts} +2 -2
  4. package/cjs/{BrowserUpload-CeSwiMo5.js → BrowserUpload-B5IJpb8m.js} +1 -1
  5. package/{esm/CalmLensAppClient-gG16T2py.d.ts → cjs/CalmLensAppClient-CMVh0y5w.d.ts} +1 -1
  6. package/cjs/{CalmLensAppClient-0UVCuNqW.js → CalmLensAppClient-DWClthAd.js} +3 -3
  7. package/cjs/{CalmLensOptionKeys-CYY6elxg.js → CalmLensOptionKeys-DsPvFCox.js} +139 -31
  8. package/cjs/{CalmLensServerClient-nfu6_YEW.js → CalmLensServerClient-B35N3hCo.js} +66 -9
  9. package/cjs/{CalmLensServerClient-BHx3x_nZ.d.ts → CalmLensServerClient-izj412cc.d.ts} +43 -7
  10. package/cjs/{CalmLensTypes-CUB0YYVz.d.ts → CalmLensTypes-SmOCgKI3.d.ts} +858 -70
  11. package/cjs/{Classification-Q5zGpR8l-CEWjnE39.d.ts → Classification-CxRedzgH-C9qlYW_J.d.ts} +35 -0
  12. package/cjs/{Core-Dc3cteU7.js → Core-5Mrihf2l.js} +10 -7
  13. package/{esm/Core-C82YmjjX.d.ts → cjs/Core-Dt_HUNvH.d.ts} +9 -5
  14. package/cjs/{ModerationContextLimits-BxOmeSqq.js → ModerationContextLimits-Bm8DxcJ_.js} +64 -12
  15. package/cjs/{ReactUpload-BK2O3dnK.js → ReactUpload-BJCjlqEb.js} +1 -1
  16. package/cjs/{ReactUpload-DiiXfKvj.d.ts → ReactUpload-Bd7Hea4w.d.ts} +1 -1
  17. package/{esm/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts → cjs/TestTriggers-BJ4B-MXR-D1tGifPU.d.ts} +7 -5
  18. package/cjs/{TestTriggers-BTyXtX0Q-ATuFDhLX.js → TestTriggers-CiFcTHX3-BmfH4J3f.js} +35 -22
  19. package/cjs/{UploadController-DLyiLDTB.js → UploadController-DoD51qnV.js} +2 -2
  20. package/{esm/WebhookPayload-BLT2y_Jy.d.ts → cjs/WebhookPayload-C7KAk3iR.d.ts} +28 -1
  21. package/cjs/app.d.ts +6 -6
  22. package/cjs/app.js +2 -2
  23. package/cjs/elements.d.ts +4 -4
  24. package/cjs/elements.js +4 -4
  25. package/{esm/index-CKRgjV16.d.ts → cjs/index-BJf0y_Uk.d.ts} +3 -3
  26. package/cjs/index.d.ts +5 -5
  27. package/cjs/index.js +1 -1
  28. package/cjs/react-native.d.ts +2 -2
  29. package/cjs/react-native.js +4 -4
  30. package/cjs/react.d.ts +3 -3
  31. package/cjs/react.js +5 -5
  32. package/cjs/server.d.ts +6 -6
  33. package/cjs/server.js +2 -2
  34. package/cjs/test-inputs.d.ts +1 -1
  35. package/cjs/test-inputs.js +13 -13
  36. package/cjs/testing.d.ts +22 -9
  37. package/cjs/testing.js +399 -57
  38. package/cjs/{ui-CTBUxnVp.d.ts → ui-DNXPuzha.d.ts} +2 -2
  39. package/cjs/{ui-CZ8exACq.js → ui-DPLnhovP.js} +3 -3
  40. package/cjs/ui.d.ts +2 -2
  41. package/cjs/ui.js +3 -3
  42. package/cjs/vue.d.ts +5 -5
  43. package/cjs/vue.js +4 -4
  44. package/{cjs/BrowserUpload-D-NnAN7g.d.ts → esm/BrowserUpload-B2kmc3Y_.d.ts} +2 -2
  45. package/esm/{BrowserUpload-i9OhCzMJ.js → BrowserUpload-BheeMat4.js} +1 -1
  46. package/{cjs/CalmLensAppClient-gG16T2py.d.ts → esm/CalmLensAppClient-CMVh0y5w.d.ts} +1 -1
  47. package/esm/{CalmLensAppClient-CK4_Py0c.js → CalmLensAppClient-D51UlnU3.js} +3 -3
  48. package/esm/{CalmLensOptionKeys-BGZlIsT2.js → CalmLensOptionKeys-BmYuSh9G.js} +139 -31
  49. package/esm/{CalmLensServerClient-dAQUcDWb.js → CalmLensServerClient-CJCjmAXh.js} +66 -9
  50. package/esm/{CalmLensServerClient-BHx3x_nZ.d.ts → CalmLensServerClient-izj412cc.d.ts} +43 -7
  51. package/esm/{CalmLensTypes-CUB0YYVz.d.ts → CalmLensTypes-SmOCgKI3.d.ts} +858 -70
  52. package/esm/{Classification-Q5zGpR8l-CEWjnE39.d.ts → Classification-CxRedzgH-C9qlYW_J.d.ts} +35 -0
  53. package/esm/{Core-BxeIud_S.js → Core-5A2CZKsC.js} +10 -7
  54. package/{cjs/Core-C82YmjjX.d.ts → esm/Core-Dt_HUNvH.d.ts} +9 -5
  55. package/esm/{ModerationContextLimits-B6_RalCQ.js → ModerationContextLimits-DeqK3UAt.js} +64 -12
  56. package/esm/{ReactUpload-DiiXfKvj.d.ts → ReactUpload-Bd7Hea4w.d.ts} +1 -1
  57. package/esm/{ReactUpload-DxwVqfX1.js → ReactUpload-OkhH4jXm.js} +1 -1
  58. package/{cjs/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts → esm/TestTriggers-BJ4B-MXR-D1tGifPU.d.ts} +7 -5
  59. package/esm/{TestTriggers-BTyXtX0Q-GRB9jQwo.js → TestTriggers-CiFcTHX3-BK2-sgOC.js} +35 -22
  60. package/esm/{UploadController-D9Z-h00Q.js → UploadController-BssSSy8Y.js} +2 -2
  61. package/{cjs/WebhookPayload-BLT2y_Jy.d.ts → esm/WebhookPayload-C7KAk3iR.d.ts} +28 -1
  62. package/esm/app.d.ts +6 -6
  63. package/esm/app.js +2 -2
  64. package/esm/elements.d.ts +4 -4
  65. package/esm/elements.js +4 -4
  66. package/{cjs/index-CKRgjV16.d.ts → esm/index-BJf0y_Uk.d.ts} +3 -3
  67. package/esm/index.d.ts +5 -5
  68. package/esm/index.js +1 -1
  69. package/esm/react-native.d.ts +2 -2
  70. package/esm/react-native.js +4 -4
  71. package/esm/react.d.ts +3 -3
  72. package/esm/react.js +5 -5
  73. package/esm/server.d.ts +6 -6
  74. package/esm/server.js +2 -2
  75. package/esm/test-inputs.d.ts +1 -1
  76. package/esm/test-inputs.js +1 -1
  77. package/esm/testing.d.ts +22 -9
  78. package/esm/testing.js +393 -51
  79. package/esm/{ui-Cr7s6JHm.js → ui-CZVG46z9.js} +3 -3
  80. package/esm/{ui-CTBUxnVp.d.ts → ui-DNXPuzha.d.ts} +2 -2
  81. package/esm/ui.d.ts +2 -2
  82. package/esm/ui.js +3 -3
  83. package/esm/vue.d.ts +5 -5
  84. package/esm/vue.js +4 -4
  85. package/package.json +2 -2
package/bin/calmlens.js CHANGED
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  // src/cli/index.ts
3
+ import { readFile as readFile2 } from "node:fs/promises";
3
4
  import { parseArgs } from "node:util";
4
5
  // package.json
5
- var version = "0.21.0";
6
+ var version = "0.23.0";
6
7
 
7
8
  // src/contract/ModerationCategories-CHFRoeWV.js
8
9
  var CLASSIFICATION_CATEGORIES = [
@@ -59,12 +60,14 @@ var API_ERROR_CODES = {
59
60
  PERMISSION_DENIED: "auth/permission-denied",
60
61
  UPLOAD_TOO_LARGE: "upload/too-large",
61
62
  DOCUMENT_TOO_MANY_ITEMS: "document/too-many-items",
63
+ MEDIA_DURATION_LIMIT: "media/duration-limit",
62
64
  INVALID_IMAGE: "image/invalid",
63
65
  IMAGE_TOO_LARGE: "image/too-large",
64
66
  FREE_UPLOADS_EXHAUSTED: "usage/free-uploads-exhausted",
65
67
  UPLOADS_PAUSED: "usage/uploads-paused",
66
68
  UNSUPPORTED_UPLOAD_TYPE: "upload/unsupported-type",
67
69
  INVALID_UPLOAD_PAYLOAD: "upload-payload/invalid",
70
+ UPLOAD_OPTIONS_IN_QUERY: "upload/options-in-query",
68
71
  USE_UPLOAD_PART: "upload/use-upload-part",
69
72
  UPLOAD_NOT_OPEN: "upload/not-open",
70
73
  INVALID_UPLOAD_PART_NUMBER: "upload-part/invalid-number",
@@ -121,6 +124,14 @@ var API_ERROR_CODES = {
121
124
  UPLOAD_PRESET_DAILY_LIMIT_REACHED: "upload-preset/daily-limit-reached",
122
125
  UPLOAD_PRESET_ORIGIN_NOT_ALLOWED: "upload-preset/origin-not-allowed",
123
126
  UPLOAD_PRESET_FIELD_NOT_ALLOWED: "upload-preset/field-not-allowed",
127
+ UPLOAD_PRESET_REVISION_CONFLICT: "upload-preset/revision-conflict",
128
+ UPLOAD_PRESET_KEY_TAKEN: "upload-preset/key-taken",
129
+ UPLOAD_PRESET_DAILY_LIMIT_REQUIRED: "upload-preset/daily-limit-required",
130
+ UPLOAD_PRESET_INVALID_FOLDER: "upload-preset/invalid-folder",
131
+ UPLOAD_PRESET_INVALID_POLICY: "upload-preset/invalid-policy",
132
+ PROJECT_SETTINGS_REVISION_CONFLICT: "project-settings/revision-conflict",
133
+ SEARCH_ESTIMATE_CHANGED: "search/estimate-changed",
134
+ METADATA_FIELD_NOT_FOUND: "metadata-field/not-found",
124
135
  UPLOAD_TOKEN_INVALID: "upload-token/invalid",
125
136
  UPLOAD_TOKEN_EXPIRED: "upload-token/expired",
126
137
  UPLOAD_TOKEN_USED: "upload-token/used",
@@ -185,6 +196,9 @@ class CalmLensError extends Error {
185
196
  static [Symbol.hasInstance](value) {
186
197
  return CalmLensError.isCalmLensError(value);
187
198
  }
199
+ isLocal() {
200
+ return this.status === undefined;
201
+ }
188
202
  isNotFound() {
189
203
  return this.status === 404;
190
204
  }
@@ -729,20 +743,6 @@ var TRANSFORM_OPTIONS_SCHEMA = {
729
743
  blur: {
730
744
  type: "number"
731
745
  },
732
- redact: {
733
- type: "object",
734
- properties: {
735
- text: {
736
- type: "boolean"
737
- },
738
- personalInformation: {
739
- type: "boolean"
740
- },
741
- faces: {
742
- type: "boolean"
743
- }
744
- }
745
- },
746
746
  border: {
747
747
  type: "object",
748
748
  properties: {
@@ -958,6 +958,9 @@ var validateServerClientOptions = (options) => {
958
958
  if (!options.apiKey || typeof options.apiKey !== "string") {
959
959
  throw invalidConfig("API key is required");
960
960
  }
961
+ if (!/^[\x21-\x7e]+$/.test(options.apiKey)) {
962
+ throw invalidConfig("API key must be printable ASCII without spaces");
963
+ }
961
964
  if (!options.projectId)
962
965
  throw invalidConfig("Project ID is required");
963
966
  configPathSegment(options.projectId, "Project ID");
@@ -1519,7 +1522,7 @@ var splitsIntoParts = (content, partSizeBytes) => {
1519
1522
  };
1520
1523
  var DEFAULT_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
1521
1524
  var toBodyBytes = (value) => value.buffer instanceof ArrayBuffer ? value : Uint8Array.from(value);
1522
- var toRawUploadBody = (payload) => {
1525
+ var toUploadData = (payload) => {
1523
1526
  const data = assetToData(payload);
1524
1527
  if (data instanceof Response) {
1525
1528
  if (!data.body) {
@@ -1529,18 +1532,87 @@ var toRawUploadBody = (payload) => {
1529
1532
  }
1530
1533
  return data.body;
1531
1534
  }
1532
- if (data instanceof ArrayBuffer || data instanceof Blob) {
1535
+ if (data instanceof Blob)
1533
1536
  return data;
1534
- }
1535
- if ("getReader" in data) {
1537
+ if (data instanceof ArrayBuffer)
1538
+ return new Uint8Array(data);
1539
+ if ("getReader" in data)
1536
1540
  return data;
1537
- }
1538
1541
  return toBodyBytes(data);
1539
1542
  };
1543
+ var toRawUploadBody = (payload) => toUploadData(payload);
1544
+ var textEncoder = new TextEncoder;
1545
+ var toUploadForm = (options, payload) => {
1546
+ const boundary = `calmlens-${randomUuid()}`;
1547
+ const head = `--${boundary}\r
1548
+ Content-Disposition: form-data; name="options"\r
1549
+ Content-Type: application/json\r
1550
+ \r
1551
+ ${JSON.stringify(options)}\r
1552
+ --${boundary}\r
1553
+ Content-Disposition: form-data; name="file"\r
1554
+ Content-Type: ${payload.type.replace(/[\r\n]/g, "")}\r
1555
+ \r
1556
+ `;
1557
+ const tail = `\r
1558
+ --${boundary}--\r
1559
+ `;
1560
+ const contentType = `multipart/form-data; boundary=${boundary}`;
1561
+ const data = toUploadData(payload);
1562
+ if (data instanceof Blob)
1563
+ return { body: new Blob([head, data, tail]), contentType };
1564
+ const headBytes = textEncoder.encode(head);
1565
+ const tailBytes = textEncoder.encode(tail);
1566
+ if (data instanceof Uint8Array) {
1567
+ const body = new Uint8Array(headBytes.length + data.length + tailBytes.length);
1568
+ body.set(headBytes);
1569
+ body.set(data, headBytes.length);
1570
+ body.set(tailBytes, headBytes.length + data.length);
1571
+ return { body, contentType };
1572
+ }
1573
+ const reader = data.getReader();
1574
+ let stage = "head";
1575
+ const body = new ReadableStream({
1576
+ async pull(controller) {
1577
+ if (stage === "head") {
1578
+ stage = "file";
1579
+ controller.enqueue(headBytes);
1580
+ return;
1581
+ }
1582
+ if (stage === "done")
1583
+ return;
1584
+ const { done, value } = await reader.read();
1585
+ if (!done) {
1586
+ if (value.byteLength)
1587
+ controller.enqueue(value);
1588
+ return;
1589
+ }
1590
+ stage = "done";
1591
+ controller.enqueue(tailBytes);
1592
+ controller.close();
1593
+ },
1594
+ cancel: (reason) => reader.cancel(reason)
1595
+ });
1596
+ return { body, contentType };
1597
+ };
1598
+ var uploadFields = (options) => Object.fromEntries(UPLOAD_OPTION_KEYS.flatMap((key) => options[key] === undefined || options[key] === null ? [] : [[key, options[key]]]));
1599
+ var UPLOAD_OPTION_KEYS = [
1600
+ "name",
1601
+ "description",
1602
+ "processingOptions",
1603
+ "visibility",
1604
+ "metadata",
1605
+ "tags",
1606
+ "authorId",
1607
+ "context",
1608
+ "externalId",
1609
+ "externalUrl",
1610
+ "folderId",
1611
+ "uploadPresetId"
1612
+ ];
1540
1613
  var setOptionalQueryValue = (params, key, value) => {
1541
- if (value !== undefined && value !== null) {
1542
- params.set(key, typeof value === "string" ? value : JSON.stringify(value));
1543
- }
1614
+ if (value !== undefined && value !== null)
1615
+ params.set(key, String(value));
1544
1616
  };
1545
1617
  var assertValidUploadMimeType = (mimeType) => {
1546
1618
  if (!isAcceptedUploadMimeType(mimeType)) {
@@ -1735,50 +1807,51 @@ class CalmLensConnection {
1735
1807
  deadline: "body"
1736
1808
  });
1737
1809
  }
1738
- upload(url, payload, headers, idempotencyKey) {
1810
+ upload(url, body, headers, idempotencyKey, text) {
1739
1811
  return this.transport.json({
1740
1812
  method: "POST",
1741
1813
  url,
1742
1814
  headers,
1743
- body: toRawUploadBody(payload),
1815
+ body,
1744
1816
  idempotencyKey,
1745
- timeoutMs: isTextPayload(payload) ? this.timeoutMs : this.options.uploadTimeoutMs,
1817
+ timeoutMs: text ? this.timeoutMs : this.options.uploadTimeoutMs,
1746
1818
  deadline: "body",
1747
1819
  fetch: this.options.uploadFetch
1748
1820
  });
1749
1821
  }
1750
- submitRawUpload(uploadsPath, options, wait, authHeaders = {}) {
1751
- const query = new URLSearchParams;
1752
- query.set("name", options.name);
1753
- query.set("wait", String(wait));
1754
- setOptionalQueryValue(query, "description", options.description);
1755
- setOptionalQueryValue(query, "processingOptions", options.processingOptions);
1756
- setOptionalQueryValue(query, "visibility", options.visibility);
1757
- setOptionalQueryValue(query, "metadata", options.metadata);
1758
- setOptionalQueryValue(query, "tags", options.tags);
1759
- setOptionalQueryValue(query, "authorId", options.authorId);
1760
- setOptionalQueryValue(query, "context", options.context);
1761
- setOptionalQueryValue(query, "externalId", options.externalId);
1762
- setOptionalQueryValue(query, "externalUrl", options.externalUrl);
1763
- setOptionalQueryValue(query, "folderId", options.folderId);
1764
- setOptionalQueryValue(query, "uploadPresetId", options.uploadPresetId);
1822
+ submitUpload(uploadsPath, options, wait, authHeaders = {}) {
1765
1823
  const isMultipart = "part" in options;
1766
1824
  const payload = isMultipart ? options.part : options.content;
1825
+ const multipartOptions = options;
1826
+ const idempotencyKey = options.idempotencyKey ?? newIdempotencyKey();
1827
+ const fields = uploadFields(options);
1828
+ if (isTextPayload(payload)) {
1829
+ const { sizeInBytes: _size, ...text } = payload;
1830
+ const body = isMultipart ? {
1831
+ ...fields,
1832
+ part: text,
1833
+ ...multipartOptions.sizeInBytes === undefined ? {} : { sizeInBytes: multipartOptions.sizeInBytes },
1834
+ ...multipartOptions.totalSizeInBytes === undefined ? {} : { totalSizeInBytes: multipartOptions.totalSizeInBytes }
1835
+ } : { ...fields, content: text };
1836
+ return this.upload(this.url(uploadsPath, { wait }), JSON.stringify(body), { ...authHeaders, "Content-Type": "application/json" }, idempotencyKey, true);
1837
+ }
1838
+ const query = new URLSearchParams;
1839
+ query.set("wait", String(wait));
1767
1840
  query.set("contentType", payload.type);
1768
1841
  setOptionalQueryValue(query, "sizeInBytes", payload.sizeInBytes ?? getAssetPayloadByteLength(payload));
1769
1842
  if (isMultipart) {
1770
1843
  const part = payload;
1771
- const multipartOptions = options;
1772
1844
  query.set("partNumber", String(part.partNumber ?? 1));
1773
1845
  query.set("isFinal", String(part.isFinal ?? false));
1774
1846
  setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? multipartOptions.sizeInBytes);
1775
1847
  setOptionalQueryValue(query, "totalSizeInBytes", multipartOptions.totalSizeInBytes);
1776
1848
  }
1777
- return this.upload(this.url(`${uploadsPath}?${query}`), payload, {
1849
+ const form = toUploadForm(fields, payload);
1850
+ return this.upload(this.url(`${uploadsPath}?${query}`), form.body, {
1778
1851
  ...authHeaders,
1779
- "Content-Type": payload.type,
1852
+ "Content-Type": form.contentType,
1780
1853
  "X-CalmLens-Upload": isMultipart ? "part" : "content"
1781
- }, options.idempotencyKey ?? newIdempotencyKey());
1854
+ }, idempotencyKey, false);
1782
1855
  }
1783
1856
  get partSizeBytes() {
1784
1857
  return this.options.partSizeBytes ?? DEFAULT_PART_SIZE_BYTES;
@@ -1795,7 +1868,7 @@ class CalmLensConnection {
1795
1868
  const count = Math.ceil(source.size / partSize);
1796
1869
  const key = idempotencyKey ?? newIdempotencyKey();
1797
1870
  const part = (partNumber) => source.slice((partNumber - 1) * partSize, Math.min(partNumber * partSize, source.size));
1798
- const first = await this.submitRawUpload(uploadsPath, {
1871
+ const first = await this.submitUpload(uploadsPath, {
1799
1872
  ...fields,
1800
1873
  part: { ...part(1), type: content.type, partNumber: 1, isFinal: false },
1801
1874
  totalSizeInBytes: source.size,
@@ -1844,7 +1917,7 @@ class CalmLensConnection {
1844
1917
  if (wait !== undefined)
1845
1918
  query.set("wait", String(wait));
1846
1919
  setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? getAssetPayloadByteLength(part));
1847
- return this.upload(this.url(`${partPath}?${query}`), part, { ...authHeaders, "X-CalmLens-Upload": "part" }, idempotencyKey ?? newIdempotencyKey());
1920
+ return this.upload(this.url(`${partPath}?${query}`), toRawUploadBody(part), { ...authHeaders, "X-CalmLens-Upload": "part" }, idempotencyKey ?? newIdempotencyKey(), isTextPayload(part));
1848
1921
  }
1849
1922
  }
1850
1923
 
@@ -1897,6 +1970,9 @@ var SERVER_OPTION_KEYS = {
1897
1970
  "lenses.list": ["cursor", "pageSize", "sort"],
1898
1971
  "lenses.retrieve": ["lensId"],
1899
1972
  "lenses.update": ["active", "description", "lensId", "name", "transform", "type"],
1973
+ "metadataFields.delete": ["fieldId", "revision"],
1974
+ "metadataFields.ensure": ["fields", "revision"],
1975
+ "metadataFields.list": [],
1900
1976
  "policies.assign": ["policyId"],
1901
1977
  "policies.create": ["description", "name", "presetId", "settings"],
1902
1978
  "policies.delete": ["policyId"],
@@ -1908,7 +1984,13 @@ var SERVER_OPTION_KEYS = {
1908
1984
  "policies.setAutomaticUpdates": ["enabled", "policyId", "presetVersion", "revision"],
1909
1985
  "policies.update": ["description", "name", "policyId", "revision", "settings"],
1910
1986
  "policies.upgrade": ["policyId", "presetVersion", "revision"],
1911
- "text.classify": ["authorId", "context", "description", "externalId", "externalUrl", "folderId", "metadata", "name", "processingOptions", "tags", "text", "uploadPresetId", "visibility"]
1987
+ "projectSettings.get": [],
1988
+ "projectSettings.update": ["revision", "searchIndexingBudgetUnits", "settings"],
1989
+ "text.classify": ["authorId", "context", "description", "externalId", "externalUrl", "folderId", "metadata", "name", "processingOptions", "tags", "text", "uploadPresetId", "visibility"],
1990
+ "uploadPresets.delete": ["uploadPresetId"],
1991
+ "uploadPresets.ensure": ["uploadPresets"],
1992
+ "uploadPresets.iterate": ["cursor", "pageSize", "sort"],
1993
+ "uploadPresets.list": ["cursor", "pageSize", "sort"]
1912
1994
  };
1913
1995
  var NULLABLE_OPTION_KEYS = {
1914
1996
  "assets.classify": ["authorId", "context", "description", "externalId", "folderId", "metadata", "processingOptions", "tags", "uploadPresetId", "visibility"],
@@ -2047,7 +2129,7 @@ var getEnsureLensCacheKey = (options) => stringifyJsonCanonical({
2047
2129
  name: options.name,
2048
2130
  description: options.description ?? null,
2049
2131
  type: options.type,
2050
- active: options.active,
2132
+ active: options.active ?? true,
2051
2133
  transform: options.transform ?? null
2052
2134
  });
2053
2135
  var requireId = (value, name) => encodePathSegment(value, name);
@@ -2071,6 +2153,7 @@ var inspectSymbol = Symbol.for("nodejs.util.inspect.custom");
2071
2153
 
2072
2154
  class CalmLensServerClient {
2073
2155
  #apiKey;
2156
+ #options;
2074
2157
  #settings;
2075
2158
  #lenses;
2076
2159
  #connection;
@@ -2084,6 +2167,7 @@ class CalmLensServerClient {
2084
2167
  }
2085
2168
  const { apiKey, ...rest } = options;
2086
2169
  this.#apiKey = apiKey;
2170
+ this.#options = rest;
2087
2171
  this.#settings = {
2088
2172
  ...resolveConnectionOptions(rest),
2089
2173
  cdnBaseUrl: (rest.cdnBaseUrl ?? getMockHooks(rest)?.defaultCdnBaseUrl ?? DEFAULT_CDN_BASE_URL).replace(/\/+$/, "")
@@ -2093,7 +2177,7 @@ class CalmLensServerClient {
2093
2177
  }
2094
2178
  withRequestOptions(options) {
2095
2179
  validateRequestOptions(options);
2096
- return new CalmLensServerClient({ ...this.#settings, ...options, apiKey: this.#apiKey }, this.#lenses);
2180
+ return new CalmLensServerClient({ ...this.#options, ...options, apiKey: this.#apiKey }, this.#lenses);
2097
2181
  }
2098
2182
  [inspectSymbol]() {
2099
2183
  const { projectId, baseUrl } = this.#settings;
@@ -2122,7 +2206,7 @@ class CalmLensServerClient {
2122
2206
  }));
2123
2207
  }
2124
2208
  if ("content" in body || "part" in body) {
2125
- return expectAsset(await this.#connection.submitRawUpload(uploadsPath, body, wait));
2209
+ return expectAsset(await this.#connection.submitUpload(uploadsPath, body, wait));
2126
2210
  }
2127
2211
  const { idempotencyKey, ...fields } = body;
2128
2212
  const data = await this.#connection.json("POST", uploadsPath, {
@@ -2440,6 +2524,44 @@ class CalmLensServerClient {
2440
2524
  })
2441
2525
  };
2442
2526
  }
2527
+ get uploadPresets() {
2528
+ return {
2529
+ list: async (options = {}) => this.request("GET", `${this.projectPath}/upload-presets`, {
2530
+ query: checked("uploadPresets.list", options)
2531
+ }),
2532
+ iterate: (options = {}) => {
2533
+ checked("uploadPresets.iterate", options);
2534
+ return this.iteratePages((cursor) => this.uploadPresets.list({ ...options, cursor }));
2535
+ },
2536
+ ensure: async (options) => this.request("PUT", `${this.projectPath}/upload-presets`, {
2537
+ body: checked("uploadPresets.ensure", options)
2538
+ }),
2539
+ delete: async (options) => {
2540
+ const { uploadPresetId } = checked("uploadPresets.delete", options);
2541
+ await this.request("DELETE", `/upload-presets/${requireId(uploadPresetId, "Upload preset ID")}`);
2542
+ }
2543
+ };
2544
+ }
2545
+ get projectSettings() {
2546
+ return {
2547
+ get: async () => this.request("GET", `${this.projectPath}/settings`),
2548
+ update: async (options) => this.request("PUT", `${this.projectPath}/settings`, {
2549
+ body: checked("projectSettings.update", options)
2550
+ })
2551
+ };
2552
+ }
2553
+ get metadataFields() {
2554
+ return {
2555
+ list: async () => this.request("GET", `${this.projectPath}/metadata-fields`),
2556
+ ensure: async (options) => this.request("PUT", `${this.projectPath}/metadata-fields`, {
2557
+ body: checked("metadataFields.ensure", options)
2558
+ }),
2559
+ delete: async (options) => {
2560
+ const { fieldId, ...query } = checked("metadataFields.delete", options);
2561
+ await this.request("DELETE", `${this.projectPath}/metadata-fields/${requireId(fieldId, "Metadata field ID")}`, { query });
2562
+ }
2563
+ };
2564
+ }
2443
2565
  get lenses() {
2444
2566
  const lensPath = (lensId) => `/lenses/${requireId(lensId, "Lens ID")}`;
2445
2567
  const forget = (matches) => {
@@ -7195,63 +7317,63 @@ function superRefine(fn, params) {
7195
7317
  return _superRefine(fn, params);
7196
7318
  }
7197
7319
 
7198
- // src/contract/Jurisdiction-DnnDdNKC.js
7320
+ // src/contract/Jurisdiction-CtB_d_2M.js
7199
7321
  var JURISDICTIONS = {
7200
7322
  global: {
7201
7323
  name: "Global",
7202
7324
  ageCheckStandard: "any",
7203
- optIn: false
7325
+ optional: false
7204
7326
  },
7205
7327
  DE: {
7206
7328
  name: "Germany",
7207
7329
  ageCheckStandard: "any",
7208
- optIn: false
7330
+ optional: false
7209
7331
  },
7210
7332
  AT: {
7211
7333
  name: "Austria",
7212
7334
  ageCheckStandard: "any",
7213
- optIn: false
7335
+ optional: false
7214
7336
  },
7215
7337
  FR: {
7216
7338
  name: "France",
7217
7339
  ageCheckStandard: "any",
7218
- optIn: false
7340
+ optional: false
7219
7341
  },
7220
7342
  GB: {
7221
7343
  name: "United Kingdom",
7222
7344
  ageCheckStandard: "verified",
7223
- optIn: false
7345
+ optional: false
7224
7346
  },
7225
7347
  EU: {
7226
7348
  name: "European Union",
7227
7349
  ageCheckStandard: "verified",
7228
- optIn: true
7350
+ optional: true
7229
7351
  },
7230
7352
  AU: {
7231
7353
  name: "Australia",
7232
7354
  ageCheckStandard: "verified",
7233
- optIn: false
7355
+ optional: false
7234
7356
  },
7235
7357
  BR: {
7236
7358
  name: "Brazil",
7237
7359
  ageCheckStandard: "verified",
7238
- optIn: false
7360
+ optional: false
7239
7361
  }
7240
7362
  };
7241
7363
  var JURISDICTION_SCHEMA = _enum(Object.keys(JURISDICTIONS));
7242
- Object.keys(JURISDICTIONS).filter((code) => !JURISDICTIONS[code].optIn);
7243
- var OPT_IN_JURISDICTIONS = Object.keys(JURISDICTIONS).filter((code) => JURISDICTIONS[code].optIn);
7244
- _enum(OPT_IN_JURISDICTIONS).array().refine((codes) => new Set(codes).size === codes.length, { message: "jurisdiction/duplicate" });
7364
+ Object.keys(JURISDICTIONS).filter((code) => !JURISDICTIONS[code].optional);
7365
+ var OPTIONAL_JURISDICTIONS = Object.keys(JURISDICTIONS).filter((code) => JURISDICTIONS[code].optional);
7366
+ _enum(OPTIONAL_JURISDICTIONS).array().refine((codes) => new Set(codes).size === codes.length, { message: "jurisdiction/duplicate" });
7245
7367
  var SERVED_JURISDICTIONS_SCHEMA = JURISDICTION_SCHEMA.array().min(1).refine((regions) => regions.includes("global") && new Set(regions).size === regions.length, { message: "jurisdiction/global-required-or-duplicate" });
7246
7368
  var 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(" "));
7247
7369
  var VIEWER_REGION_SCHEMA = _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.");
7248
7370
  var EU_COUNTRIES2 = 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(" "));
7249
7371
  var VIEWER_CLAIMS_SCHEMA = object({
7250
7372
  region: VIEWER_REGION_SCHEMA.optional().describe("Viewer country. Defaults to the country of the connection reaching CalmLens; proxies should forward the viewer country explicitly."),
7251
- ageConfirmed: boolean2().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.")
7373
+ ageConfirmed: boolean2().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. Viewer claims are assertions from your application; CalmLens doesn't verify them. To restrict who can load an age-restricted asset, make it private and issue signed URLs only to viewers who passed your age check.")
7252
7374
  }).strict();
7253
7375
 
7254
- // src/contract/TestRegionalActions-DPNhFf9c.js
7376
+ // src/contract/TestRegionalActions-DUzwPr1a.js
7255
7377
  var msg = (text) => text;
7256
7378
  var MODERATION_QUALIFIER_INFO = {
7257
7379
  "sexual-pornographic-media": {
@@ -7661,6 +7783,13 @@ var MODERATION_QUALIFIER_INFO = {
7661
7783
  description: msg("Qualifying content clearly attributed to an invented character, fictional story, game, illustration, generated image or reenacted scene."),
7662
7784
  exclusions: "Unclear fictional context, and a real-world threat or actionable harmful request presented as fiction."
7663
7785
  },
7786
+ "sexual-artistic": {
7787
+ category: "sexual",
7788
+ kind: "context",
7789
+ displayName: msg("Artwork"),
7790
+ description: msg("Qualifying content that is a work of art presented as art, such as a painting, sculpture, print, poem or stage or film scene, or a critic, guide or lecturer talking about one, and not made to arouse."),
7791
+ exclusions: "Content meant to arouse, whatever it is called; pornography, erotic illustration, hentai and generated images; photographs labelled as art; adult content promotion."
7792
+ },
7664
7793
  "sexual-support-prevention": {
7665
7794
  category: "sexual",
7666
7795
  kind: "context",
@@ -8269,7 +8398,7 @@ var TEST_REGIONAL_ACTIONS_SCHEMA = array(object({
8269
8398
  ])
8270
8399
  }).strict()).max(7).refine((entries) => new Set(entries.map((entry) => entry.region)).size === entries.length, "Choose each region once");
8271
8400
 
8272
- // src/contract/TestTriggers-BTyXtX0Q.js
8401
+ // src/contract/TestTriggers-CiFcTHX3.js
8273
8402
  var TEST_IMAGE_GRID_LEVELS = [
8274
8403
  72,
8275
8404
  128,
@@ -8316,7 +8445,10 @@ function testInputForSignal(signal, kind = "text") {
8316
8445
  case "sexual.adult":
8317
8446
  return kind === "image" ? TEST_INPUT_PRESETS.adultImage : TEST_INPUT_PRESETS.adultText;
8318
8447
  case "hate.regional-symbol":
8319
- return TEST_INPUT_PRESETS.germany;
8448
+ return { instances: [{
8449
+ category: "hate",
8450
+ qualifiers: ["hate-symbol", "hate-nazi-symbols-public-display"]
8451
+ }] };
8320
8452
  case "sexual.involving-minors":
8321
8453
  return { instances: [{
8322
8454
  category: "sexual",
@@ -8425,10 +8557,13 @@ var TEST_INPUT_PRESETS = {
8425
8557
  }
8426
8558
  ]
8427
8559
  },
8428
- germany: { instances: [{
8429
- category: "hate",
8430
- qualifiers: ["hate-symbol", "hate-nazi-symbols-public-display"]
8431
- }] },
8560
+ germany: {
8561
+ instances: [],
8562
+ regionalActions: [{
8563
+ region: "DE",
8564
+ action: "block"
8565
+ }]
8566
+ },
8432
8567
  mixed: { instances: [{
8433
8568
  category: "harassment",
8434
8569
  qualifiers: ["harassment-abuse", "harassment-documentary"]
@@ -8557,6 +8692,302 @@ async function generateTestTextCode(scenario, key) {
8557
8692
  throw new RangeError("Test scenario is too large");
8558
8693
  return `<!calmlens-test ${await tag(payload, key)} ${payload}>`;
8559
8694
  }
8695
+ // src/cli/configuration.ts
8696
+ class ConfigurationError extends Error {
8697
+ }
8698
+ var SECTIONS = ["policies", "policy", "uploadPresets", "lenses", "metadataFields", "settings"];
8699
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
8700
+ var parseConfiguration = (text, source = "calmlens.config.json") => {
8701
+ let value;
8702
+ try {
8703
+ value = JSON.parse(text);
8704
+ } catch (error) {
8705
+ throw new ConfigurationError(`${source} isn't valid JSON: ${error.message}`);
8706
+ }
8707
+ if (!isObject2(value))
8708
+ throw new ConfigurationError(`${source} must hold a JSON object.`);
8709
+ for (const key of Object.keys(value))
8710
+ if (key !== "$schema" && !SECTIONS.includes(key))
8711
+ throw new ConfigurationError(`${source} has an unknown section "${key}". Use ${SECTIONS.join(", ")}.`);
8712
+ for (const section of ["policies", "uploadPresets", "lenses", "metadataFields", "settings"]) {
8713
+ if (value[section] === undefined)
8714
+ continue;
8715
+ if (!isObject2(value[section]))
8716
+ throw new ConfigurationError(`${source}: "${section}" must be an object.`);
8717
+ if (section === "settings")
8718
+ continue;
8719
+ for (const [name, item] of Object.entries(value[section]))
8720
+ if (!isObject2(item))
8721
+ throw new ConfigurationError(`${source}: ${section} "${name}" must be an object.`);
8722
+ }
8723
+ if (value.policy !== undefined && typeof value.policy !== "string")
8724
+ throw new ConfigurationError(`${source}: "policy" must be a policy name.`);
8725
+ const config = value;
8726
+ for (const [name, policy] of Object.entries(config.policies ?? {}))
8727
+ if (!policy.presetId && !policy.settings)
8728
+ throw new ConfigurationError(`${source}: policy "${name}" needs "presetId", "settings" or both.`);
8729
+ return config;
8730
+ };
8731
+ var collect = async (items) => {
8732
+ const all = [];
8733
+ for await (const item of items)
8734
+ all.push(item);
8735
+ return all;
8736
+ };
8737
+ var readConfigurationState = async (client, config) => {
8738
+ const presetsNamePolicies = Object.values(config.uploadPresets ?? {}).some((preset) => preset.policy !== undefined);
8739
+ const [policies, assignedPolicy, uploadPresets, lenses, metadataFields, settings] = await Promise.all([
8740
+ config.policies || config.policy !== undefined || presetsNamePolicies ? collect(client.policies.iterate()) : [],
8741
+ config.policy !== undefined ? client.policies.retrieveAssigned() : undefined,
8742
+ config.uploadPresets ? collect(client.uploadPresets.iterate()) : [],
8743
+ config.lenses ? collect(client.lenses.iterate()) : [],
8744
+ config.metadataFields ? client.metadataFields.list() : undefined,
8745
+ config.settings ? client.projectSettings.get() : undefined
8746
+ ]);
8747
+ return {
8748
+ policies,
8749
+ assignedPolicy,
8750
+ uploadPresets,
8751
+ lenses,
8752
+ metadataFields: metadataFields?.fields ?? [],
8753
+ settings: settings?.settings,
8754
+ settingsRevision: settings?.revision ?? metadataFields?.revision
8755
+ };
8756
+ };
8757
+ var canonical = (value) => JSON.stringify(value ?? null, (_key, item) => isObject2(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : item);
8758
+ var same = (a, b) => canonical(a) === canonical(b);
8759
+ var LABELS = {
8760
+ policy: "policy",
8761
+ assignment: "project policy",
8762
+ metadataField: "metadata field",
8763
+ settings: "project settings",
8764
+ lens: "lens",
8765
+ uploadPreset: "upload preset"
8766
+ };
8767
+ var presetValues = (definition) => {
8768
+ const list = (value) => value?.length ? [...new Set(value)] : null;
8769
+ return {
8770
+ key: definition.key,
8771
+ name: definition.name,
8772
+ access: definition.access ?? "token",
8773
+ enabled: definition.enabled ?? true,
8774
+ allowedContentTypes: list(definition.allowedContentTypes),
8775
+ maxSizeInBytes: definition.maxSizeInBytes ?? null,
8776
+ folderId: definition.folderId ?? null,
8777
+ policyId: definition.policyId ?? null,
8778
+ visibility: definition.visibility ?? "private",
8779
+ processingOptions: definition.processingOptions ?? null,
8780
+ revealDecision: definition.revealDecision ?? false,
8781
+ dailyUploadLimit: definition.dailyUploadLimit ?? null,
8782
+ allowedOrigins: list(definition.allowedOrigins)
8783
+ };
8784
+ };
8785
+ var lensValues = (identifier, lens) => ({
8786
+ identifier,
8787
+ name: lens.name,
8788
+ description: lens.description ?? null,
8789
+ type: lens.type ?? "image",
8790
+ active: lens.active ?? true,
8791
+ transform: lens.transform ?? null
8792
+ });
8793
+ var changedFields = (desired, current) => Object.keys(desired).filter((key) => !same(desired[key], current[key]));
8794
+ var policyNamed = (state, name) => {
8795
+ const matches = state.policies.filter((policy) => policy.name === name);
8796
+ if (matches.length > 1)
8797
+ throw new ConfigurationError(`The organisation has ${matches.length} policies named "${name}". Rename all but one in the portal.`);
8798
+ return matches[0];
8799
+ };
8800
+ var planConfiguration = (config, state, options = {}) => {
8801
+ const changes = [];
8802
+ let unchanged = 0;
8803
+ const update = (kind, name, fields) => {
8804
+ if (fields.length)
8805
+ changes.push({ kind, action: "update", name, fields });
8806
+ else
8807
+ unchanged++;
8808
+ };
8809
+ const knownPolicy = (name) => {
8810
+ if (!config.policies?.[name] && !policyNamed(state, name))
8811
+ throw new ConfigurationError(`No policy is named "${name}": add it under "policies" or create it in the portal.`);
8812
+ };
8813
+ const prune = (kind, held, listed) => {
8814
+ if (options.prune) {
8815
+ for (const name of held)
8816
+ if (!(name in listed))
8817
+ changes.push({ kind, action: "delete", name });
8818
+ }
8819
+ };
8820
+ for (const [name, definition] of Object.entries(config.policies ?? {})) {
8821
+ const existing = policyNamed(state, name);
8822
+ if (!existing)
8823
+ changes.push({ kind: "policy", action: "create", name });
8824
+ else
8825
+ update("policy", name, [
8826
+ ...definition.description !== undefined && definition.description !== existing.description ? ["description"] : [],
8827
+ ...definition.settings && !same(definition.settings, existing.settings) ? ["settings"] : []
8828
+ ]);
8829
+ }
8830
+ if (config.policy !== undefined) {
8831
+ knownPolicy(config.policy);
8832
+ if (policyNamed(state, config.policy)?.id === state.assignedPolicy?.id)
8833
+ unchanged++;
8834
+ else
8835
+ changes.push({ kind: "assignment", action: "update", name: config.policy });
8836
+ }
8837
+ if (config.metadataFields) {
8838
+ const current = new Map(state.metadataFields.map((field) => [field.id, field]));
8839
+ for (const [id, field] of Object.entries(config.metadataFields)) {
8840
+ const existing = current.get(id);
8841
+ if (!existing)
8842
+ changes.push({ kind: "metadataField", action: "create", name: id });
8843
+ else
8844
+ update("metadataField", id, changedFields({ id, ...field }, existing));
8845
+ }
8846
+ prune("metadataField", [...current.keys()], config.metadataFields);
8847
+ }
8848
+ if (config.settings)
8849
+ update("settings", "settings", changedFields(config.settings, state.settings ?? {}));
8850
+ if (config.lenses) {
8851
+ const current = new Map(state.lenses.map((lens) => [lens.identifier, lens]));
8852
+ for (const [identifier, lens] of Object.entries(config.lenses)) {
8853
+ const existing = current.get(identifier);
8854
+ if (!existing)
8855
+ changes.push({ kind: "lens", action: "create", name: identifier });
8856
+ else
8857
+ update("lens", identifier, changedFields(lensValues(identifier, lens), existing));
8858
+ }
8859
+ prune("lens", [...current.keys()], config.lenses);
8860
+ }
8861
+ if (config.uploadPresets) {
8862
+ const current = new Map(state.uploadPresets.map((preset) => [preset.key, preset]));
8863
+ for (const [key, { policy, ...preset }] of Object.entries(config.uploadPresets)) {
8864
+ if (policy !== undefined)
8865
+ knownPolicy(policy);
8866
+ const existing = current.get(key);
8867
+ if (!existing) {
8868
+ changes.push({ kind: "uploadPreset", action: "create", name: key });
8869
+ continue;
8870
+ }
8871
+ const policyId = policy === undefined ? null : policyNamed(state, policy)?.id ?? policy;
8872
+ update("uploadPreset", key, changedFields(presetValues({ ...preset, key, policyId }), existing).map((field) => field === "policyId" ? "policy" : field));
8873
+ }
8874
+ prune("uploadPreset", [...current.keys()], config.uploadPresets);
8875
+ }
8876
+ return { changes, unchanged };
8877
+ };
8878
+ var formatPlan = (plan) => {
8879
+ const items = (count) => `${count} item${count === 1 ? "" : "s"}`;
8880
+ if (!plan.changes.length)
8881
+ return `No changes: ${items(plan.unchanged)} already match the file.
8882
+ `;
8883
+ const symbol = { create: "+", update: "~", delete: "-" };
8884
+ const lines = plan.changes.map((change) => {
8885
+ const subject = change.kind === "settings" ? LABELS.settings : `${LABELS[change.kind]} "${change.name}"`;
8886
+ const fields = change.fields?.length ? ` (${change.fields.join(", ")})` : "";
8887
+ return ` ${symbol[change.action]} ${subject}${fields}`;
8888
+ });
8889
+ const count = (action) => plan.changes.filter((change) => change.action === action).length;
8890
+ return `${lines.join(`
8891
+ `)}
8892
+
8893
+ ${count("create")} to create, ${count("update")} to update, ${count("delete")} to delete, ${plan.unchanged} unchanged.
8894
+ `;
8895
+ };
8896
+ var applyConfiguration = async (client, config, state, plan, log = () => {}) => {
8897
+ const changes = (kind, deletes = false) => plan.changes.filter((change) => change.kind === kind && change.action === "delete" === deletes);
8898
+ const plural = (count, noun, many = `${noun}s`) => `${count} ${count === 1 ? noun : many}`;
8899
+ const policyIds = new Map(state.policies.map((policy) => [policy.name, policy.id]));
8900
+ const policyIdOf = (name) => policyIds.get(name);
8901
+ for (const change of changes("policy")) {
8902
+ const { presetId, settings, description } = config.policies[change.name];
8903
+ const existing = state.policies.find((policy) => policy.name === change.name);
8904
+ if (existing) {
8905
+ await client.policies.update({
8906
+ policyId: existing.id,
8907
+ revision: existing.revision,
8908
+ ...description !== undefined && { description },
8909
+ ...settings && { settings }
8910
+ });
8911
+ log(`Updated policy "${change.name}".`);
8912
+ continue;
8913
+ }
8914
+ const created = await client.policies.create({
8915
+ name: change.name,
8916
+ ...description !== undefined && { description },
8917
+ ...presetId ? { presetId } : { settings }
8918
+ });
8919
+ policyIds.set(change.name, created.id);
8920
+ if (presetId && settings)
8921
+ await client.policies.update({
8922
+ policyId: created.id,
8923
+ revision: created.revision,
8924
+ settings
8925
+ });
8926
+ log(`Created policy "${change.name}".`);
8927
+ }
8928
+ for (const change of changes("assignment")) {
8929
+ await client.policies.assign({ policyId: policyIdOf(change.name) });
8930
+ log(`The project now moderates with policy "${change.name}".`);
8931
+ }
8932
+ let revision = state.settingsRevision;
8933
+ const fields = changes("metadataField");
8934
+ if (fields.length) {
8935
+ ({ revision } = await client.metadataFields.ensure({
8936
+ revision,
8937
+ fields: fields.map((change) => ({
8938
+ id: change.name,
8939
+ ...config.metadataFields[change.name]
8940
+ }))
8941
+ }));
8942
+ log(`Saved ${plural(fields.length, "metadata field")}.`);
8943
+ }
8944
+ for (const change of changes("metadataField", true)) {
8945
+ await client.metadataFields.delete({ fieldId: change.name, revision });
8946
+ ({ revision } = await client.metadataFields.list());
8947
+ log(`Deleted metadata field "${change.name}".`);
8948
+ }
8949
+ if (changes("settings").length) {
8950
+ await client.projectSettings.update({
8951
+ revision,
8952
+ settings: { ...state.settings, ...config.settings }
8953
+ });
8954
+ log("Saved the project settings.");
8955
+ }
8956
+ const lenses = changes("lens");
8957
+ if (lenses.length) {
8958
+ await client.ensureLenses({
8959
+ lenses: lenses.map((change) => lensValues(change.name, config.lenses[change.name]))
8960
+ });
8961
+ log(`Saved ${plural(lenses.length, "lens", "lenses")}.`);
8962
+ }
8963
+ for (const change of changes("lens", true)) {
8964
+ const lens = state.lenses.find((candidate) => candidate.identifier === change.name);
8965
+ await client.lenses.delete({ lensId: lens.id });
8966
+ log(`Deleted lens "${change.name}".`);
8967
+ }
8968
+ const presets = changes("uploadPreset");
8969
+ if (presets.length) {
8970
+ await client.uploadPresets.ensure({
8971
+ uploadPresets: presets.map((change) => {
8972
+ const { policy, ...preset } = config.uploadPresets[change.name];
8973
+ const existing = state.uploadPresets.find((candidate) => candidate.key === change.name);
8974
+ return {
8975
+ ...preset,
8976
+ key: change.name,
8977
+ revision: existing?.revision ?? 0,
8978
+ policyId: policy === undefined ? null : policyIdOf(policy)
8979
+ };
8980
+ })
8981
+ });
8982
+ log(`Saved ${plural(presets.length, "upload preset")}.`);
8983
+ }
8984
+ for (const change of changes("uploadPreset", true)) {
8985
+ const preset = state.uploadPresets.find((candidate) => candidate.key === change.name);
8986
+ await client.uploadPresets.delete({ uploadPresetId: preset.id });
8987
+ log(`Deleted upload preset "${change.name}".`);
8988
+ }
8989
+ };
8990
+
8560
8991
  // src/cli/listen.ts
8561
8992
  import { randomBytes } from "node:crypto";
8562
8993
 
@@ -8711,7 +9142,7 @@ function slugify2(input) {
8711
9142
  return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
8712
9143
  }
8713
9144
  var captureStackTrace2 = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
8714
- function isObject2(data) {
9145
+ function isObject3(data) {
8715
9146
  return typeof data === "object" && data !== null && !Array.isArray(data);
8716
9147
  }
8717
9148
  var allowsEval2 = /* @__PURE__ */ cached2(() => {
@@ -8727,7 +9158,7 @@ var allowsEval2 = /* @__PURE__ */ cached2(() => {
8727
9158
  }
8728
9159
  });
8729
9160
  function isPlainObject3(o) {
8730
- if (isObject2(o) === false)
9161
+ if (isObject3(o) === false)
8731
9162
  return false;
8732
9163
  const ctor = o.constructor;
8733
9164
  if (ctor === undefined)
@@ -8735,7 +9166,7 @@ function isPlainObject3(o) {
8735
9166
  if (typeof ctor !== "function")
8736
9167
  return true;
8737
9168
  const prot = ctor.prototype;
8738
- if (isObject2(prot) === false)
9169
+ if (isObject3(prot) === false)
8739
9170
  return false;
8740
9171
  if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false)
8741
9172
  return false;
@@ -11249,7 +11680,7 @@ var $ZodObject2 = /* @__PURE__ */ $constructor2("$ZodObject", (inst, def) => {
11249
11680
  }
11250
11681
  return propValues;
11251
11682
  });
11252
- const isObject$1 = isObject2;
11683
+ const isObject$1 = isObject3;
11253
11684
  const catchall = def.catchall;
11254
11685
  let value;
11255
11686
  const memo = globalConfig2.memoizer;
@@ -11397,7 +11828,7 @@ var $ZodObjectJIT2 = /* @__PURE__ */ $constructor2("$ZodObjectJIT", (inst, def)
11397
11828
  return doc.compile();
11398
11829
  };
11399
11830
  let fastpass;
11400
- const isObject$2 = isObject2;
11831
+ const isObject$2 = isObject3;
11401
11832
  const jit = !globalConfig2.jitless;
11402
11833
  const fastEnabled = jit && allowsEval2.value;
11403
11834
  const catchall = def.catchall;
@@ -11587,7 +12018,7 @@ var $ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor2("$ZodDiscriminatedUn
11587
12018
  const disc = cached2(() => discriminatorMap(def));
11588
12019
  inst._zod.parse = (payload, ctx) => {
11589
12020
  const input = payload.value;
11590
- if (!isObject2(input)) {
12021
+ if (!isObject3(input)) {
11591
12022
  payload.issues.push({
11592
12023
  code: "invalid_type",
11593
12024
  expected: "object",
@@ -16903,6 +17334,8 @@ var createWebhookHeaders = async (options) => {
16903
17334
  };
16904
17335
  // src/cli/listen.ts
16905
17336
  var FORWARD_TIMEOUT_MS = 1e4;
17337
+ var RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 15000, 30000];
17338
+ var MAX_RETRY_AFTER_MS = 60000;
16906
17339
  var MAX_BACKOFF_MS = 30000;
16907
17340
  var FATAL_ERROR_CODES = new Set([
16908
17341
  "api-key/missing",
@@ -16918,7 +17351,7 @@ var forwardEvent = async (event, options) => {
16918
17351
  const headers = await createWebhookHeaders({
16919
17352
  secret: options.secret,
16920
17353
  body,
16921
- deliveryId: newId("dlv")
17354
+ deliveryId: options.deliveryId ?? newId("dlv")
16922
17355
  });
16923
17356
  const response = await (options.fetchImpl ?? fetch)(options.forwardTo, {
16924
17357
  method: "POST",
@@ -16926,7 +17359,13 @@ var forwardEvent = async (event, options) => {
16926
17359
  body,
16927
17360
  signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS)
16928
17361
  });
16929
- return { ok: response.ok, status: response.status, durationMs: Date.now() - startedAt };
17362
+ const retryAfter = Number(response.headers.get("retry-after"));
17363
+ return {
17364
+ ok: response.ok,
17365
+ status: response.status,
17366
+ durationMs: Date.now() - startedAt,
17367
+ ...(response.status === 429 || response.status === 503) && Number.isFinite(retryAfter) && retryAfter > 0 ? { retryAfterSeconds: retryAfter } : {}
17368
+ };
16930
17369
  } catch (error) {
16931
17370
  const cause = error.cause?.code;
16932
17371
  return {
@@ -16936,10 +17375,12 @@ var forwardEvent = async (event, options) => {
16936
17375
  };
16937
17376
  }
16938
17377
  };
17378
+ var isRetryable = (result) => !result.ok && (result.status === undefined || result.status === 408 || result.status === 425 || result.status === 429 || result.status >= 500);
16939
17379
  var formatTime = (date) => date.toTimeString().slice(0, 8);
16940
- var formatForwardLine = (event, result, now = new Date) => {
17380
+ var formatForwardLine = (event, result, now = new Date, retry) => {
16941
17381
  const outcome = result.status ? `${result.status}${result.ok ? "" : " (handler returned an error)"}` : `failed: ${result.error}${result.error === "ECONNREFUSED" ? " (is your server running?)" : ""}`;
16942
- return `${formatTime(now)} ${event.type.padEnd(16)} ${event.id} → ${outcome} [${result.durationMs}ms]`;
17382
+ const attempt = retry && retry.attempts > 1 && (retry.attempt > 1 || !result.ok) ? ` attempt ${retry.attempt} of ${retry.attempts}${retry.delayMs === undefined ? isRetryable(result) ? ", giving up" : "" : `, retrying in ${Math.round(retry.delayMs / 1000)}s`}` : "";
17383
+ return `${formatTime(now)} ${event.type.padEnd(16)} ${event.id} → ${outcome} [${result.durationMs}ms]${attempt}`;
16943
17384
  };
16944
17385
  var sleep2 = (ms, signal) => new Promise((resolve) => {
16945
17386
  if (signal?.aborted)
@@ -16950,6 +17391,24 @@ var sleep2 = (ms, signal) => new Promise((resolve) => {
16950
17391
  resolve();
16951
17392
  }, { once: true });
16952
17393
  });
17394
+ var deliverEvent = async (event, options) => {
17395
+ const log = options.log ?? ((line) => process.stdout.write(`${line}
17396
+ `));
17397
+ const delays = options.retryDelaysMs ?? RETRY_DELAYS_MS;
17398
+ const attempts = delays.length + 1;
17399
+ const deliveryId = newId("dlv");
17400
+ for (let attempt = 1;; attempt++) {
17401
+ const result = await forwardEvent(event, { ...options, deliveryId });
17402
+ const baseDelay = delays[attempt - 1];
17403
+ const delayMs = isRetryable(result) && baseDelay !== undefined ? Math.max(baseDelay, Math.min(MAX_RETRY_AFTER_MS, (result.retryAfterSeconds ?? 0) * 1000)) : undefined;
17404
+ log(formatForwardLine(event, result, new Date, { attempt, attempts, delayMs }));
17405
+ if (delayMs === undefined || options.signal?.aborted)
17406
+ return result;
17407
+ await sleep2(delayMs, options.signal);
17408
+ if (options.signal?.aborted)
17409
+ return result;
17410
+ }
17411
+ };
16953
17412
  var unavailableEventTypes = (excludedTypes, requested) => requested.size ? excludedTypes.filter((type) => requested.has(type)) : [...excludedTypes];
16954
17413
  var describeEventTypes = (requested, unavailableTypes) => {
16955
17414
  const unavailable = new Set(unavailableTypes);
@@ -17000,7 +17459,9 @@ var listen = async (options) => {
17000
17459
  for (const event of inAssetOrder(page.items)) {
17001
17460
  if (eventTypes.size > 0 && !eventTypes.has(event.type))
17002
17461
  continue;
17003
- log(formatForwardLine(event, await forwardEvent(event, options)));
17462
+ await deliverEvent(event, { ...options, log });
17463
+ if (signal?.aborted)
17464
+ return;
17004
17465
  }
17005
17466
  cursor = page.nextCursor;
17006
17467
  if (!page.hasMore)
@@ -17137,21 +17598,34 @@ Usage:
17137
17598
  calmlens logout
17138
17599
  calmlens listen --forward-to <url> [options]
17139
17600
  calmlens trigger [sexual|violence|self-harm|harassment|hate|criminal-activity|clean] [options]
17601
+ calmlens plan [--config <path>] [--prune]
17602
+ calmlens apply [--config <path>] [--prune]
17140
17603
 
17141
- Run it with \`npx calmlens\`, or install it with \`npm install -g calmlens\`.
17604
+ Install it with \`brew install calmlens/sdks/calmlens\` (after
17605
+ \`brew tap calmlens/sdks https://github.com/CalmLens/sdks\`), the install script at
17606
+ https://calmlens.com/install.sh, a download from https://github.com/CalmLens/sdks/releases,
17607
+ or \`npm install -g calmlens\`. See https://calmlens.com/docs/guides/local-development.
17142
17608
 
17143
17609
  Commands:
17144
17610
  login Sign in through your browser and choose a project. The CLI keeps the key it
17145
17611
  receives, so listen and trigger need no API key or project ID.
17146
17612
  logout Revoke and forget the key from login.
17147
17613
  listen Forward your project's events to a local webhook handler with the same flat
17148
- body (id, projectId, type, severity, title, description, assetId, asset, facts,
17149
- createdAt) and headers (x-calmlens-timestamp, x-calmlens-signature: v1=...) as
17150
- real deliveries. No public URL needed.
17614
+ body (id, projectId, actor, type, severity, title, description, assetId,
17615
+ assetSequence, asset, facts, createdAt) and headers (x-calmlens-delivery,
17616
+ x-calmlens-timestamp, x-calmlens-signature: v1=...) as real deliveries. No
17617
+ public URL needed. Like real deliveries, network errors, timeouts, 408, 425, 429
17618
+ and 5xx responses are retried, up to 7 attempts with the same delivery ID, here
17619
+ after 1, 2, 4, 8, 15 and 30 seconds (longer if Retry-After asks, up to 60).
17151
17620
  trigger Moderate a harmless test comment so CalmLens creates real events. Each trigger
17152
17621
  counts as one upload. Test comments other than clean are signed with the
17153
- project's test input key (Project settings → Test inputs in the portal, with
17154
- Recognise test inputs turned on).
17622
+ project's test input key (Project settings → Test inputs in the portal).
17623
+ plan Compare calmlens.config.json with the project: its policies (by name, with the
17624
+ project's policy), upload presets (by key), lenses (by identifier), metadata
17625
+ fields (by ID) and settings. Prints what apply would change and changes nothing.
17626
+ apply Make the changes plan prints. Each is sent with the revision just read, so a
17627
+ change made meanwhile in the portal or by another deploy is refused, not lost.
17628
+ See https://calmlens.com/docs/guides/configuration-as-code.
17155
17629
 
17156
17630
  Options:
17157
17631
  --forward-to <url> Local webhook URL, e.g. http://localhost:3000/api/webhooks/calmlens
@@ -17164,6 +17638,9 @@ Options:
17164
17638
  --test-key <key> Project's test input key, for trigger (default: $CALMLENS_TEST_INPUT_KEY)
17165
17639
  --env-file <path> Load environment variables from a file, e.g. .env.local
17166
17640
  --interval <seconds> Seconds between checks for new events (default: 2)
17641
+ --config <path> For plan and apply: the configuration file (default: calmlens.config.json)
17642
+ --prune For plan and apply: also delete upload presets, lenses and metadata
17643
+ fields the file doesn't list (never policies)
17167
17644
  --api-url <url> API base URL (default: $CALMLENS_API_URL or https://api.calmlens.com/v1)
17168
17645
  -v, --version Show the CLI version
17169
17646
  -h, --help Show this help
@@ -17194,6 +17671,8 @@ var main = async () => {
17194
17671
  interval: { type: "string" },
17195
17672
  "api-url": { type: "string" },
17196
17673
  "read-only": { type: "boolean" },
17674
+ config: { type: "string" },
17675
+ prune: { type: "boolean" },
17197
17676
  "no-browser": { type: "boolean" },
17198
17677
  help: { type: "boolean", short: "h" },
17199
17678
  version: { type: "boolean", short: "v" }
@@ -17320,6 +17799,33 @@ var main = async () => {
17320
17799
  }
17321
17800
  return;
17322
17801
  }
17802
+ if (command === "plan" || command === "apply") {
17803
+ const path = values.config ?? "calmlens.config.json";
17804
+ let text;
17805
+ try {
17806
+ text = await readFile2(path, "utf8");
17807
+ } catch {
17808
+ return fail(`Couldn't read ${path}. Pass --config <path> to use another file.`);
17809
+ }
17810
+ try {
17811
+ const config = parseConfiguration(text, path);
17812
+ const state = await readConfigurationState(client, config);
17813
+ const plan = planConfiguration(config, state, { prune: Boolean(values.prune) });
17814
+ process.stdout.write(formatPlan(plan));
17815
+ if (command === "apply" && plan.changes.length) {
17816
+ await applyConfiguration(client, config, state, plan, (line) => process.stdout.write(`${line}
17817
+ `));
17818
+ process.stdout.write(`Applied.
17819
+ `);
17820
+ }
17821
+ } catch (error) {
17822
+ if (error instanceof CalmLensError && error.code.endsWith("/revision-conflict"))
17823
+ fail(`${describeError(error)}
17824
+ Something changed since it was read. Run \`calmlens ${command}\` again to see the latest differences.`);
17825
+ fail(error instanceof ConfigurationError ? error.message : `${command === "apply" ? "Apply" : "Plan"} failed: ${describeError(error)}`);
17826
+ }
17827
+ return;
17828
+ }
17323
17829
  fail(`Unknown command "${command}".
17324
17830
 
17325
17831
  ${HELP}`);