calmlens 0.21.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 (79) hide show
  1. package/README.md +3 -2
  2. package/bin/calmlens.js +571 -67
  3. package/{esm/BrowserUpload-D-NnAN7g.d.ts → cjs/BrowserUpload-BWjZ9ntu.d.ts} +2 -2
  4. package/cjs/{BrowserUpload-CeSwiMo5.js → BrowserUpload-Bwlib4Zc.js} +1 -1
  5. package/{esm/CalmLensAppClient-gG16T2py.d.ts → cjs/CalmLensAppClient-BaW3ddUR.d.ts} +1 -1
  6. package/cjs/{CalmLensAppClient-0UVCuNqW.js → CalmLensAppClient-DUYMo9PZ.js} +3 -3
  7. package/cjs/{CalmLensOptionKeys-CYY6elxg.js → CalmLensOptionKeys-YvgV995V.js} +139 -31
  8. package/cjs/{CalmLensServerClient-nfu6_YEW.js → CalmLensServerClient-3N-gdsxC.js} +61 -4
  9. package/cjs/{CalmLensServerClient-BHx3x_nZ.d.ts → CalmLensServerClient-BKzn8zmp.d.ts} +38 -2
  10. package/cjs/{CalmLensTypes-CUB0YYVz.d.ts → CalmLensTypes-BDKwThbO.d.ts} +612 -53
  11. package/{esm/Core-C82YmjjX.d.ts → cjs/Core-C33pkBmf.d.ts} +7 -4
  12. package/cjs/{Core-Dc3cteU7.js → Core-Cm5Z1oJ9.js} +9 -6
  13. package/cjs/{ModerationContextLimits-BxOmeSqq.js → ModerationContextLimits-ud1xpZRK.js} +61 -2
  14. package/cjs/{ReactUpload-BK2O3dnK.js → ReactUpload-DQ0BYISX.js} +1 -1
  15. package/cjs/{ReactUpload-DiiXfKvj.d.ts → ReactUpload-DhF8mm51.d.ts} +1 -1
  16. package/cjs/{TestTriggers-BTyXtX0Q-ATuFDhLX.js → TestTriggers-D29T_R0M-D6Bu-Mln.js} +16 -16
  17. package/cjs/{UploadController-DLyiLDTB.js → UploadController-l8fZM2qT.js} +2 -2
  18. package/cjs/{WebhookPayload-BLT2y_Jy.d.ts → WebhookPayload-Dt6DttS0.d.ts} +28 -1
  19. package/cjs/app.d.ts +5 -5
  20. package/cjs/app.js +2 -2
  21. package/cjs/elements.d.ts +4 -4
  22. package/cjs/elements.js +4 -4
  23. package/{esm/index-CKRgjV16.d.ts → cjs/index-Bde1wjiw.d.ts} +2 -2
  24. package/cjs/index.d.ts +4 -4
  25. package/cjs/index.js +1 -1
  26. package/cjs/react-native.d.ts +2 -2
  27. package/cjs/react-native.js +4 -4
  28. package/cjs/react.d.ts +3 -3
  29. package/cjs/react.js +5 -5
  30. package/cjs/server.d.ts +5 -5
  31. package/cjs/server.js +2 -2
  32. package/cjs/test-inputs.js +13 -13
  33. package/cjs/testing.d.ts +10 -6
  34. package/cjs/testing.js +332 -54
  35. package/cjs/{ui-CZ8exACq.js → ui-BRA4HQ8r.js} +3 -3
  36. package/cjs/{ui-CTBUxnVp.d.ts → ui-YQuvbidU.d.ts} +2 -2
  37. package/cjs/ui.d.ts +2 -2
  38. package/cjs/ui.js +3 -3
  39. package/cjs/vue.d.ts +5 -5
  40. package/cjs/vue.js +4 -4
  41. package/{cjs/BrowserUpload-D-NnAN7g.d.ts → esm/BrowserUpload-BWjZ9ntu.d.ts} +2 -2
  42. package/esm/{BrowserUpload-i9OhCzMJ.js → BrowserUpload-GRZVB0G_.js} +1 -1
  43. package/esm/{CalmLensAppClient-CK4_Py0c.js → CalmLensAppClient-B5QIJ6KS.js} +3 -3
  44. package/{cjs/CalmLensAppClient-gG16T2py.d.ts → esm/CalmLensAppClient-BaW3ddUR.d.ts} +1 -1
  45. package/esm/{CalmLensOptionKeys-BGZlIsT2.js → CalmLensOptionKeys-BG7Qrh8-.js} +139 -31
  46. package/esm/{CalmLensServerClient-BHx3x_nZ.d.ts → CalmLensServerClient-BKzn8zmp.d.ts} +38 -2
  47. package/esm/{CalmLensServerClient-dAQUcDWb.js → CalmLensServerClient-bRUAebi-.js} +61 -4
  48. package/esm/{CalmLensTypes-CUB0YYVz.d.ts → CalmLensTypes-BDKwThbO.d.ts} +612 -53
  49. package/esm/{Core-BxeIud_S.js → Core-BvQe4moS.js} +9 -6
  50. package/{cjs/Core-C82YmjjX.d.ts → esm/Core-C33pkBmf.d.ts} +7 -4
  51. package/esm/{ModerationContextLimits-B6_RalCQ.js → ModerationContextLimits-CrxSnVZ3.js} +61 -2
  52. package/esm/{ReactUpload-DxwVqfX1.js → ReactUpload-BMO8saxT.js} +1 -1
  53. package/esm/{ReactUpload-DiiXfKvj.d.ts → ReactUpload-DhF8mm51.d.ts} +1 -1
  54. package/esm/{TestTriggers-BTyXtX0Q-GRB9jQwo.js → TestTriggers-D29T_R0M-Ztc74ucs.js} +16 -16
  55. package/esm/{UploadController-D9Z-h00Q.js → UploadController-DnJrWiE4.js} +2 -2
  56. package/esm/{WebhookPayload-BLT2y_Jy.d.ts → WebhookPayload-Dt6DttS0.d.ts} +28 -1
  57. package/esm/app.d.ts +5 -5
  58. package/esm/app.js +2 -2
  59. package/esm/elements.d.ts +4 -4
  60. package/esm/elements.js +4 -4
  61. package/{cjs/index-CKRgjV16.d.ts → esm/index-Bde1wjiw.d.ts} +2 -2
  62. package/esm/index.d.ts +4 -4
  63. package/esm/index.js +1 -1
  64. package/esm/react-native.d.ts +2 -2
  65. package/esm/react-native.js +4 -4
  66. package/esm/react.d.ts +3 -3
  67. package/esm/react.js +5 -5
  68. package/esm/server.d.ts +5 -5
  69. package/esm/server.js +2 -2
  70. package/esm/test-inputs.js +1 -1
  71. package/esm/testing.d.ts +10 -6
  72. package/esm/testing.js +326 -48
  73. package/esm/{ui-CTBUxnVp.d.ts → ui-YQuvbidU.d.ts} +2 -2
  74. package/esm/{ui-Cr7s6JHm.js → ui-heryDd6g.js} +3 -3
  75. package/esm/ui.d.ts +2 -2
  76. package/esm/ui.js +3 -3
  77. package/esm/vue.d.ts +5 -5
  78. package/esm/vue.js +4 -4
  79. 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.22.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
  }
