@marktiderman/genesis-forms 0.7.0 → 0.8.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.
@@ -72,10 +72,10 @@ async function timedFetch(deps, url, init, signal) {
72
72
  throw error;
73
73
  }
74
74
  }
75
- async function resolveOption(what, option, config) {
75
+ async function resolveOption(what, option, config, context = {}) {
76
76
  if (typeof option !== "function") return option;
77
77
  try {
78
- return await option(config);
78
+ return await option(config, context);
79
79
  } catch (error) {
80
80
  if (error instanceof DeliveryError) throw error;
81
81
  throw new DeliveryError(`${what} could not be resolved`);
@@ -772,6 +772,53 @@ for (const manifest of [...builtins, ...structuredFieldTypes, calculatedFieldTyp
772
772
  function own(record, key) {
773
773
  return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : void 0;
774
774
  }
775
+ function resolve(operand, scope) {
776
+ if ("field" in operand) return own(scope.values, operand.field);
777
+ if ("hidden" in operand) return own(scope.hidden, operand.hidden);
778
+ return operand.value;
779
+ }
780
+ function deepEqual(a, b) {
781
+ if (a === b) return true;
782
+ if (Array.isArray(a) && Array.isArray(b)) {
783
+ return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
784
+ }
785
+ return false;
786
+ }
787
+ function evaluate(condition, scope) {
788
+ if ("all" in condition) return condition.all.every((c) => evaluate(c, scope));
789
+ if ("any" in condition) return condition.any.some((c) => evaluate(c, scope));
790
+ if ("not" in condition) return !evaluate(condition.not, scope);
791
+ const left = resolve(condition.left, scope);
792
+ const right = condition.right ? resolve(condition.right, scope) : void 0;
793
+ const field = "field" in condition.left ? scope.fields.get(condition.left.field) : void 0;
794
+ const unanswered = isEmptyValue(left, field);
795
+ switch (condition.op) {
796
+ case "answered":
797
+ return !unanswered;
798
+ case "empty":
799
+ return unanswered;
800
+ case "eq":
801
+ return !unanswered && deepEqual(left, right);
802
+ case "neq":
803
+ return unanswered || !deepEqual(left, right);
804
+ case "lt":
805
+ case "lte":
806
+ case "gt":
807
+ case "gte": {
808
+ if (typeof left !== "number" || typeof right !== "number") return false;
809
+ if (condition.op === "lt") return left < right;
810
+ if (condition.op === "lte") return left <= right;
811
+ if (condition.op === "gt") return left > right;
812
+ return left >= right;
813
+ }
814
+ case "in":
815
+ return !unanswered && Array.isArray(right) && right.some((r) => deepEqual(r, left));
816
+ case "contains":
817
+ if (unanswered) return false;
818
+ if (Array.isArray(left)) return left.some((l) => deepEqual(l, right));
819
+ return typeof left === "string" && typeof right === "string" && left.toLowerCase().includes(right.toLowerCase());
820
+ }
821
+ }
775
822
  function withheld(def, field) {
776
823
  return def.settings?.anonymous === true && field?.identifying === true;
777
824
  }
@@ -1139,9 +1186,20 @@ function sheetsDestination(options) {
1139
1186
  async function run(items, config, deliveryOptions) {
1140
1187
  if (!items.length) return { ok: true };
1141
1188
  const { spreadsheetId, sheetName } = configOf(config);
1142
- const account = await resolveOption("The sheet destination's account", options.account, config);
1143
1189
  const signal = deliveryOptions.signal;
1144
- const token = await googleAccessToken(account, { ...options, signal });
1190
+ const context = { destinationId: deliveryOptions.destinationId };
1191
+ let account = null;
1192
+ let token;
1193
+ if (options.accessToken) {
1194
+ token = await resolveOption("The sheet destination's access token", options.accessToken, config, context);
1195
+ if (typeof token !== "string" || !token) throw new DeliveryError("The sheet destination has no access token");
1196
+ } else if (options.account) {
1197
+ account = await resolveOption("The sheet destination's account", options.account, config, context);
1198
+ token = await googleAccessToken(account, { ...options, signal });
1199
+ } else {
1200
+ throw new DeliveryError("The sheet destination has neither an account nor an access token");
1201
+ }
1202
+ const sharedWith = account ? `is the sheet shared with ${account.clientEmail}?` : "is the sheet still connected to its Google account?";
1145
1203
  const base = `${SHEETS_API}/${encodeURIComponent(spreadsheetId)}`;
1146
1204
  const escape = options.escapeFormulas === true;
1147
1205
  const call = async (what, url, init = {}) => {
@@ -1153,12 +1211,12 @@ function sheetsDestination(options) {
1153
1211
  );
1154
1212
  if (!response.ok) {
1155
1213
  discard(response);
1156
- if (what === "append" && (response.status === 400 || response.status === 404)) {
1214
+ if ((what === "append" || what === "update rows") && (response.status === 400 || response.status === 404)) {
1157
1215
  throw new StaleSheetError(`Google Sheets append answered ${response.status}`, { status: response.status });
1158
1216
  }
1159
1217
  if (response.status === 403 || response.status === 404) {
1160
1218
  throw new DeliveryError(
1161
- `Google Sheets ${what} answered ${response.status}: is the sheet shared with ${account.clientEmail}?`,
1219
+ `Google Sheets ${what} answered ${response.status}: ${sharedWith}`,
1162
1220
  { status: response.status }
1163
1221
  );
1164
1222
  }
@@ -1254,14 +1312,45 @@ function sheetsDestination(options) {
1254
1312
  }
1255
1313
  let skipped = [];
1256
1314
  async function append(state2) {
1257
- let pending = items.map((item, i) => ({ id: item.submission.id, row: rows[i].row }));
1258
- if (deliveryOptions.redelivery) {
1315
+ const byId = /* @__PURE__ */ new Map();
1316
+ items.forEach((item, i) => {
1317
+ const id = item.submission.id;
1318
+ const update = (item.update ?? deliveryOptions.update) === true || byId.get(id)?.update === true;
1319
+ byId.delete(id);
1320
+ byId.set(id, { id, row: rows[i].row, update });
1321
+ });
1322
+ let pending = [...byId.values()];
1323
+ const updating = pending.some((p) => p.update);
1324
+ const overwrite = [];
1325
+ skipped = [];
1326
+ if (deliveryOptions.redelivery || updating) {
1259
1327
  const column = columnLetter(state2.header.indexOf("id"));
1260
- const from = state2.last_row > 0 ? Math.max(2, state2.last_row - DEDUPE_WINDOW) : 2;
1328
+ const from = !updating && state2.last_row > 0 ? Math.max(2, state2.last_row - DEDUPE_WINDOW) : 2;
1261
1329
  const ids = await call("read ids", range(`${column}${from}:${column}`));
1262
- const present = new Set((ids.values ?? []).map((r) => String(r?.[0] ?? "")));
1263
- skipped = pending.filter((p) => present.has(p.id)).map((p) => p.id);
1264
- pending = pending.filter((p) => !present.has(p.id));
1330
+ const rowOf = /* @__PURE__ */ new Map();
1331
+ (ids.values ?? []).forEach((r, i) => {
1332
+ const id = String(r?.[0] ?? "");
1333
+ if (id && !rowOf.has(id)) rowOf.set(id, from + i);
1334
+ });
1335
+ pending = pending.filter((p) => {
1336
+ const at = rowOf.get(p.id);
1337
+ if (at === void 0) return true;
1338
+ if (p.update) overwrite.push({ at, row: p.row });
1339
+ else skipped.push(p.id);
1340
+ return false;
1341
+ });
1342
+ }
1343
+ if (overwrite.length) {
1344
+ await call("update rows", `${base}/values:batchUpdate`, {
1345
+ method: "POST",
1346
+ body: JSON.stringify({
1347
+ valueInputOption: "RAW",
1348
+ data: overwrite.map((o) => ({
1349
+ range: `${quoteSheet(sheetName)}!A${o.at}`,
1350
+ values: [rowFor(state2.header, o.row, escape)]
1351
+ }))
1352
+ })
1353
+ });
1265
1354
  }
1266
1355
  if (!pending.length) return state2;
1267
1356
  const result = await call(
@@ -1296,11 +1385,147 @@ function sheetsDestination(options) {
1296
1385
  };
1297
1386
  return {
1298
1387
  kind: "sheet",
1299
- deliver: (submission, definition, config, deliveryOptions = {}) => guarded([{ submission, definition, deliveryId: deliveryOptions.deliveryId }], config, deliveryOptions),
1388
+ deliver: (submission, definition, config, deliveryOptions = {}) => guarded(
1389
+ [{ submission, definition, deliveryId: deliveryOptions.deliveryId, update: deliveryOptions.update }],
1390
+ config,
1391
+ deliveryOptions
1392
+ ),
1300
1393
  deliverBatch: (items, config, deliveryOptions = {}) => guarded(items, config, deliveryOptions)
1301
1394
  };
1302
1395
  }
1303
1396
 
1397
+ // src/destinations/hook-url.ts
1398
+ var MAX_HOOK_URL_LENGTH = 2048;
1399
+ var SLACK_HOSTS = /* @__PURE__ */ new Set(["hooks.slack.com"]);
1400
+ var HookUrlError = class extends DeliveryError {
1401
+ name = "HookUrlError";
1402
+ };
1403
+ var NOT_PUBLIC = "The address must be on the public internet.";
1404
+ var INTERNAL_SUFFIXES = [".localhost", ".local", ".internal", ".intranet", ".lan", ".home.arpa"];
1405
+ function ipv4Bytes(ip) {
1406
+ const parts = ip.split(".");
1407
+ if (parts.length !== 4) return null;
1408
+ const bytes = parts.map((p) => /^\d{1,3}$/.test(p) ? Number(p) : NaN);
1409
+ return bytes.every((b) => Number.isInteger(b) && b >= 0 && b <= 255) ? bytes : null;
1410
+ }
1411
+ function publicIpv4(b) {
1412
+ const [a, c] = [b[0], b[1]];
1413
+ if (a === 0 || a === 10 || a === 127) return false;
1414
+ if (a === 100 && c >= 64 && c <= 127) return false;
1415
+ if (a === 169 && c === 254) return false;
1416
+ if (a === 172 && c >= 16 && c <= 31) return false;
1417
+ if (a === 192 && c === 168) return false;
1418
+ if (a === 192 && c === 0 && (b[2] === 0 || b[2] === 2)) return false;
1419
+ if (a === 198 && (c === 18 || c === 19)) return false;
1420
+ if (a === 198 && c === 51 && b[2] === 100) return false;
1421
+ if (a === 203 && c === 0 && b[2] === 113) return false;
1422
+ if (a >= 224) return false;
1423
+ return true;
1424
+ }
1425
+ function ipv6Bytes(ip) {
1426
+ let text = ip.replace(/^\[|\]$/g, "").toLowerCase();
1427
+ const zone = text.indexOf("%");
1428
+ if (zone >= 0) text = text.slice(0, zone);
1429
+ let tail = [];
1430
+ const lastColon = text.lastIndexOf(":");
1431
+ if (text.slice(lastColon + 1).includes(".")) {
1432
+ const v4 = ipv4Bytes(text.slice(lastColon + 1));
1433
+ if (!v4) return null;
1434
+ tail = v4;
1435
+ text = text.slice(0, lastColon + 1) + "0:0";
1436
+ }
1437
+ const halves = text.split("::");
1438
+ if (halves.length > 2) return null;
1439
+ const groups = (s) => s === "" ? [] : s.split(":");
1440
+ const head = groups(halves[0]);
1441
+ const rest = halves.length === 2 ? groups(halves[1]) : [];
1442
+ const missing = 8 - head.length - rest.length;
1443
+ if (halves.length === 1 ? missing !== 0 : missing < 1) return null;
1444
+ const all = [...head, ...Array(halves.length === 2 ? missing : 0).fill("0"), ...rest];
1445
+ const bytes = [];
1446
+ for (const g of all) {
1447
+ if (!/^[0-9a-f]{1,4}$/.test(g)) return null;
1448
+ const n = parseInt(g, 16);
1449
+ bytes.push(n >> 8, n & 255);
1450
+ }
1451
+ if (tail.length) bytes.splice(12, 4, ...tail);
1452
+ return bytes;
1453
+ }
1454
+ function publicIpv6(b) {
1455
+ const zeros = (from, to) => b.slice(from, to).every((x) => x === 0);
1456
+ if (zeros(0, 16)) return false;
1457
+ if (zeros(0, 15) && b[15] === 1) return false;
1458
+ if (zeros(0, 10) && b[10] === 255 && b[11] === 255) return publicIpv4(b.slice(12));
1459
+ if (zeros(0, 12)) return publicIpv4(b.slice(12));
1460
+ if (b[0] === 0 && b[1] === 100 && b[2] === 255 && b[3] === 155 && zeros(4, 12)) return publicIpv4(b.slice(12));
1461
+ if ((b[0] & 254) === 252) return false;
1462
+ if (b[0] === 254 && (b[1] & 192) === 128) return false;
1463
+ if (b[0] === 254 && (b[1] & 192) === 192) return false;
1464
+ if (b[0] === 255) return false;
1465
+ if (b[0] === 32 && b[1] === 1 && b[2] === 13 && b[3] === 184) return false;
1466
+ if (b[0] === 32 && b[1] === 1 && b[2] === 0 && b[3] === 0) return false;
1467
+ if (b[0] === 32 && b[1] === 2) return publicIpv4(b.slice(2, 6));
1468
+ if (b[0] === 1 && zeros(1, 8)) return false;
1469
+ return true;
1470
+ }
1471
+ function isPublicAddress(ip) {
1472
+ const v4 = ipv4Bytes(ip);
1473
+ if (v4) return publicIpv4(v4);
1474
+ const v6 = ipv6Bytes(ip);
1475
+ return v6 ? publicIpv6(v6) : false;
1476
+ }
1477
+ function isIpLiteral(host) {
1478
+ return ipv4Bytes(host) !== null || host.startsWith("[");
1479
+ }
1480
+ function parseHookUrl(raw, kind = "webhook") {
1481
+ const text = raw.trim();
1482
+ if (!text) throw new HookUrlError("Paste the address to send responses to.");
1483
+ if (text.length > MAX_HOOK_URL_LENGTH) throw new HookUrlError("That address is too long.");
1484
+ let url;
1485
+ try {
1486
+ url = new URL(text);
1487
+ } catch {
1488
+ throw new HookUrlError("That doesn't look like a web address.");
1489
+ }
1490
+ if (url.protocol !== "https:") throw new HookUrlError("The address must start with https://.");
1491
+ if (url.username || url.password) throw new HookUrlError("The address can't include a user name or password.");
1492
+ if (url.port && url.port !== "443") throw new HookUrlError("The address must use the standard https port.");
1493
+ url.hash = "";
1494
+ const host = url.hostname.replace(/\.$/, "");
1495
+ if (kind === "slack") {
1496
+ if (!SLACK_HOSTS.has(host) || !url.pathname.startsWith("/services/")) {
1497
+ throw new HookUrlError("Use a Slack incoming webhook address, which starts with https://hooks.slack.com/services/.");
1498
+ }
1499
+ return url;
1500
+ }
1501
+ if (isIpLiteral(host)) {
1502
+ if (!isPublicAddress(host)) throw new HookUrlError(NOT_PUBLIC);
1503
+ return url;
1504
+ }
1505
+ if (!host.includes(".") || host === "localhost" || INTERNAL_SUFFIXES.some((suffix) => host.endsWith(suffix))) {
1506
+ throw new HookUrlError(NOT_PUBLIC);
1507
+ }
1508
+ return url;
1509
+ }
1510
+ async function checkHookHost(url, resolve2) {
1511
+ const host = url.hostname.replace(/\.$/, "");
1512
+ if (isIpLiteral(host)) {
1513
+ if (!isPublicAddress(host)) throw new HookUrlError(NOT_PUBLIC);
1514
+ return;
1515
+ }
1516
+ let addresses;
1517
+ try {
1518
+ addresses = await resolve2(host);
1519
+ } catch {
1520
+ throw new HookUrlError(`${host} couldn't be found`, { retryable: true });
1521
+ }
1522
+ if (!addresses.length) throw new HookUrlError(`${host} couldn't be found`, { retryable: true });
1523
+ if (!addresses.every(isPublicAddress)) throw new HookUrlError(NOT_PUBLIC);
1524
+ }
1525
+ function hookHost(url) {
1526
+ return url.hostname.replace(/\.$/, "").toLowerCase();
1527
+ }
1528
+
1304
1529
  // src/destinations/webhook.ts
1305
1530
  var MIN_SECRET_BYTES = 16;
1306
1531
  var STRICT_BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
@@ -1318,6 +1543,9 @@ function secretKey(secret) {
1318
1543
  async function hmacKey(secret, usage) {
1319
1544
  return crypto.subtle.importKey("raw", secretKey(secret), { name: "HMAC", hash: "SHA-256" }, false, [usage]);
1320
1545
  }
1546
+ function newWebhookSecret() {
1547
+ return `whsec_${base64(crypto.getRandomValues(new Uint8Array(32)))}`;
1548
+ }
1321
1549
  async function signWebhook(secret, id, timestamp, body) {
1322
1550
  const key = await hmacKey(secret, "sign");
1323
1551
  const mac = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${id}.${timestamp}.${body}`));
@@ -1440,15 +1668,17 @@ function webhookDestination(options) {
1440
1668
  kind: "webhook",
1441
1669
  async deliver(submission, definition, config, deliveryOptions = {}) {
1442
1670
  try {
1443
- const url = checkWebhookUrl(configString(config, "url"), options);
1444
- const secret = await resolveOption("The webhook secret", options.secret, config);
1671
+ const context = { destinationId: deliveryOptions.destinationId };
1672
+ const raw = options.url ? await resolveOption("The webhook url", options.url, config, context) : configString(config, "url");
1673
+ const url = checkWebhookUrl(typeof raw === "string" ? raw.trim() : "", options);
1674
+ if (options.resolveHost && !options.allowPrivateHosts) await checkHookHost(url, options.resolveHost);
1675
+ const secret = await resolveOption("The webhook secret", options.secret, config, context);
1445
1676
  if (!secret) throw new DeliveryError("The webhook secret is not set");
1446
1677
  const now = options.now?.() ?? Date.now();
1447
1678
  const id = deliveryOptions.deliveryId ?? submission.id;
1448
1679
  const timestamp = Math.floor(now / 1e3);
1449
- const body = JSON.stringify(
1450
- webhookPayload(submission, definition, { sensitive: options.sensitive, type: options.type, now })
1451
- );
1680
+ const type = options.type ?? (deliveryOptions.update ? "form.updated" : void 0);
1681
+ const body = JSON.stringify(webhookPayload(submission, definition, { sensitive: options.sensitive, type, now }));
1452
1682
  const response = await timedFetch(
1453
1683
  options,
1454
1684
  url.toString(),
@@ -1481,6 +1711,386 @@ function webhookDestination(options) {
1481
1711
  };
1482
1712
  }
1483
1713
 
1484
- export { DEDUPE_WINDOW, DEFAULT_SHEET_NAME, DeliveryError, GOOGLE_TOKEN_URL, HEADER_SCAN_ROWS, MAX_RECIPIENTS, REQUEST_TIMEOUT_MS, RESEND_API, SENSITIVE_MASK, SHEETS_API, SHEETS_SCOPE, answerCell, checkWebhookUrl, clearGoogleTokenCache, columnLetter, deliveryFailure, emailBody, emailDestination, escapeFormula, escapeHtml, googleAccessToken, headerSafe, httpError, idempotencyKey, isPrivateHost, isRetryableStatus, isSafeAddress, isSafeFrom, mergeHeader, renderEmail, resendProvider, responseRow, retryAfterSeconds, rowFor, sheetsDestination, signJwt, signWebhook, verifyWebhook, visibleInputs, webhookDestination, webhookPayload };
1714
+ // src/destinations/slack.ts
1715
+ var SLACK_VALUE_LIMIT = 1500;
1716
+ function escapeSlack(text) {
1717
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1718
+ }
1719
+ var cut = (text) => text.length > SLACK_VALUE_LIMIT ? `${text.slice(0, SLACK_VALUE_LIMIT)}\u2026` : text;
1720
+ function slackMessage(submission, definition, options = {}) {
1721
+ const title = definition.title || definition.id;
1722
+ const heading = options.heading ?? `${options.update ? "Updated response" : "New response"}: ${title}`;
1723
+ const lines = [`*${escapeSlack(heading)}*`];
1724
+ for (const [label, value] of options.lines ?? []) {
1725
+ if (value.trim()) lines.push(`*${escapeSlack(label)}*: ${escapeSlack(cut(value))}`);
1726
+ }
1727
+ const { row, labels } = responseRow(submission, definition, { sensitive: options.sensitive ?? "mask" });
1728
+ const omit = new Set(options.omit ?? []);
1729
+ let answered = 0;
1730
+ for (const [key, label] of Object.entries(labels)) {
1731
+ const text = String(row[key] ?? "");
1732
+ if (!text || omit.has(key)) continue;
1733
+ answered++;
1734
+ lines.push(`*${escapeSlack(label || key)}*: ${escapeSlack(cut(text))}`);
1735
+ }
1736
+ if (!answered) lines.push("_No answers._");
1737
+ const when = submission.submittedAt ? ` \xB7 ${escapeSlack(submission.submittedAt)}` : "";
1738
+ const link = options.link;
1739
+ lines.push(
1740
+ link && /^https?:\/\//i.test(link.url) ? `<${link.url.replace(/[<>|]/g, "")}|${escapeSlack(link.text ?? "Open the response").replace(/[|]/g, "")}>${when}` : `Response ${escapeSlack(submission.id)}${when}`
1741
+ );
1742
+ return { text: lines.join("\n") };
1743
+ }
1744
+ function slackDestination(options = {}) {
1745
+ return {
1746
+ kind: "slack",
1747
+ async deliver(submission, definition, config, deliveryOptions = {}) {
1748
+ try {
1749
+ const context = { destinationId: deliveryOptions.destinationId };
1750
+ const raw = options.url ? await resolveOption("The Slack webhook url", options.url, config, context) : configString(config, "url");
1751
+ if (typeof raw !== "string" || !raw.trim()) throw new DeliveryError("The Slack destination has no url");
1752
+ const url = parseHookUrl(raw, "slack");
1753
+ if (options.resolveHost) await checkHookHost(url, options.resolveHost);
1754
+ const update = deliveryOptions.update === true;
1755
+ const messageOptions = options.message ? await resolveOption(
1756
+ "The Slack message",
1757
+ () => options.message({ submission, definition, config, update, destinationId: deliveryOptions.destinationId }),
1758
+ config
1759
+ ) : {};
1760
+ const body = JSON.stringify(slackMessage(submission, definition, { update, ...messageOptions }));
1761
+ const response = await timedFetch(
1762
+ options,
1763
+ url.toString(),
1764
+ {
1765
+ method: "POST",
1766
+ redirect: "manual",
1767
+ headers: { "content-type": "application/json", "user-agent": "genesis-forms-slack/1" },
1768
+ body
1769
+ },
1770
+ deliveryOptions.signal
1771
+ );
1772
+ discard(response);
1773
+ if (response.status >= 200 && response.status < 300) return { ok: true };
1774
+ if (response.status === 0 || response.status >= 300 && response.status < 400) {
1775
+ throw new DeliveryError(`Slack answered ${response.status || "a redirect"}: redirects are not followed`, {
1776
+ ...response.status ? { status: response.status } : {}
1777
+ });
1778
+ }
1779
+ throw httpError("Slack", response);
1780
+ } catch (error) {
1781
+ return deliveryFailure(error);
1782
+ }
1783
+ }
1784
+ };
1785
+ }
1786
+
1787
+ // src/destinations/condition.ts
1788
+ var OPERATORS = /* @__PURE__ */ new Set(["eq", "neq", "lt", "lte", "gt", "gte", "in", "contains", "answered", "empty"]);
1789
+ var MAX_CONDITION_DEPTH = 10;
1790
+ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1791
+ function isOperand(v) {
1792
+ if (!isObject2(v)) return false;
1793
+ const keys = Object.keys(v);
1794
+ if (keys.length !== 1) return false;
1795
+ if (keys[0] === "field" || keys[0] === "hidden") return typeof v[keys[0]] === "string";
1796
+ return keys[0] === "value";
1797
+ }
1798
+ function isCondition(v, depth = 0) {
1799
+ if (!isObject2(v) || depth > MAX_CONDITION_DEPTH) return false;
1800
+ if ("all" in v) return Array.isArray(v["all"]) && v["all"].every((c) => isCondition(c, depth + 1));
1801
+ if ("any" in v) return Array.isArray(v["any"]) && v["any"].every((c) => isCondition(c, depth + 1));
1802
+ if ("not" in v) return isCondition(v["not"], depth + 1);
1803
+ return typeof v["op"] === "string" && OPERATORS.has(v["op"]) && isOperand(v["left"]) && (v["right"] === void 0 || isOperand(v["right"]));
1804
+ }
1805
+ function conditionOf(config) {
1806
+ const when = config["when"];
1807
+ if (when === void 0 || when === null) return null;
1808
+ if (!isCondition(when)) throw new DeliveryError("The destination's condition can't be read");
1809
+ return when;
1810
+ }
1811
+ function passesCondition(submission, definition, config) {
1812
+ const condition = conditionOf(config);
1813
+ if (!condition) return true;
1814
+ const fields = /* @__PURE__ */ new Map();
1815
+ for (const block of definition.blocks) if (block.kind === "field") fields.set(block.id, block);
1816
+ const hidden = /* @__PURE__ */ Object.create(null);
1817
+ for (const source of [submission.hidden, submission.context]) {
1818
+ for (const name of Object.keys(source ?? {})) {
1819
+ const value = own(source, name);
1820
+ if (value !== void 0) hidden[name] = value;
1821
+ }
1822
+ }
1823
+ return evaluate(condition, { values: submission.answers, hidden, fields });
1824
+ }
1825
+
1826
+ // src/destinations/google-oauth.ts
1827
+ var DRIVE_FILE_SCOPE = "https://www.googleapis.com/auth/drive.file";
1828
+ async function refreshGoogleAccessToken(client, refreshToken, options = {}) {
1829
+ if (!client.clientId || !client.clientSecret) throw new DeliveryError("The Google OAuth client id or secret is not set");
1830
+ if (!refreshToken) throw new DeliveryError("This sheet's Google connection is gone. Connect the sheet again.");
1831
+ const response = await timedFetch(
1832
+ options,
1833
+ GOOGLE_TOKEN_URL,
1834
+ {
1835
+ method: "POST",
1836
+ // The body holds the refresh token and client secret: never follow a redirect with it.
1837
+ redirect: "error",
1838
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1839
+ body: new URLSearchParams({
1840
+ grant_type: "refresh_token",
1841
+ refresh_token: refreshToken,
1842
+ client_id: client.clientId,
1843
+ client_secret: client.clientSecret
1844
+ }).toString()
1845
+ },
1846
+ options.signal
1847
+ );
1848
+ if (!response.ok) {
1849
+ const body2 = jsonObject(await response.json().catch(() => null));
1850
+ if (response.status === 400 && body2.error === "invalid_grant") {
1851
+ throw new DeliveryError("Google access to this sheet was removed. Connect the sheet again.", { status: 400 });
1852
+ }
1853
+ discard(response);
1854
+ throw httpError("Google token endpoint", response);
1855
+ }
1856
+ const body = jsonObject(await response.json().catch(() => null));
1857
+ if (typeof body.access_token !== "string" || !body.access_token) {
1858
+ throw new DeliveryError("Google token endpoint returned no access token", { retryable: true });
1859
+ }
1860
+ return {
1861
+ accessToken: body.access_token,
1862
+ expiresIn: typeof body.expires_in === "number" && body.expires_in > 0 ? body.expires_in : 3600,
1863
+ scope: typeof body.scope === "string" ? body.scope : DRIVE_FILE_SCOPE
1864
+ };
1865
+ }
1866
+ function jsonObject(value) {
1867
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
1868
+ }
1869
+ var cache2 = /* @__PURE__ */ new Map();
1870
+ function clearGoogleOAuthTokenCache() {
1871
+ cache2.clear();
1872
+ }
1873
+ async function googleOAuthAccessToken(client, refreshToken, options = {}) {
1874
+ if (!refreshToken) throw new DeliveryError("This sheet's Google connection is gone. Connect the sheet again.");
1875
+ const now = options.now?.() ?? Date.now();
1876
+ const key = await sha256Hex(`${client.clientId}
1877
+ ${refreshToken}`);
1878
+ const hit = cache2.get(key);
1879
+ if (hit && hit.expiresAt - 6e4 > now) return hit.token;
1880
+ const fresh = await refreshGoogleAccessToken(client, refreshToken, options);
1881
+ cache2.set(key, { token: fresh.accessToken, expiresAt: now + fresh.expiresIn * 1e3 });
1882
+ return fresh.accessToken;
1883
+ }
1884
+
1885
+ // src/destinations/secret-box.ts
1886
+ var enc = new TextEncoder();
1887
+ function secretKeyBytes(key) {
1888
+ if (typeof key !== "string") {
1889
+ if (key.length !== 32) throw new DeliveryError("The encryption key must be 32 bytes");
1890
+ return new Uint8Array(key);
1891
+ }
1892
+ const text = key.trim().replace(/=+$/, "");
1893
+ if (!text) throw new DeliveryError("The encryption key is not set");
1894
+ let bytes;
1895
+ try {
1896
+ bytes = fromBase64(text + "=".repeat((4 - text.length % 4) % 4));
1897
+ } catch {
1898
+ throw new DeliveryError("The encryption key is not base64");
1899
+ }
1900
+ if (bytes.length !== 32) throw new DeliveryError("The encryption key must be 32 bytes");
1901
+ return bytes;
1902
+ }
1903
+ async function deriveSecretKey(key, info) {
1904
+ if (!info) throw new DeliveryError("A sealing key needs its purpose (info)");
1905
+ const base = await crypto.subtle.importKey("raw", secretKeyBytes(key), "HKDF", false, ["deriveKey"]);
1906
+ return crypto.subtle.deriveKey(
1907
+ { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: enc.encode(info) },
1908
+ base,
1909
+ { name: "AES-GCM", length: 256 },
1910
+ false,
1911
+ ["encrypt", "decrypt"]
1912
+ );
1913
+ }
1914
+ async function sealSecret(key, plaintext, aad) {
1915
+ const iv = crypto.getRandomValues(new Uint8Array(12));
1916
+ const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: enc.encode(aad) }, key, enc.encode(plaintext));
1917
+ return `v1.${base64url(iv)}.${base64url(new Uint8Array(sealed))}`;
1918
+ }
1919
+ async function openSecret(key, sealed, aad) {
1920
+ const [version, iv, body, extra] = sealed.split(".");
1921
+ if (version !== "v1" || !iv || !body || extra !== void 0) throw new DeliveryError("The stored secret is not in a known format");
1922
+ try {
1923
+ const plain = await crypto.subtle.decrypt(
1924
+ { name: "AES-GCM", iv: padded(iv), additionalData: enc.encode(aad) },
1925
+ key,
1926
+ padded(body)
1927
+ );
1928
+ return new TextDecoder().decode(plain);
1929
+ } catch {
1930
+ throw new DeliveryError("The stored secret could not be decrypted");
1931
+ }
1932
+ }
1933
+ function padded(text) {
1934
+ return fromBase64(text + "=".repeat((4 - text.length % 4) % 4));
1935
+ }
1936
+
1937
+ // src/destinations/runner.ts
1938
+ var DEFAULT_MAX_ATTEMPTS = 8;
1939
+ var DEFAULT_MAX_DEFERRALS = 24;
1940
+ var DEFAULT_BATCH_SIZE = 25;
1941
+ function defaultBackoff(attempt) {
1942
+ return Math.min(6 * 3600, 60 * 2 ** Math.max(0, attempt - 1));
1943
+ }
1944
+ function deliveryOutcome(result, attempt, options = {}) {
1945
+ if (result.ok) return result.notSent ? { status: "skipped", reason: result.notSent.slice(0, 500) } : { status: "sent" };
1946
+ const http = result.status !== void 0 ? { httpStatus: result.status } : {};
1947
+ if (!result.retryable) return { status: "failed", error: result.error, ...http };
1948
+ const now = options.now ?? Date.now();
1949
+ if (result.retryAfterSeconds !== void 0 && (options.deferrals ?? 0) < (options.maxDeferrals ?? DEFAULT_MAX_DEFERRALS)) {
1950
+ const seconds2 = Math.max(1, Math.ceil(result.retryAfterSeconds));
1951
+ return { status: "retry", error: result.error, retryAt: new Date(now + seconds2 * 1e3), retryAfterSeconds: seconds2, counted: false, ...http };
1952
+ }
1953
+ const max = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
1954
+ if (attempt >= max) return { status: "failed", error: `${result.error} (gave up after ${attempt} attempts)`.slice(0, 500), ...http };
1955
+ const seconds = Math.max(1, Math.ceil((options.backoff ?? defaultBackoff)(attempt)));
1956
+ return { status: "retry", error: result.error, retryAt: new Date(now + seconds * 1e3), retryAfterSeconds: seconds, counted: true, ...http };
1957
+ }
1958
+ function createDeliveryRunner(options) {
1959
+ const log = (message) => {
1960
+ try {
1961
+ options.log?.(message);
1962
+ } catch {
1963
+ }
1964
+ };
1965
+ const now = () => options.now?.() ?? Date.now();
1966
+ async function send(group, signal) {
1967
+ const first = group[0];
1968
+ const destination = options.destinations[first.kind];
1969
+ if (!destination) {
1970
+ return group.map(() => ({ ok: false, retryable: false, error: `No destination for kind ${first.kind}` }));
1971
+ }
1972
+ const results = group.map((d) => {
1973
+ try {
1974
+ return passesCondition(d.submission, d.definition, d.config) ? null : "filtered";
1975
+ } catch (error) {
1976
+ return deliveryFailure(error);
1977
+ }
1978
+ });
1979
+ const due = group.filter((_, i) => results[i] === null);
1980
+ let state = first.state;
1981
+ const keep = (result) => {
1982
+ if (result.ok && result.state) state = result.state;
1983
+ };
1984
+ const guard = async (call) => {
1985
+ try {
1986
+ return await call();
1987
+ } catch (error) {
1988
+ return deliveryFailure(error);
1989
+ }
1990
+ };
1991
+ const base = { state, signal, destinationId: first.destinationId };
1992
+ let sent;
1993
+ if (due.length > 1 && destination.deliverBatch) {
1994
+ const items = due.map((d) => ({ submission: d.submission, definition: d.definition, deliveryId: d.id, update: d.update }));
1995
+ const result = await guard(
1996
+ () => destination.deliverBatch(items, first.config, { ...base, redelivery: due.some((d) => d.redelivery) })
1997
+ );
1998
+ keep(result);
1999
+ sent = due.map(() => result);
2000
+ } else {
2001
+ sent = [];
2002
+ for (const d of due) {
2003
+ const result = await guard(
2004
+ () => destination.deliver(d.submission, d.definition, d.config, {
2005
+ ...base,
2006
+ state,
2007
+ deliveryId: d.id,
2008
+ redelivery: d.redelivery,
2009
+ update: d.update
2010
+ })
2011
+ );
2012
+ keep(result);
2013
+ sent.push(result);
2014
+ }
2015
+ }
2016
+ if (state !== first.state && state && options.saveState) {
2017
+ try {
2018
+ await options.saveState(first.destinationId, state);
2019
+ } catch {
2020
+ log(`Saving destination ${first.destinationId}'s state failed`);
2021
+ }
2022
+ }
2023
+ let next = 0;
2024
+ return results.map((r) => r ?? sent[next++]);
2025
+ }
2026
+ return {
2027
+ async run(runOptions = {}) {
2028
+ const report = {
2029
+ claimed: 0,
2030
+ sent: 0,
2031
+ filtered: 0,
2032
+ skipped: 0,
2033
+ retrying: 0,
2034
+ deferred: 0,
2035
+ failed: 0,
2036
+ stale: 0,
2037
+ unrecorded: 0
2038
+ };
2039
+ const limit = runOptions.limit ?? options.batchSize ?? DEFAULT_BATCH_SIZE;
2040
+ const claimed = await options.claim({ limit, filter: runOptions.filter });
2041
+ report.claimed = claimed.length;
2042
+ const groups = /* @__PURE__ */ new Map();
2043
+ for (const delivery of claimed) {
2044
+ const list = groups.get(delivery.destinationId) ?? [];
2045
+ list.push(delivery);
2046
+ groups.set(delivery.destinationId, list);
2047
+ }
2048
+ await Promise.all(
2049
+ [...groups.values()].map(async (group) => {
2050
+ const results = await send(group, runOptions.signal);
2051
+ const at = now();
2052
+ await Promise.all(
2053
+ group.map(async (delivery, i) => {
2054
+ const result = results[i];
2055
+ const outcome = result === "filtered" ? { status: "filtered" } : deliveryOutcome(result, delivery.attempt, {
2056
+ now: at,
2057
+ maxAttempts: options.maxAttempts,
2058
+ backoff: options.backoff,
2059
+ deferrals: delivery.deferrals,
2060
+ maxDeferrals: options.maxDeferrals
2061
+ });
2062
+ if (outcome.status === "sent" && result !== "filtered" && result.ok && result.skipped?.includes(delivery.submission.id)) {
2063
+ outcome.alreadyThere = true;
2064
+ }
2065
+ if (outcome.status === "failed" || outcome.status === "retry") {
2066
+ log(`Delivery ${delivery.id} (${delivery.kind}) ${outcome.status === "failed" ? "failed" : "will be retried"}: ${outcome.error}`);
2067
+ } else if (outcome.status === "skipped") {
2068
+ log(`Delivery ${delivery.id} (${delivery.kind}) skipped: ${outcome.reason}`);
2069
+ }
2070
+ let recorded;
2071
+ try {
2072
+ recorded = await options.record(delivery, outcome);
2073
+ } catch {
2074
+ report.unrecorded++;
2075
+ log(`Recording delivery ${delivery.id} failed`);
2076
+ return;
2077
+ }
2078
+ if (recorded === false) report.stale++;
2079
+ else if (outcome.status === "sent") report.sent++;
2080
+ else if (outcome.status === "filtered") report.filtered++;
2081
+ else if (outcome.status === "skipped") report.skipped++;
2082
+ else if (outcome.status === "failed") report.failed++;
2083
+ else if (outcome.counted) report.retrying++;
2084
+ else report.deferred++;
2085
+ })
2086
+ );
2087
+ })
2088
+ );
2089
+ return report;
2090
+ }
2091
+ };
2092
+ }
2093
+
2094
+ export { DEDUPE_WINDOW, DEFAULT_BATCH_SIZE, DEFAULT_MAX_ATTEMPTS, DEFAULT_MAX_DEFERRALS, DEFAULT_SHEET_NAME, DRIVE_FILE_SCOPE, DeliveryError, GOOGLE_TOKEN_URL, HEADER_SCAN_ROWS, HookUrlError, MAX_CONDITION_DEPTH, MAX_HOOK_URL_LENGTH, MAX_RECIPIENTS, REQUEST_TIMEOUT_MS, RESEND_API, SENSITIVE_MASK, SHEETS_API, SHEETS_SCOPE, SLACK_HOSTS, SLACK_VALUE_LIMIT, answerCell, checkHookHost, checkWebhookUrl, clearGoogleOAuthTokenCache, clearGoogleTokenCache, columnLetter, conditionOf, createDeliveryRunner, defaultBackoff, deliveryFailure, deliveryOutcome, deriveSecretKey, emailBody, emailDestination, escapeFormula, escapeHtml, escapeSlack, googleAccessToken, googleOAuthAccessToken, headerSafe, hookHost, httpError, idempotencyKey, isCondition, isPrivateHost, isPublicAddress, isRetryableStatus, isSafeAddress, isSafeFrom, mergeHeader, newWebhookSecret, openSecret, parseHookUrl, passesCondition, refreshGoogleAccessToken, renderEmail, resendProvider, responseRow, retryAfterSeconds, rowFor, sealSecret, secretKeyBytes, sheetsDestination, signJwt, signWebhook, slackDestination, slackMessage, verifyWebhook, visibleInputs, webhookDestination, webhookPayload };
1485
2095
  //# sourceMappingURL=destinations.js.map
1486
2096
  //# sourceMappingURL=destinations.js.map