@@ -1519,7 +1533,7 @@ var splitsIntoParts = (content, partSizeBytes) => {
1519
1533
  };
1520
1534
  var DEFAULT_MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
1521
1535
  var toBodyBytes = (value) => value.buffer instanceof ArrayBuffer ? value : Uint8Array.from(value);
1522
- var toRawUploadBody = (payload) => {
1536
+ var toUploadData = (payload) => {
1523
1537
  const data = assetToData(payload);
1524
1538
  if (data instanceof Response) {
1525
1539
  if (!data.body) {
@@ -1529,18 +1543,87 @@ var toRawUploadBody = (payload) => {
1529
1543
  }
1530
1544
  return data.body;
1531
1545
  }
1532
- if (data instanceof ArrayBuffer || data instanceof Blob) {
1546
+ if (data instanceof Blob)
1533
1547
  return data;
1534
- }
1535
- if ("getReader" in data) {
1548
+ if (data instanceof ArrayBuffer)
1549
+ return new Uint8Array(data);
1550
+ if ("getReader" in data)
1536
1551
  return data;
1537
- }
1538
1552
  return toBodyBytes(data);
1539
1553
  };
1554
+ var toRawUploadBody = (payload) => toUploadData(payload);
1555
+ var textEncoder = new TextEncoder;
1556
+ var toUploadForm = (options, payload) => {
1557
+ const boundary = `calmlens-${randomUuid()}`;
1558
+ const head = `--${boundary}\r
1559
+ Content-Disposition: form-data; name="options"\r
1560
+ Content-Type: application/json\r
1561
+ \r
1562
+ ${JSON.stringify(options)}\r
1563
+ --${boundary}\r
1564
+ Content-Disposition: form-data; name="file"\r
1565
+ Content-Type: ${payload.type.replace(/[\r\n]/g, "")}\r
1566
+ \r
1567
+ `;
1568
+ const tail = `\r
1569
+ --${boundary}--\r
1570
+ `;
1571
+ const contentType = `multipart/form-data; boundary=${boundary}`;
1572
+ const data = toUploadData(payload);
1573
+ if (data instanceof Blob)
1574
+ return { body: new Blob([head, data, tail]), contentType };
1575
+ const headBytes = textEncoder.encode(head);
1576
+ const tailBytes = textEncoder.encode(tail);
1577
+ if (data instanceof Uint8Array) {
1578
+ const body = new Uint8Array(headBytes.length + data.length + tailBytes.length);
1579
+ body.set(headBytes);
1580
+ body.set(data, headBytes.length);
1581
+ body.set(tailBytes, headBytes.length + data.length);
1582
+ return { body, contentType };
1583
+ }
1584
+ const reader = data.getReader();
1585
+ let stage = "head";
1586
+ const body = new ReadableStream({
1587
+ async pull(controller) {
1588
+ if (stage === "head") {
1589
+ stage = "file";
1590
+ controller.enqueue(headBytes);
1591
+ return;
1592
+ }
1593
+ if (stage === "done")
1594
+ return;
1595
+ const { done, value } = await reader.read();
1596
+ if (!done) {
1597
+ if (value.byteLength)
1598
+ controller.enqueue(value);
1599
+ return;
1600
+ }
1601
+ stage = "done";
1602
+ controller.enqueue(tailBytes);
1603
+ controller.close();
1604
+ },
1605
+ cancel: (reason) => reader.cancel(reason)
1606
+ });
1607
+ return { body, contentType };
1608
+ };
1609
+ var uploadFields = (options) => Object.fromEntries(UPLOAD_OPTION_KEYS.flatMap((key) => options[key] === undefined || options[key] === null ? [] : [[key, options[key]]]));
1610
+ var UPLOAD_OPTION_KEYS = [
1611
+ "name",
1612
+ "description",
1613
+ "processingOptions",
1614
+ "visibility",
1615
+ "metadata",
1616
+ "tags",
1617
+ "authorId",
1618
+ "context",
1619
+ "externalId",
1620
+ "externalUrl",
1621
+ "folderId",
1622
+ "uploadPresetId"
1623
+ ];
1540
1624
  var setOptionalQueryValue = (params, key, value) => {
1541
- if (value !== undefined && value !== null) {
1542
- params.set(key, typeof value === "string" ? value : JSON.stringify(value));
1543
- }
1625
+ if (value !== undefined && value !== null)
1626
+ params.set(key, String(value));
1544
1627
  };
1545
1628
  var assertValidUploadMimeType = (mimeType) => {
1546
1629
  if (!isAcceptedUploadMimeType(mimeType)) {
@@ -1735,50 +1818,51 @@ class CalmLensConnection {
1735
1818
  deadline: "body"
1736
1819
  });
1737
1820
  }
1738
- upload(url, payload, headers, idempotencyKey) {
1821
+ upload(url, body, headers, idempotencyKey, text) {
1739
1822
  return this.transport.json({
1740
1823
  method: "POST",
1741
1824
  url,
1742
1825
  headers,
1743
- body: toRawUploadBody(payload),
1826
+ body,
1744
1827
  idempotencyKey,
1745
- timeoutMs: isTextPayload(payload) ? this.timeoutMs : this.options.uploadTimeoutMs,
1828
+ timeoutMs: text ? this.timeoutMs : this.options.uploadTimeoutMs,
1746
1829
  deadline: "body",
1747
1830
  fetch: this.options.uploadFetch
1748
1831
  });
1749
1832
  }
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);
1833
+ submitUpload(uploadsPath, options, wait, authHeaders = {}) {
1765
1834
  const isMultipart = "part" in options;
1766
1835
  const payload = isMultipart ? options.part : options.content;
1836
+ const multipartOptions = options;
1837
+ const idempotencyKey = options.idempotencyKey ?? newIdempotencyKey();
1838
+ const fields = uploadFields(options);
1839
+ if (isTextPayload(payload)) {
1840
+ const { sizeInBytes: _size, ...text } = payload;
1841
+ const body = isMultipart ? {
1842
+ ...fields,
1843
+ part: text,
1844
+ ...multipartOptions.sizeInBytes === undefined ? {} : { sizeInBytes: multipartOptions.sizeInBytes },
1845
+ ...multipartOptions.totalSizeInBytes === undefined ? {} : { totalSizeInBytes: multipartOptions.totalSizeInBytes }
1846
+ } : { ...fields, content: text };
1847
+ return this.upload(this.url(uploadsPath, { wait }), JSON.stringify(body), { ...authHeaders, "Content-Type": "application/json" }, idempotencyKey, true);
1848
+ }
1849
+ const query = new URLSearchParams;
1850
+ query.set("wait", String(wait));
1767
1851
  query.set("contentType", payload.type);
1768
1852
  setOptionalQueryValue(query, "sizeInBytes", payload.sizeInBytes ?? getAssetPayloadByteLength(payload));
1769
1853
  if (isMultipart) {
1770
1854
  const part = payload;
1771
- const multipartOptions = options;
1772
1855
  query.set("partNumber", String(part.partNumber ?? 1));
1773
1856
  query.set("isFinal", String(part.isFinal ?? false));
1774
1857
  setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? multipartOptions.sizeInBytes);
1775
1858
  setOptionalQueryValue(query, "totalSizeInBytes", multipartOptions.totalSizeInBytes);
1776
1859
  }
1777
- return this.upload(this.url(`${uploadsPath}?${query}`), payload, {
1860
+ const form = toUploadForm(fields, payload);
1861
+ return this.upload(this.url(`${uploadsPath}?${query}`), form.body, {
1778
1862
  ...authHeaders,
1779
- "Content-Type": payload.type,
1863
+ "Content-Type": form.contentType,
1780
1864
  "X-CalmLens-Upload": isMultipart ? "part" : "content"
1781
- }, options.idempotencyKey ?? newIdempotencyKey());
1865
+ }, idempotencyKey, false);
1782
1866
  }
1783
1867
  get partSizeBytes() {
1784
1868
  return this.options.partSizeBytes ?? DEFAULT_PART_SIZE_BYTES;
@@ -1795,7 +1879,7 @@ class CalmLensConnection {
1795
1879
  const count = Math.ceil(source.size / partSize);
1796
1880
  const key = idempotencyKey ?? newIdempotencyKey();
1797
1881
  const part = (partNumber) => source.slice((partNumber - 1) * partSize, Math.min(partNumber * partSize, source.size));
1798
- const first = await this.submitRawUpload(uploadsPath, {
1882
+ const first = await this.submitUpload(uploadsPath, {
1799
1883
  ...fields,
1800
1884
  part: { ...part(1), type: content.type, partNumber: 1, isFinal: false },
1801
1885
  totalSizeInBytes: source.size,
@@ -1844,7 +1928,7 @@ class CalmLensConnection {
1844
1928
  if (wait !== undefined)
1845
1929
  query.set("wait", String(wait));
1846
1930
  setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? getAssetPayloadByteLength(part));
1847
- return this.upload(this.url(`${partPath}?${query}`), part, { ...authHeaders, "X-CalmLens-Upload": "part" }, idempotencyKey ?? newIdempotencyKey());
1931
+ return this.upload(this.url(`${partPath}?${query}`), toRawUploadBody(part), { ...authHeaders, "X-CalmLens-Upload": "part" }, idempotencyKey ?? newIdempotencyKey(), isTextPayload(part));
1848
1932
  }
1849
1933
  }
1850
1934
 
@@ -1897,6 +1981,9 @@ var SERVER_OPTION_KEYS = {
1897
1981
  "lenses.list": ["cursor", "pageSize", "sort"],
1898
1982
  "lenses.retrieve": ["lensId"],
1899
1983
  "lenses.update": ["active", "description", "lensId", "name", "transform", "type"],
1984
+ "metadataFields.delete": ["fieldId", "revision"],
1985
+ "metadataFields.ensure": ["fields", "revision"],
1986
+ "metadataFields.list": [],
1900
1987
  "policies.assign": ["policyId"],
1901
1988
  "policies.create": ["description", "name", "presetId", "settings"],
1902
1989
  "policies.delete": ["policyId"],
@@ -1908,7 +1995,13 @@ var SERVER_OPTION_KEYS = {
1908
1995
  "policies.setAutomaticUpdates": ["enabled", "policyId", "presetVersion", "revision"],
1909
1996
  "policies.update": ["description", "name", "policyId", "revision", "settings"],
1910
1997
  "policies.upgrade": ["policyId", "presetVersion", "revision"],
1911
- "text.classify": ["authorId", "context", "description", "externalId", "externalUrl", "folderId", "metadata", "name", "processingOptions", "tags", "text", "uploadPresetId", "visibility"]
1998
+ "projectSettings.get": [],
1999
+ "projectSettings.update": ["revision", "searchIndexingBudgetUnits", "settings"],
2000
+ "text.classify": ["authorId", "context", "description", "externalId", "externalUrl", "folderId", "metadata", "name", "processingOptions", "tags", "text", "uploadPresetId", "visibility"],
2001
+ "uploadPresets.delete": ["uploadPresetId"],
2002
+ "uploadPresets.ensure": ["uploadPresets"],
2003
+ "uploadPresets.iterate": ["cursor", "pageSize", "sort"],
2004
+ "uploadPresets.list": ["cursor", "pageSize", "sort"]
1912
2005
  };
1913
2006
  var NULLABLE_OPTION_KEYS = {
1914
2007
  "assets.classify": ["authorId", "context", "description", "externalId", "folderId", "metadata", "processingOptions", "tags", "uploadPresetId", "visibility"],
@@ -2071,6 +2164,7 @@ var inspectSymbol = Symbol.for("nodejs.util.inspect.custom");
2071
2164
 
2072
2165
  class CalmLensServerClient {
2073
2166
  #apiKey;
2167
+ #options;
2074
2168
  #settings;
2075
2169
  #lenses;
2076
2170
  #connection;
@@ -2084,6 +2178,7 @@ class CalmLensServerClient {
2084
2178
  }
2085
2179
  const { apiKey, ...rest } = options;
2086
2180
  this.#apiKey = apiKey;
2181
+ this.#options = rest;
2087
2182
  this.#settings = {
2088
2183
  ...resolveConnectionOptions(rest),
2089
2184
  cdnBaseUrl: (rest.cdnBaseUrl ?? getMockHooks(rest)?.defaultCdnBaseUrl ?? DEFAULT_CDN_BASE_URL).replace(/\/+$/, "")
@@ -2093,7 +2188,7 @@ class CalmLensServerClient {
2093
2188
  }
2094
2189
  withRequestOptions(options) {
2095
2190
  validateRequestOptions(options);
2096
- return new CalmLensServerClient({ ...this.#settings, ...options, apiKey: this.#apiKey }, this.#lenses);
2191
+ return new CalmLensServerClient({ ...this.#options, ...options, apiKey: this.#apiKey }, this.#lenses);
2097
2192
  }
2098
2193
  [inspectSymbol]() {
2099
2194
  const { projectId, baseUrl } = this.#settings;
@@ -2122,7 +2217,7 @@ class CalmLensServerClient {
2122
2217
  }));
2123
2218
  }
2124
2219
  if ("content" in body || "part" in body) {
2125
- return expectAsset(await this.#connection.submitRawUpload(uploadsPath, body, wait));
2220
+ return expectAsset(await this.#connection.submitUpload(uploadsPath, body, wait));
2126
2221
  }
2127
2222
  const { idempotencyKey, ...fields } = body;
2128
2223
  const data = await this.#connection.json("POST", uploadsPath, {
@@ -2440,6 +2535,44 @@ class CalmLensServerClient {
2440
2535
  })
2441
2536
  };
2442
2537
  }
2538
+ get uploadPresets() {
2539
+ return {
2540
+ list: async (options = {}) => this.request("GET", `${this.projectPath}/upload-presets`, {
2541
+ query: checked("uploadPresets.list", options)
2542
+ }),
2543
+ iterate: (options = {}) => {
2544
+ checked("uploadPresets.iterate", options);
2545
+ return this.iteratePages((cursor) => this.uploadPresets.list({ ...options, cursor }));
2546
+ },
2547
+ ensure: async (options) => this.request("PUT", `${this.projectPath}/upload-presets`, {
2548
+ body: checked("uploadPresets.ensure", options)
2549
+ }),
2550
+ delete: async (options) => {
2551
+ const { uploadPresetId } = checked("uploadPresets.delete", options);
2552
+ await this.request("DELETE", `/upload-presets/${requireId(uploadPresetId, "Upload preset ID")}`);
2553
+ }
2554
+ };
2555
+ }
2556
+ get projectSettings() {
2557
+ return {
2558
+ get: async () => this.request("GET", `${this.projectPath}/settings`),
2559
+ update: async (options) => this.request("PUT", `${this.projectPath}/settings`, {
2560
+ body: checked("projectSettings.update", options)
2561
+ })
2562
+ };
2563
+ }
2564
+ get metadataFields() {
2565
+ return {
2566
+ list: async () => this.request("GET", `${this.projectPath}/metadata-fields`),
2567
+ ensure: async (options) => this.request("PUT", `${this.projectPath}/metadata-fields`, {
2568
+ body: checked("metadataFields.ensure", options)
2569
+ }),
2570
+ delete: async (options) => {
2571
+ const { fieldId, ...query } = checked("metadataFields.delete", options);
2572
+ await this.request("DELETE", `${this.projectPath}/metadata-fields/${requireId(fieldId, "Metadata field ID")}`, { query });
2573
+ }
2574
+ };
2575
+ }
2443
2576
  get lenses() {
2444
2577
  const lensPath = (lensId) => `/lenses/${requireId(lensId, "Lens ID")}`;
2445
2578
  const forget = (matches) => {
@@ -7195,53 +7328,53 @@ function superRefine(fn, params) {
7195
7328
  return _superRefine(fn, params);
7196
7329
  }
7197
7330
 
7198
- // src/contract/Jurisdiction-DnnDdNKC.js
7331
+ // src/contract/Jurisdiction-LWQvqyxL.js
7199
7332
  var JURISDICTIONS = {
7200
7333
  global: {
7201
7334
  name: "Global",
7202
7335
  ageCheckStandard: "any",
7203
- optIn: false
7336
+ optional: false
7204
7337
  },
7205
7338
  DE: {
7206
7339
  name: "Germany",
7207
7340
  ageCheckStandard: "any",
7208
- optIn: false
7341
+ optional: false
7209
7342
  },
7210
7343
  AT: {
7211
7344
  name: "Austria",
7212
7345
  ageCheckStandard: "any",
7213
- optIn: false
7346
+ optional: false
7214
7347
  },
7215
7348
  FR: {
7216
7349
  name: "France",
7217
7350
  ageCheckStandard: "any",
7218
- optIn: false
7351
+ optional: false
7219
7352
  },
7220
7353
  GB: {
7221
7354
  name: "United Kingdom",
7222
7355
  ageCheckStandard: "verified",
7223
- optIn: false
7356
+ optional: false
7224
7357
  },
7225
7358
  EU: {
7226
7359
  name: "European Union",
7227
7360
  ageCheckStandard: "verified",
7228
- optIn: true
7361
+ optional: true
7229
7362
  },
7230
7363
  AU: {
7231
7364
  name: "Australia",
7232
7365
  ageCheckStandard: "verified",
7233
- optIn: false
7366
+ optional: false
7234
7367
  },
7235
7368
  BR: {
7236
7369
  name: "Brazil",
7237
7370
  ageCheckStandard: "verified",
7238
- optIn: false
7371
+ optional: false
7239
7372
  }
7240
7373
  };
7241
7374
  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" });
7375
+ Object.keys(JURISDICTIONS).filter((code) => !JURISDICTIONS[code].optional);
7376
+ var OPTIONAL_JURISDICTIONS = Object.keys(JURISDICTIONS).filter((code) => JURISDICTIONS[code].optional);
7377
+ _enum(OPTIONAL_JURISDICTIONS).array().refine((codes) => new Set(codes).size === codes.length, { message: "jurisdiction/duplicate" });
7245
7378
  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
7379
  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
7380
  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.");
@@ -7251,7 +7384,7 @@ var VIEWER_CLAIMS_SCHEMA = object({
7251
7384
  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.")
7252
7385
  }).strict();
7253
7386
 
7254
- // src/contract/TestRegionalActions-DPNhFf9c.js
7387
+ // src/contract/TestRegionalActions-C2mw3ntb.js
7255
7388
  var msg = (text) => text;
7256
7389
  var MODERATION_QUALIFIER_INFO = {
7257
7390
  "sexual-pornographic-media": {
@@ -8269,7 +8402,7 @@ var TEST_REGIONAL_ACTIONS_SCHEMA = array(object({
8269
8402
  ])
8270
8403
  }).strict()).max(7).refine((entries) => new Set(entries.map((entry) => entry.region)).size === entries.length, "Choose each region once");
8271
8404
 
8272
- // src/contract/TestTriggers-BTyXtX0Q.js
8405
+ // src/contract/TestTriggers-D29T_R0M.js
8273
8406
  var TEST_IMAGE_GRID_LEVELS = [
8274
8407
  72,
8275
8408
  128,
@@ -8557,6 +8690,302 @@ async function generateTestTextCode(scenario, key) {
8557
8690
  throw new RangeError("Test scenario is too large");
8558
8691
  return `<!calmlens-test ${await tag(payload, key)} ${payload}>`;
8559
8692
  }
8693
+ // src/cli/configuration.ts
8694
+ class ConfigurationError extends Error {
8695
+ }
8696
+ var SECTIONS = ["policies", "policy", "uploadPresets", "lenses", "metadataFields", "settings"];
8697
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
8698
+ var parseConfiguration = (text, source = "calmlens.config.json") => {
8699
+ let value;
8700
+ try {
8701
+ value = JSON.parse(text);
8702
+ } catch (error) {
8703
+ throw new ConfigurationError(`${source} isn't valid JSON: ${error.message}`);
8704
+ }
8705
+ if (!isObject2(value))
8706
+ throw new ConfigurationError(`${source} must hold a JSON object.`);
8707
+ for (const key of Object.keys(value))
8708
+ if (key !== "$schema" && !SECTIONS.includes(key))
8709
+ throw new ConfigurationError(`${source} has an unknown section "${key}". Use ${SECTIONS.join(", ")}.`);
8710
+ for (const section of ["policies", "uploadPresets", "lenses", "metadataFields", "settings"]) {
8711
+ if (value[section] === undefined)
8712
+ continue;
8713
+ if (!isObject2(value[section]))
8714
+ throw new ConfigurationError(`${source}: "${section}" must be an object.`);
8715
+ if (section === "settings")
8716
+ continue;
8717
+ for (const [name, item] of Object.entries(value[section]))
8718
+ if (!isObject2(item))
8719
+ throw new ConfigurationError(`${source}: ${section} "${name}" must be an object.`);
8720
+ }
8721
+ if (value.policy !== undefined && typeof value.policy !== "string")
8722
+ throw new ConfigurationError(`${source}: "policy" must be a policy name.`);
8723
+ const config = value;
8724
+ for (const [name, policy] of Object.entries(config.policies ?? {}))
8725
+ if (!policy.presetId && !policy.settings)
8726
+ throw new ConfigurationError(`${source}: policy "${name}" needs "presetId", "settings" or both.`);
8727
+ return config;
8728
+ };
8729
+ var collect = async (items) => {
8730
+ const all = [];
8731
+ for await (const item of items)
8732
+ all.push(item);
8733
+ return all;
8734
+ };
8735
+ var readConfigurationState = async (client, config) => {
8736
+ const presetsNamePolicies = Object.values(config.uploadPresets ?? {}).some((preset) => preset.policy !== undefined);
8737
+ const [policies, assignedPolicy, uploadPresets, lenses, metadataFields, settings] = await Promise.all([
8738
+ config.policies || config.policy !== undefined || presetsNamePolicies ? collect(client.policies.iterate()) : [],
8739
+ config.policy !== undefined ? client.policies.retrieveAssigned() : undefined,
8740
+ config.uploadPresets ? collect(client.uploadPresets.iterate()) : [],
8741
+ config.lenses ? collect(client.lenses.iterate()) : [],
8742
+ config.metadataFields ? client.metadataFields.list() : undefined,
8743
+ config.settings ? client.projectSettings.get() : undefined
8744
+ ]);
8745
+ return {
8746
+ policies,
8747
+ assignedPolicy,
8748
+ uploadPresets,
8749
+ lenses,
8750
+ metadataFields: metadataFields?.fields ?? [],
8751
+ settings: settings?.settings,
8752
+ settingsRevision: settings?.revision ?? metadataFields?.revision
8753
+ };
8754
+ };
8755
+ 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);
8756
+ var same = (a, b) => canonical(a) === canonical(b);
8757
+ var LABELS = {
8758
+ policy: "policy",
8759
+ assignment: "project policy",
8760
+ metadataField: "metadata field",
8761
+ settings: "project settings",
8762
+ lens: "lens",
8763
+ uploadPreset: "upload preset"
8764
+ };
8765
+ var presetValues = (definition) => {
8766
+ const list = (value) => value?.length ? [...new Set(value)] : null;
8767
+ return {
8768
+ key: definition.key,
8769
+ name: definition.name,
8770
+ access: definition.access ?? "token",
8771
+ enabled: definition.enabled ?? true,
8772
+ allowedContentTypes: list(definition.allowedContentTypes),
8773
+ maxSizeInBytes: definition.maxSizeInBytes ?? null,
8774
+ folderId: definition.folderId ?? null,
8775
+ policyId: definition.policyId ?? null,
8776
+ visibility: definition.visibility ?? "private",
8777
+ processingOptions: definition.processingOptions ?? null,
8778
+ revealDecision: definition.revealDecision ?? false,
8779
+ dailyUploadLimit: definition.dailyUploadLimit ?? null,
8780
+ allowedOrigins: list(definition.allowedOrigins)
8781
+ };
8782
+ };
8783
+ var lensValues = (identifier, lens) => ({
8784
+ identifier,
8785
+ name: lens.name,
8786
+ description: lens.description ?? null,
8787
+ type: lens.type ?? "image",
8788
+ active: lens.active ?? true,
8789
+ transform: lens.transform ?? null
8790
+ });
8791
+ var changedFields = (desired, current) => Object.keys(desired).filter((key) => !same(desired[key], current[key]));
8792
+ var policyNamed = (state, name) => {
8793
+ const matches = state.policies.filter((policy) => policy.name === name);
8794
+ if (matches.length > 1)
8795
+ throw new ConfigurationError(`The organisation has ${matches.length} policies named "${name}". Rename all but one in the portal.`);
8796
+ return matches[0];
8797
+ };
8798
+ var planConfiguration = (config, state, options = {}) => {
8799
+ const changes = [];
8800
+ let unchanged = 0;
8801
+ const update = (kind, name, fields) => {
8802
+ if (fields.length)
8803
+ changes.push({ kind, action: "update", name, fields });
8804
+ else
8805
+ unchanged++;
8806
+ };
8807
+ const knownPolicy = (name) => {
8808
+ if (!config.policies?.[name] && !policyNamed(state, name))
8809
+ throw new ConfigurationError(`No policy is named "${name}": add it under "policies" or create it in the portal.`);
8810
+ };
8811
+ const prune = (kind, held, listed) => {
8812
+ if (options.prune) {
8813
+ for (const name of held)
8814
+ if (!(name in listed))
8815
+ changes.push({ kind, action: "delete", name });
8816
+ }
8817
+ };
8818
+ for (const [name, definition] of Object.entries(config.policies ?? {})) {
8819
+ const existing = policyNamed(state, name);
8820
+ if (!existing)
8821
+ changes.push({ kind: "policy", action: "create", name });
8822
+ else
8823
+ update("policy", name, [
8824
+ ...definition.description !== undefined && definition.description !== existing.description ? ["description"] : [],
8825
+ ...definition.settings && !same(definition.settings, existing.settings) ? ["settings"] : []
8826
+ ]);
8827
+ }
8828
+ if (config.policy !== undefined) {
8829
+ knownPolicy(config.policy);
8830
+ if (policyNamed(state, config.policy)?.id === state.assignedPolicy?.id)
8831
+ unchanged++;
8832
+ else
8833
+ changes.push({ kind: "assignment", action: "update", name: config.policy });
8834
+ }
8835
+ if (config.metadataFields) {
8836
+ const current = new Map(state.metadataFields.map((field) => [field.id, field]));
8837
+ for (const [id, field] of Object.entries(config.metadataFields)) {
8838
+ const existing = current.get(id);
8839
+ if (!existing)
8840
+ changes.push({ kind: "metadataField", action: "create", name: id });
8841
+ else
8842
+ update("metadataField", id, changedFields({ id, ...field }, existing));
8843
+ }
8844
+ prune("metadataField", [...current.keys()], config.metadataFields);
8845
+ }
8846
+ if (config.settings)
8847
+ update("settings", "settings", changedFields(config.settings, state.settings ?? {}));
8848
+ if (config.lenses) {
8849
+ const current = new Map(state.lenses.map((lens) => [lens.identifier, lens]));
8850
+ for (const [identifier, lens] of Object.entries(config.lenses)) {
8851
+ const existing = current.get(identifier);
8852
+ if (!existing)
8853
+ changes.push({ kind: "lens", action: "create", name: identifier });
8854
+ else
8855
+ update("lens", identifier, changedFields(lensValues(identifier, lens), existing));
8856
+ }
8857
+ prune("lens", [...current.keys()], config.lenses);
8858
+ }
8859
+ if (config.uploadPresets) {
8860
+ const current = new Map(state.uploadPresets.map((preset) => [preset.key, preset]));
8861
+ for (const [key, { policy, ...preset }] of Object.entries(config.uploadPresets)) {
8862
+ if (policy !== undefined)
8863
+ knownPolicy(policy);
8864
+ const existing = current.get(key);
8865
+ if (!existing) {
8866
+ changes.push({ kind: "uploadPreset", action: "create", name: key });
8867
+ continue;
8868
+ }
8869
+ const policyId = policy === undefined ? null : policyNamed(state, policy)?.id ?? policy;
8870
+ update("uploadPreset", key, changedFields(presetValues({ ...preset, key, policyId }), existing).map((field) => field === "policyId" ? "policy" : field));
8871
+ }
8872
+ prune("uploadPreset", [...current.keys()], config.uploadPresets);
8873
+ }
8874
+ return { changes, unchanged };
8875
+ };
8876
+ var formatPlan = (plan) => {
8877
+ const items = (count) => `${count} item${count === 1 ? "" : "s"}`;
8878
+ if (!plan.changes.length)
8879
+ return `No changes: ${items(plan.unchanged)} already match the file.
8880
+ `;
8881
+ const symbol = { create: "+", update: "~", delete: "-" };
8882
+ const lines = plan.changes.map((change) => {
8883
+ const subject = change.kind === "settings" ? LABELS.settings : `${LABELS[change.kind]} "${change.name}"`;
8884
+ const fields = change.fields?.length ? ` (${change.fields.join(", ")})` : "";
8885
+ return ` ${symbol[change.action]} ${subject}${fields}`;
8886
+ });
8887
+ const count = (action) => plan.changes.filter((change) => change.action === action).length;
8888
+ return `${lines.join(`
8889
+ `)}
8890
+
8891
+ ${count("create")} to create, ${count("update")} to update, ${count("delete")} to delete, ${plan.unchanged} unchanged.
8892
+ `;
8893
+ };
8894
+ var applyConfiguration = async (client, config, state, plan, log = () => {}) => {
8895
+ const changes = (kind, deletes = false) => plan.changes.filter((change) => change.kind === kind && change.action === "delete" === deletes);
8896
+ const plural = (count, noun, many = `${noun}s`) => `${count} ${count === 1 ? noun : many}`;
8897
+ const policyIds = new Map(state.policies.map((policy) => [policy.name, policy.id]));
8898
+ const policyIdOf = (name) => policyIds.get(name);
8899
+ for (const change of changes("policy")) {
8900
+ const { presetId, settings, description } = config.policies[change.name];
8901
+ const existing = state.policies.find((policy) => policy.name === change.name);
8902
+ if (existing) {
8903
+ await client.policies.update({
8904
+ policyId: existing.id,
8905
+ revision: existing.revision,
8906
+ ...description !== undefined && { description },
8907
+ ...settings && { settings }
8908
+ });
8909
+ log(`Updated policy "${change.name}".`);
8910
+ continue;
8911
+ }
8912
+ const created = await client.policies.create({
8913
+ name: change.name,
8914
+ ...description !== undefined && { description },
8915
+ ...presetId ? { presetId } : { settings }
8916
+ });
8917
+ policyIds.set(change.name, created.id);
8918
+ if (presetId && settings)
8919
+ await client.policies.update({
8920
+ policyId: created.id,
8921
+ revision: created.revision,
8922
+ settings
8923
+ });
8924
+ log(`Created policy "${change.name}".`);
8925
+ }
8926
+ for (const change of changes("assignment")) {
8927
+ await client.policies.assign({ policyId: policyIdOf(change.name) });
8928
+ log(`The project now moderates with policy "${change.name}".`);
8929
+ }
8930
+ let revision = state.settingsRevision;
8931
+ const fields = changes("metadataField");
8932
+ if (fields.length) {
8933
+ ({ revision } = await client.metadataFields.ensure({
8934
+ revision,
8935
+ fields: fields.map((change) => ({
8936
+ id: change.name,
8937
+ ...config.metadataFields[change.name]
8938
+ }))
8939
+ }));
8940
+ log(`Saved ${plural(fields.length, "metadata field")}.`);
8941
+ }
8942
+ for (const change of changes("metadataField", true)) {
8943
+ await client.metadataFields.delete({ fieldId: change.name, revision });
8944
+ ({ revision } = await client.metadataFields.list());
8945
+ log(`Deleted metadata field "${change.name}".`);
8946
+ }
8947
+ if (changes("settings").length) {
8948
+ await client.projectSettings.update({
8949
+ revision,
8950
+ settings: { ...state.settings, ...config.settings }
8951
+ });
8952
+ log("Saved the project settings.");
8953
+ }
8954
+ const lenses = changes("lens");
8955
+ if (lenses.length) {
8956
+ await client.ensureLenses({
8957
+ lenses: lenses.map((change) => lensValues(change.name, config.lenses[change.name]))
8958
+ });
8959
+ log(`Saved ${plural(lenses.length, "lens", "lenses")}.`);
8960
+ }
8961
+ for (const change of changes("lens", true)) {
8962
+ const lens = state.lenses.find((candidate) => candidate.identifier === change.name);
8963
+ await client.lenses.delete({ lensId: lens.id });
8964
+ log(`Deleted lens "${change.name}".`);
8965
+ }
8966
+ const presets = changes("uploadPreset");
8967
+ if (presets.length) {
8968
+ await client.uploadPresets.ensure({
8969
+ uploadPresets: presets.map((change) => {
8970
+ const { policy, ...preset } = config.uploadPresets[change.name];
8971
+ const existing = state.uploadPresets.find((candidate) => candidate.key === change.name);
8972
+ return {
8973
+ ...preset,
8974
+ key: change.name,
8975
+ revision: existing?.revision ?? 0,
8976
+ policyId: policy === undefined ? null : policyIdOf(policy)
8977
+ };
8978
+ })
8979
+ });
8980
+ log(`Saved ${plural(presets.length, "upload preset")}.`);
8981
+ }
8982
+ for (const change of changes("uploadPreset", true)) {
8983
+ const preset = state.uploadPresets.find((candidate) => candidate.key === change.name);
8984
+ await client.uploadPresets.delete({ uploadPresetId: preset.id });
8985
+ log(`Deleted upload preset "${change.name}".`);
8986
+ }
8987
+ };
8988
+
8560
8989
  // src/cli/listen.ts
8561
8990
  import { randomBytes } from "node:crypto";
8562
8991
 
@@ -8711,7 +9140,7 @@ function slugify2(input) {
8711
9140
  return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
8712
9141
  }
8713
9142
  var captureStackTrace2 = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
8714
- function isObject2(data) {
9143
+ function isObject3(data) {
8715
9144
  return typeof data === "object" && data !== null && !Array.isArray(data);
8716
9145
  }
8717
9146
  var allowsEval2 = /* @__PURE__ */ cached2(() => {
@@ -8727,7 +9156,7 @@ var allowsEval2 = /* @__PURE__ */ cached2(() => {
8727
9156
  }
8728
9157
  });
8729
9158
  function isPlainObject3(o) {
8730
- if (isObject2(o) === false)
9159
+ if (isObject3(o) === false)
8731
9160
  return false;
8732
9161
  const ctor = o.constructor;
8733
9162
  if (ctor === undefined)
@@ -8735,7 +9164,7 @@ function isPlainObject3(o) {
8735
9164
  if (typeof ctor !== "function")
8736
9165
  return true;
8737
9166
  const prot = ctor.prototype;
8738
- if (isObject2(prot) === false)
9167
+ if (isObject3(prot) === false)
8739
9168
  return false;
8740
9169
  if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false)
8741
9170
  return false;
@@ -11249,7 +11678,7 @@ var $ZodObject2 = /* @__PURE__ */ $constructor2("$ZodObject", (inst, def) => {
11249
11678
  }
11250
11679
  return propValues;
11251
11680
  });
11252
- const isObject$1 = isObject2;
11681
+ const isObject$1 = isObject3;
11253
11682
  const catchall = def.catchall;
11254
11683
  let value;
11255
11684
  const memo = globalConfig2.memoizer;
@@ -11397,7 +11826,7 @@ var $ZodObjectJIT2 = /* @__PURE__ */ $constructor2("$ZodObjectJIT", (inst, def)
11397
11826
  return doc.compile();
11398
11827
  };
11399
11828
  let fastpass;
11400
- const isObject$2 = isObject2;
11829
+ const isObject$2 = isObject3;
11401
11830
  const jit = !globalConfig2.jitless;
11402
11831
  const fastEnabled = jit && allowsEval2.value;
11403
11832
  const catchall = def.catchall;
@@ -11587,7 +12016,7 @@ var $ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor2("$ZodDiscriminatedUn
11587
12016
  const disc = cached2(() => discriminatorMap(def));
11588
12017
  inst._zod.parse = (payload, ctx) => {
11589
12018
  const input = payload.value;
11590
- if (!isObject2(input)) {
12019
+ if (!isObject3(input)) {
11591
12020
  payload.issues.push({
11592
12021
  code: "invalid_type",
11593
12022
  expected: "object",
@@ -16903,6 +17332,8 @@ var createWebhookHeaders = async (options) => {
16903
17332
  };
16904
17333
  // src/cli/listen.ts
16905
17334
  var FORWARD_TIMEOUT_MS = 1e4;
17335
+ var RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 15000, 30000];
17336
+ var MAX_RETRY_AFTER_MS = 60000;
16906
17337
  var MAX_BACKOFF_MS = 30000;
16907
17338
  var FATAL_ERROR_CODES = new Set([
16908
17339
  "api-key/missing",
@@ -16918,7 +17349,7 @@ var forwardEvent = async (event, options) => {
16918
17349
  const headers = await createWebhookHeaders({
16919
17350
  secret: options.secret,
16920
17351
  body,
16921
- deliveryId: newId("dlv")
17352
+ deliveryId: options.deliveryId ?? newId("dlv")
16922
17353
  });
16923
17354
  const response = await (options.fetchImpl ?? fetch)(options.forwardTo, {
16924
17355
  method: "POST",
@@ -16926,7 +17357,13 @@ var forwardEvent = async (event, options) => {
16926
17357
  body,
16927
17358
  signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS)
16928
17359
  });
16929
- return { ok: response.ok, status: response.status, durationMs: Date.now() - startedAt };
17360
+ const retryAfter = Number(response.headers.get("retry-after"));
17361
+ return {
17362
+ ok: response.ok,
17363
+ status: response.status,
17364
+ durationMs: Date.now() - startedAt,
17365
+ ...(response.status === 429 || response.status === 503) && Number.isFinite(retryAfter) && retryAfter > 0 ? { retryAfterSeconds: retryAfter } : {}
17366
+ };
16930
17367
  } catch (error) {
16931
17368
  const cause = error.cause?.code;
16932
17369
  return {
@@ -16936,10 +17373,12 @@ var forwardEvent = async (event, options) => {
16936
17373
  };
16937
17374
  }
16938
17375
  };
17376
+ var isRetryable = (result) => !result.ok && (result.status === undefined || result.status === 408 || result.status === 425 || result.status === 429 || result.status >= 500);
16939
17377
  var formatTime = (date) => date.toTimeString().slice(0, 8);
16940
- var formatForwardLine = (event, result, now = new Date) => {
17378
+ var formatForwardLine = (event, result, now = new Date, retry) => {
16941
17379
  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]`;
17380
+ 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`}` : "";
17381
+ return `${formatTime(now)} ${event.type.padEnd(16)} ${event.id} → ${outcome} [${result.durationMs}ms]${attempt}`;
16943
17382
  };
16944
17383
  var sleep2 = (ms, signal) => new Promise((resolve) => {
16945
17384
  if (signal?.aborted)
@@ -16950,6 +17389,24 @@ var sleep2 = (ms, signal) => new Promise((resolve) => {
16950
17389
  resolve();
16951
17390
  }, { once: true });
16952
17391
  });
17392
+ var deliverEvent = async (event, options) => {
17393
+ const log = options.log ?? ((line) => process.stdout.write(`${line}
17394
+ `));
17395
+ const delays = options.retryDelaysMs ?? RETRY_DELAYS_MS;
17396
+ const attempts = delays.length + 1;
17397
+ const deliveryId = newId("dlv");
17398
+ for (let attempt = 1;; attempt++) {
17399
+ const result = await forwardEvent(event, { ...options, deliveryId });
17400
+ const baseDelay = delays[attempt - 1];
17401
+ const delayMs = isRetryable(result) && baseDelay !== undefined ? Math.max(baseDelay, Math.min(MAX_RETRY_AFTER_MS, (result.retryAfterSeconds ?? 0) * 1000)) : undefined;
17402
+ log(formatForwardLine(event, result, new Date, { attempt, attempts, delayMs }));
17403
+ if (delayMs === undefined || options.signal?.aborted)
17404
+ return result;
17405
+ await sleep2(delayMs, options.signal);
17406
+ if (options.signal?.aborted)
17407
+ return result;
17408
+ }
17409
+ };
16953
17410
  var unavailableEventTypes = (excludedTypes, requested) => requested.size ? excludedTypes.filter((type) => requested.has(type)) : [...excludedTypes];
16954
17411
  var describeEventTypes = (requested, unavailableTypes) => {
16955
17412
  const unavailable = new Set(unavailableTypes);
@@ -17000,7 +17457,9 @@ var listen = async (options) => {
17000
17457
  for (const event of inAssetOrder(page.items)) {
17001
17458
  if (eventTypes.size > 0 && !eventTypes.has(event.type))
17002
17459
  continue;
17003
- log(formatForwardLine(event, await forwardEvent(event, options)));
17460
+ await deliverEvent(event, { ...options, log });
17461
+ if (signal?.aborted)
17462
+ return;
17004
17463
  }
17005
17464
  cursor = page.nextCursor;
17006
17465
  if (!page.hasMore)
@@ -17137,21 +17596,34 @@ Usage:
17137
17596
  calmlens logout
17138
17597
  calmlens listen --forward-to <url> [options]
17139
17598
  calmlens trigger [sexual|violence|self-harm|harassment|hate|criminal-activity|clean] [options]
17599
+ calmlens plan [--config <path>] [--prune]
17600
+ calmlens apply [--config <path>] [--prune]
17140
17601
 
17141
- Run it with \`npx calmlens\`, or install it with \`npm install -g calmlens\`.
17602
+ Install it with \`brew install calmlens/sdks/calmlens\` (after
17603
+ \`brew tap calmlens/sdks https://github.com/CalmLens/sdks\`), the install script at
17604
+ https://calmlens.com/install.sh, a download from https://github.com/CalmLens/sdks/releases,
17605
+ or \`npm install -g calmlens\`. See https://calmlens.com/docs/guides/local-development.
17142
17606
 
17143
17607
  Commands:
17144
17608
  login Sign in through your browser and choose a project. The CLI keeps the key it
17145
17609
  receives, so listen and trigger need no API key or project ID.
17146
17610
  logout Revoke and forget the key from login.
17147
17611
  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.
17612
+ body (id, projectId, actor, type, severity, title, description, assetId,
17613
+ assetSequence, asset, facts, createdAt) and headers (x-calmlens-delivery,
17614
+ x-calmlens-timestamp, x-calmlens-signature: v1=...) as real deliveries. No
17615
+ public URL needed. Like real deliveries, network errors, timeouts, 408, 425, 429
17616
+ and 5xx responses are retried, up to 7 attempts with the same delivery ID, here
17617
+ after 1, 2, 4, 8, 15 and 30 seconds (longer if Retry-After asks, up to 60).
17151
17618
  trigger Moderate a harmless test comment so CalmLens creates real events. Each trigger
17152
17619
  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).
17620
+ project's test input key (Project settings → Test inputs in the portal).
17621
+ plan Compare calmlens.config.json with the project: its policies (by name, with the
17622
+ project's policy), upload presets (by key), lenses (by identifier), metadata
17623
+ fields (by ID) and settings. Prints what apply would change and changes nothing.
17624
+ apply Make the changes plan prints. Each is sent with the revision just read, so a
17625
+ change made meanwhile in the portal or by another deploy is refused, not lost.
17626
+ See https://calmlens.com/docs/guides/configuration-as-code.
17155
17627
 
17156
17628
  Options:
17157
17629
  --forward-to <url> Local webhook URL, e.g. http://localhost:3000/api/webhooks/calmlens
@@ -17164,6 +17636,9 @@ Options:
17164
17636
  --test-key <key> Project's test input key, for trigger (default: $CALMLENS_TEST_INPUT_KEY)
17165
17637
  --env-file <path> Load environment variables from a file, e.g. .env.local
17166
17638
  --interval <seconds> Seconds between checks for new events (default: 2)
17639
+ --config <path> For plan and apply: the configuration file (default: calmlens.config.json)
17640
+ --prune For plan and apply: also delete upload presets, lenses and metadata
17641
+ fields the file doesn't list (never policies)
17167
17642
  --api-url <url> API base URL (default: $CALMLENS_API_URL or https://api.calmlens.com/v1)
17168
17643
  -v, --version Show the CLI version
17169
17644
  -h, --help Show this help
@@ -17194,6 +17669,8 @@ var main = async () => {
17194
17669
  interval: { type: "string" },
17195
17670
  "api-url": { type: "string" },
17196
17671
  "read-only": { type: "boolean" },
17672
+ config: { type: "string" },
17673
+ prune: { type: "boolean" },
17197
17674
  "no-browser": { type: "boolean" },
17198
17675
  help: { type: "boolean", short: "h" },
17199
17676
  version: { type: "boolean", short: "v" }
@@ -17320,6 +17797,33 @@ var main = async () => {
17320
17797
  }
17321
17798
  return;
17322
17799
  }
17800
+ if (command === "plan" || command === "apply") {
17801
+ const path = values.config ?? "calmlens.config.json";
17802
+ let text;
17803
+ try {
17804
+ text = await readFile2(path, "utf8");
17805
+ } catch {
17806
+ return fail(`Couldn't read ${path}. Pass --config <path> to use another file.`);
17807
+ }
17808
+ try {
17809
+ const config = parseConfiguration(text, path);
17810
+ const state = await readConfigurationState(client, config);
17811
+ const plan = planConfiguration(config, state, { prune: Boolean(values.prune) });
17812
+ process.stdout.write(formatPlan(plan));
17813
+ if (command === "apply" && plan.changes.length) {
17814
+ await applyConfiguration(client, config, state, plan, (line) => process.stdout.write(`${line}
17815
+ `));
17816
+ process.stdout.write(`Applied.
17817
+ `);
17818
+ }
17819
+ } catch (error) {
17820
+ if (error instanceof CalmLensError && error.code.endsWith("/revision-conflict"))
17821
+ fail(`${describeError(error)}
17822
+ Something changed since it was read. Run \`calmlens ${command}\` again to see the latest differences.`);
17823
+ fail(error instanceof ConfigurationError ? error.message : `${command === "apply" ? "Apply" : "Plan"} failed: ${describeError(error)}`);
17824
+ }
17825
+ return;
17826
+ }
17323
17827
  fail(`Unknown command "${command}".
17324
17828
 
17325
17829
  ${HELP}`);