@drawbridge/drawbridge-utils 0.0.118 → 0.0.121
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.
- package/dist/connections/index.cjs +1182 -75
- package/dist/connections/index.d.cts +1832 -95
- package/dist/connections/index.d.ts +1832 -95
- package/dist/connections/index.js +1175 -73
- package/dist/phone.d.cts +1 -1
- package/dist/phone.d.ts +1 -1
- package/dist/providers.cjs +1154 -95
- package/dist/providers.d.cts +86 -77
- package/dist/providers.d.ts +86 -77
- package/dist/providers.js +1150 -91
- package/dist/sendgrid.cjs +4 -6
- package/dist/sendgrid.d.cts +19 -14
- package/dist/sendgrid.d.ts +19 -14
- package/dist/sendgrid.js +4 -6
- package/dist/twilio.cjs +2 -3
- package/dist/twilio.d.cts +11 -3
- package/dist/twilio.d.ts +11 -3
- package/dist/twilio.js +2 -3
- package/package.json +1 -1
package/dist/providers.js
CHANGED
|
@@ -176,6 +176,53 @@ var HOOKS = Object.freeze({
|
|
|
176
176
|
"promotions"
|
|
177
177
|
])
|
|
178
178
|
});
|
|
179
|
+
var HOOK_EFFECTS = Object.freeze(["enqueues", "events", "writes"]);
|
|
180
|
+
var WRITE_OPERATIONS = Object.freeze(["create", "update"]);
|
|
181
|
+
var HOOK_PROPS = Object.freeze([
|
|
182
|
+
"channel",
|
|
183
|
+
"clientId",
|
|
184
|
+
"clientSecret",
|
|
185
|
+
"connection",
|
|
186
|
+
"contact",
|
|
187
|
+
"context",
|
|
188
|
+
"cursor",
|
|
189
|
+
"declaration",
|
|
190
|
+
"doc",
|
|
191
|
+
"email",
|
|
192
|
+
"event",
|
|
193
|
+
"headers",
|
|
194
|
+
"id",
|
|
195
|
+
"lead",
|
|
196
|
+
"limit",
|
|
197
|
+
"manifest",
|
|
198
|
+
"payload",
|
|
199
|
+
"scope",
|
|
200
|
+
"search",
|
|
201
|
+
"secret",
|
|
202
|
+
"settings",
|
|
203
|
+
"sort",
|
|
204
|
+
"step",
|
|
205
|
+
"suppressed",
|
|
206
|
+
"token",
|
|
207
|
+
"tokens",
|
|
208
|
+
"workflow"
|
|
209
|
+
]);
|
|
210
|
+
var HOOK_OPTIONS = Object.freeze([
|
|
211
|
+
"adminToken",
|
|
212
|
+
"canSend",
|
|
213
|
+
"chunkSize",
|
|
214
|
+
"dispatch",
|
|
215
|
+
"fetcher",
|
|
216
|
+
"logger",
|
|
217
|
+
"mintId",
|
|
218
|
+
"read",
|
|
219
|
+
"reconcileScopes",
|
|
220
|
+
"request",
|
|
221
|
+
"resolveContact",
|
|
222
|
+
"resolveSettings",
|
|
223
|
+
"rotateToken",
|
|
224
|
+
"shopify"
|
|
225
|
+
]);
|
|
179
226
|
var STEPS = Object.freeze({
|
|
180
227
|
"commerce.code.issue": "Issue discount code",
|
|
181
228
|
"commerce.customer.insert": "Create customer",
|
|
@@ -357,13 +404,16 @@ var attentive_default = `<svg width="500" height="500" viewBox="0 0 500 500" fil
|
|
|
357
404
|
<path d="M166.04 261.805C180.228 259.107 195.528 261.893 207.581 269.971C218.512 277.079 226.908 288.136 230.604 300.657C234.835 314.103 233.614 329.124 227.485 341.788C220.097 356.875 205.782 368.543 189.317 372.089C173.957 375.652 157.089 372.386 144.304 363.103C132.971 355.295 124.912 342.989 121.891 329.581C118.943 316.636 120.725 302.656 127.002 290.938C134.699 275.951 149.503 264.933 166.046 261.811" fill="#1E1C1C"/>
|
|
358
405
|
</svg>`;
|
|
359
406
|
|
|
360
|
-
// lib/connections/attentive.js
|
|
407
|
+
// lib/connections/providers/attentive.js
|
|
361
408
|
var attentive_default2 = {
|
|
362
409
|
auth: {
|
|
363
410
|
oauth: {
|
|
364
|
-
// NAMES of the
|
|
365
|
-
//
|
|
366
|
-
//
|
|
411
|
+
// NAMES of the credentials holding OUR app's client — keys into the map
|
|
412
|
+
// the provider collection answers, entered on the admin screen at
|
|
413
|
+
// registration, never before. (The names are the env vars they once
|
|
414
|
+
// were; the vocabulary stayed when the storage moved.) No `headers` on
|
|
415
|
+
// the client: Attentive takes credentials as form fields, which is the
|
|
416
|
+
// runner's default.
|
|
367
417
|
client: {
|
|
368
418
|
id: "ATTENTIVE_OAUTH_CLIENT_ID",
|
|
369
419
|
secret: "ATTENTIVE_OAUTH_CLIENT_SECRET"
|
|
@@ -468,7 +518,7 @@ var attentive_default2 = {
|
|
|
468
518
|
// show a picker quietly missing most of a real account. The response's
|
|
469
519
|
// only identifier is `externalId`, so an entry without one cannot be
|
|
470
520
|
// stored and is dropped.
|
|
471
|
-
audiences: async ({ cursor,
|
|
521
|
+
audiences: async ({ cursor, limit = 100, search, token }, { fetcher = fetch } = {}) => {
|
|
472
522
|
const query = new URLSearchParams({
|
|
473
523
|
limit: String(Math.min(limit, 1e3)),
|
|
474
524
|
...cursor && { cursor },
|
|
@@ -584,10 +634,11 @@ var request = async ({
|
|
|
584
634
|
// lib/hubspot.js
|
|
585
635
|
var HUBSPOT_BASE = "https://api.hubapi.com";
|
|
586
636
|
var hubspotRequest = ({ body, fetcher, method, path, query, token }) => {
|
|
637
|
+
if (!token) throw new Error("HubSpot access token missing \u2014 pass token (the drawbridge provider's hubspotToken)");
|
|
587
638
|
return (fetcher || request)({
|
|
588
639
|
body,
|
|
589
640
|
headers: {
|
|
590
|
-
"Authorization": "Bearer " +
|
|
641
|
+
"Authorization": "Bearer " + token
|
|
591
642
|
},
|
|
592
643
|
method,
|
|
593
644
|
query,
|
|
@@ -689,16 +740,15 @@ var contacts = {
|
|
|
689
740
|
// FORGET A CONTACT, by id or by email. Account deletion — the caller had
|
|
690
741
|
// to search then remove, which is one round trip it should not have to
|
|
691
742
|
// know about.
|
|
692
|
-
remove: async ({ email,
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
const contact = id || await lookup({ email, fetcher, token: key });
|
|
743
|
+
remove: async ({ email, id, token }, { fetcher } = {}) => {
|
|
744
|
+
if (!token) return;
|
|
745
|
+
const contact = id || await lookup({ email, fetcher, token });
|
|
696
746
|
if (!contact) return;
|
|
697
747
|
return hubspotRequest({
|
|
698
748
|
fetcher,
|
|
699
749
|
method: "DELETE",
|
|
700
750
|
path: "/crm/v3/objects/contacts/" + contact,
|
|
701
|
-
token
|
|
751
|
+
token
|
|
702
752
|
});
|
|
703
753
|
},
|
|
704
754
|
// Connect an account to its contact by email, creating it if absent, and
|
|
@@ -707,24 +757,23 @@ var contacts = {
|
|
|
707
757
|
// no delete-old-then-create-new.
|
|
708
758
|
//
|
|
709
759
|
// Prefer the cached hubspotId; fall back to a search; create last.
|
|
710
|
-
sync: async ({ doc,
|
|
760
|
+
sync: async ({ doc, token }, { fetcher } = {}) => {
|
|
711
761
|
var _a, _b;
|
|
712
|
-
|
|
713
|
-
if (!key) return;
|
|
762
|
+
if (!token) return;
|
|
714
763
|
if (doc == null ? void 0 : doc.hubspotId) {
|
|
715
764
|
try {
|
|
716
|
-
return (_a = await send({ doc, fetcher, method: "PATCH", path: "/crm/v3/objects/contacts/" + doc.hubspotId, token
|
|
765
|
+
return (_a = await send({ doc, fetcher, method: "PATCH", path: "/crm/v3/objects/contacts/" + doc.hubspotId, token })) == null ? void 0 : _a.id;
|
|
717
766
|
} catch (error) {
|
|
718
767
|
if ((error == null ? void 0 : error.status) !== 404) throw error;
|
|
719
768
|
}
|
|
720
769
|
}
|
|
721
|
-
const existing = await lookup({ email: doc == null ? void 0 : doc.email, fetcher, token
|
|
770
|
+
const existing = await lookup({ email: doc == null ? void 0 : doc.email, fetcher, token });
|
|
722
771
|
return (_b = await send({
|
|
723
772
|
doc,
|
|
724
773
|
fetcher,
|
|
725
774
|
method: existing ? "PATCH" : "POST",
|
|
726
775
|
path: existing ? "/crm/v3/objects/contacts/" + existing : "/crm/v3/objects/contacts",
|
|
727
|
-
token
|
|
776
|
+
token
|
|
728
777
|
})) == null ? void 0 : _b.id;
|
|
729
778
|
}
|
|
730
779
|
};
|
|
@@ -1180,6 +1229,36 @@ var plans = {
|
|
|
1180
1229
|
conversion: 0.5
|
|
1181
1230
|
}
|
|
1182
1231
|
};
|
|
1232
|
+
var resolvePlan = (subscription) => {
|
|
1233
|
+
var _a, _b;
|
|
1234
|
+
const custom = subscription == null ? void 0 : subscription.custom;
|
|
1235
|
+
if (!custom) return plans[subscription == null ? void 0 : subscription.plan] ?? free;
|
|
1236
|
+
return {
|
|
1237
|
+
// Reusing all.features / all.limits is what keeps a custom plan the same
|
|
1238
|
+
// SHAPE as a catalog one: the base feature grants every plan carries, the
|
|
1239
|
+
// campaign limits that are always infinite, and members defaulting to
|
|
1240
|
+
// infinite when a deal does not name it.
|
|
1241
|
+
conversion: custom.conversion ?? free.conversion,
|
|
1242
|
+
custom: true,
|
|
1243
|
+
// A custom plan is a negotiated PAID deal, so it carries the paid-tier
|
|
1244
|
+
// baseline whether or not the deal thought to name it. Today that is the
|
|
1245
|
+
// sending domain: every catalog paid tier grants it, and a custom plan
|
|
1246
|
+
// silently lacking it would be a support ticket, not a pricing decision.
|
|
1247
|
+
features: all.features([organization.networking.key, ...((_a = custom.features) == null ? void 0 : _a.granted) || []]),
|
|
1248
|
+
limits: all.limits(((_b = custom.limits) == null ? void 0 : _b.organization) || {}),
|
|
1249
|
+
// A custom plan stores its overage BARE on `custom.overages` — a different
|
|
1250
|
+
// shape from the catalog's nested one. Number() so a deal stored as a string
|
|
1251
|
+
// still resolves to cents-per-action; an unnamed overage stays undefined
|
|
1252
|
+
// (it bills nothing) rather than becoming NaN.
|
|
1253
|
+
actionCents: custom.overages == null ? void 0 : Number(custom.overages),
|
|
1254
|
+
overages: { actions: custom.overages },
|
|
1255
|
+
title: custom.title || "Custom"
|
|
1256
|
+
};
|
|
1257
|
+
};
|
|
1258
|
+
var conversionRate = (subscription) => {
|
|
1259
|
+
var _a;
|
|
1260
|
+
return ((_a = resolvePlan(subscription)) == null ? void 0 : _a.conversion) ?? free.conversion;
|
|
1261
|
+
};
|
|
1183
1262
|
|
|
1184
1263
|
// lib/transactions.js
|
|
1185
1264
|
import { currentTraceId } from "@drawbridge/drawbridge-telemetry";
|
|
@@ -1334,7 +1413,36 @@ var channels = {
|
|
|
1334
1413
|
}
|
|
1335
1414
|
};
|
|
1336
1415
|
|
|
1337
|
-
// lib/connections/drawbridge.js
|
|
1416
|
+
// lib/connections/providers/drawbridge.js
|
|
1417
|
+
var interpolate = (template, data2) => {
|
|
1418
|
+
if (!template) return template;
|
|
1419
|
+
return template.replace(/\{\{(\w+)\}\}/g, (_, key) => (data2 == null ? void 0 : data2[key]) != null ? String(data2[key]) : "{{" + key + "}}");
|
|
1420
|
+
};
|
|
1421
|
+
var teamRecipients = async ({ memberIds = [], organization: organization2, read }) => {
|
|
1422
|
+
const org = await read.get({ collection: "organization", query: { id: organization2 } });
|
|
1423
|
+
const owner = (org == null ? void 0 : org.owner) ? await read.get({ collection: "user", query: { id: org.owner } }) : null;
|
|
1424
|
+
const members = memberIds.length ? await read.aggregate({
|
|
1425
|
+
collection: "member",
|
|
1426
|
+
pipeline: [
|
|
1427
|
+
{
|
|
1428
|
+
$match: {
|
|
1429
|
+
id: { $in: memberIds },
|
|
1430
|
+
organization: organization2,
|
|
1431
|
+
status: "accepted"
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
]
|
|
1435
|
+
}) : [];
|
|
1436
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1437
|
+
return [owner, ...members].filter((member) => {
|
|
1438
|
+
if (!(member == null ? void 0 : member.id) || !(member == null ? void 0 : member.email)) return false;
|
|
1439
|
+
const address = member.email.toLowerCase();
|
|
1440
|
+
if (seen.has(address)) return false;
|
|
1441
|
+
seen.add(address);
|
|
1442
|
+
return true;
|
|
1443
|
+
});
|
|
1444
|
+
};
|
|
1445
|
+
var queueNotification = (data2) => ({ collection: "notification", data: data2, operation: "create" });
|
|
1338
1446
|
var drawbridge_default2 = {
|
|
1339
1447
|
auth: {
|
|
1340
1448
|
type: "none"
|
|
@@ -1352,10 +1460,15 @@ var drawbridge_default2 = {
|
|
|
1352
1460
|
exclusive: false,
|
|
1353
1461
|
fields: [],
|
|
1354
1462
|
group: "developer",
|
|
1355
|
-
//
|
|
1356
|
-
//
|
|
1357
|
-
//
|
|
1358
|
-
//
|
|
1463
|
+
// THE BODIES LIVE HERE, beside the declarations that name them. They used to
|
|
1464
|
+
// live in drawbridge-sync because they touch the database, the queues and the
|
|
1465
|
+
// sockets — and a published package cannot carry a controller.
|
|
1466
|
+
//
|
|
1467
|
+
// It does not have to. A hook is a function, so everything it needs is PASSED
|
|
1468
|
+
// IN: `read` for the reads, `canSend` for the opt-out floor, `resolveContact`
|
|
1469
|
+
// for the one write whose RESULT the hook has to count. Everything else a hook
|
|
1470
|
+
// wants done it DESCRIBES — `writes`, `enqueues`, `events` — and the shell
|
|
1471
|
+
// performs it. See lib/connections/contract.js for that shape.
|
|
1359
1472
|
hooks: {
|
|
1360
1473
|
auth: {
|
|
1361
1474
|
// Nothing to connect, revoke, probe or re-scope.
|
|
@@ -1376,13 +1489,157 @@ var drawbridge_default2 = {
|
|
|
1376
1489
|
// accounts DRAWBRIDGE holds rather than ones a merchant connects.
|
|
1377
1490
|
contacts,
|
|
1378
1491
|
email: {
|
|
1379
|
-
|
|
1380
|
-
//
|
|
1381
|
-
//
|
|
1382
|
-
//
|
|
1383
|
-
|
|
1384
|
-
//
|
|
1385
|
-
|
|
1492
|
+
// A PERIODIC SUMMARY to the team, on a schedule trigger rather than per
|
|
1493
|
+
// lead.
|
|
1494
|
+
//
|
|
1495
|
+
// The count is the point: `email.notify` tells the owner one lead arrived
|
|
1496
|
+
// and dampens a spike to one message per bucket, which is deliberately not
|
|
1497
|
+
// a count. This is where "you got 43 entries this week" comes from.
|
|
1498
|
+
digest: async ({ context, step, workflow }, { read } = {}) => {
|
|
1499
|
+
var _a, _b, _c, _d;
|
|
1500
|
+
const days = { day: 1, month: 30, week: 7 }[(_a = workflow == null ? void 0 : workflow.trigger) == null ? void 0 : _a.event] || 7;
|
|
1501
|
+
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1e3);
|
|
1502
|
+
const campaign = ((_c = (_b = workflow == null ? void 0 : workflow.trigger) == null ? void 0 : _b.filters) == null ? void 0 : _c.campaign) || null;
|
|
1503
|
+
const [counted] = await read.aggregate({
|
|
1504
|
+
collection: "lead",
|
|
1505
|
+
pipeline: [
|
|
1506
|
+
{
|
|
1507
|
+
$match: {
|
|
1508
|
+
createdAt: { $gte: since },
|
|
1509
|
+
organization: workflow.organization,
|
|
1510
|
+
...campaign && { campaigns: { $in: [campaign] } }
|
|
1511
|
+
}
|
|
1512
|
+
},
|
|
1513
|
+
{ $count: "count" }
|
|
1514
|
+
]
|
|
1515
|
+
});
|
|
1516
|
+
const count = Number((counted == null ? void 0 : counted.count) || 0);
|
|
1517
|
+
const request2 = { campaign, count, days };
|
|
1518
|
+
if (!count) return { message: "No new leads in the period \u2014 digest skipped.", request: request2, response: { skipped: true }, skipped: true };
|
|
1519
|
+
const recipients = await teamRecipients({
|
|
1520
|
+
memberIds: ((_d = step.settings) == null ? void 0 : _d.members) || [],
|
|
1521
|
+
organization: workflow.organization,
|
|
1522
|
+
read
|
|
1523
|
+
});
|
|
1524
|
+
const values = { ...context, count };
|
|
1525
|
+
return {
|
|
1526
|
+
message: "Digest of " + count + " new lead(s) queued for " + recipients.length + " recipient(s).",
|
|
1527
|
+
request: request2,
|
|
1528
|
+
response: { count, notified: recipients.length },
|
|
1529
|
+
writes: recipients.map((member) => {
|
|
1530
|
+
var _a2, _b2;
|
|
1531
|
+
return queueNotification({
|
|
1532
|
+
audience: "member",
|
|
1533
|
+
message: interpolate((_a2 = step.settings) == null ? void 0 : _a2.message, values),
|
|
1534
|
+
organization: workflow.organization,
|
|
1535
|
+
send: { type: "email", email: member.email },
|
|
1536
|
+
title: interpolate((_b2 = step.settings) == null ? void 0 : _b2.subject, values),
|
|
1537
|
+
workflow: workflow.id
|
|
1538
|
+
});
|
|
1539
|
+
})
|
|
1540
|
+
};
|
|
1541
|
+
},
|
|
1542
|
+
// To the organization's OWN PEOPLE. Never suppressed, never
|
|
1543
|
+
// subscription-gated, no unsubscribe footer — telling an org's staff about
|
|
1544
|
+
// their own leads is not commercial mail to a stranger.
|
|
1545
|
+
//
|
|
1546
|
+
// FREE, permanently. The lead that triggered this run already consumed the
|
|
1547
|
+
// billable action, and `members` is a list — billing here would turn one
|
|
1548
|
+
// lead into five more charges and the org would be paying to read its own
|
|
1549
|
+
// mail. The declaration prices it at zero; the shell bills nothing for
|
|
1550
|
+
// zero.
|
|
1551
|
+
notify: async ({ context, step, workflow }, { read } = {}) => {
|
|
1552
|
+
var _a;
|
|
1553
|
+
const memberIds = ((_a = step.settings) == null ? void 0 : _a.members) || [];
|
|
1554
|
+
const request2 = { members: memberIds.length };
|
|
1555
|
+
const recipients = await teamRecipients({ memberIds, organization: workflow.organization, read });
|
|
1556
|
+
if (!recipients.length) {
|
|
1557
|
+
return {
|
|
1558
|
+
message: "No owner or accepted member with an email address \u2014 team notification skipped.",
|
|
1559
|
+
request: request2,
|
|
1560
|
+
response: { skipped: true },
|
|
1561
|
+
skipped: true
|
|
1562
|
+
};
|
|
1563
|
+
}
|
|
1564
|
+
const bucket = Math.floor(Date.now() / (15 * 60 * 1e3));
|
|
1565
|
+
return {
|
|
1566
|
+
message: "Team notification queued for " + recipients.length + " recipient(s).",
|
|
1567
|
+
request: request2,
|
|
1568
|
+
response: { notified: recipients.length },
|
|
1569
|
+
writes: recipients.map((member) => {
|
|
1570
|
+
var _a2, _b;
|
|
1571
|
+
return {
|
|
1572
|
+
...queueNotification({
|
|
1573
|
+
audience: "member",
|
|
1574
|
+
// Per workflow, recipient AND bucket, so one recipient's damper
|
|
1575
|
+
// can never swallow another's mail and a later bucket is never
|
|
1576
|
+
// mistaken for a duplicate of an earlier one.
|
|
1577
|
+
key: "team.notify." + workflow.id + "." + member.id + "." + bucket,
|
|
1578
|
+
message: interpolate((_a2 = step.settings) == null ? void 0 : _a2.message, context),
|
|
1579
|
+
organization: workflow.organization,
|
|
1580
|
+
send: { type: "email", email: member.email },
|
|
1581
|
+
title: interpolate((_b = step.settings) == null ? void 0 : _b.subject, context),
|
|
1582
|
+
workflow: workflow.id
|
|
1583
|
+
}),
|
|
1584
|
+
// E11000 IS THE DAMPER WORKING: this recipient has already been
|
|
1585
|
+
// told within the bucket. Declared per write rather than assumed by
|
|
1586
|
+
// the shell, because on every other write here a duplicate key is a
|
|
1587
|
+
// real failure.
|
|
1588
|
+
ignoreDuplicate: true
|
|
1589
|
+
};
|
|
1590
|
+
})
|
|
1591
|
+
};
|
|
1592
|
+
},
|
|
1593
|
+
// Drawbridge sends lead-facing email itself — no merchant provider gates
|
|
1594
|
+
// it.
|
|
1595
|
+
//
|
|
1596
|
+
// This QUEUES rather than sends: queue/notification.js owns delivery, the
|
|
1597
|
+
// unsubscribe token and the CAN-SPAM footer. The step's job is to say who
|
|
1598
|
+
// and what, correctly, and to refuse early when it must not send at all.
|
|
1599
|
+
send: async ({ context, step, workflow }, { canSend, read } = {}) => {
|
|
1600
|
+
var _a, _b;
|
|
1601
|
+
const to = context == null ? void 0 : context.email;
|
|
1602
|
+
if (!to) throw new Error("No email address on context (context.email is required)");
|
|
1603
|
+
const request2 = { to };
|
|
1604
|
+
const { ok: sendable } = await canSend({ channel: "email", to });
|
|
1605
|
+
if (!sendable) return { message: "Recipient has opted out \u2014 skipped.", request: request2, response: { skipped: true }, skipped: true };
|
|
1606
|
+
const organization2 = await read.get({ collection: "organization", query: { id: workflow.organization } });
|
|
1607
|
+
const subscription = (organization2 == null ? void 0 : organization2.subscription) ? await read.get({ collection: "subscription", query: { id: organization2.subscription } }) : null;
|
|
1608
|
+
if ((subscription == null ? void 0 : subscription.status) !== "active") {
|
|
1609
|
+
return {
|
|
1610
|
+
message: "Organization has no active subscription \u2014 workflow-step email skipped.",
|
|
1611
|
+
request: request2,
|
|
1612
|
+
response: { skipped: true },
|
|
1613
|
+
skipped: true
|
|
1614
|
+
};
|
|
1615
|
+
}
|
|
1616
|
+
return {
|
|
1617
|
+
message: "Email queued for delivery to " + to + ".",
|
|
1618
|
+
request: request2,
|
|
1619
|
+
response: { queued: true },
|
|
1620
|
+
// NO `connection` FIELD, deliberately: the platform sends this.
|
|
1621
|
+
// `audience : 'lead'` states what the queue would otherwise infer from
|
|
1622
|
+
// shape.
|
|
1623
|
+
//
|
|
1624
|
+
// `campaign` is not decoration. queue/notification.js mints the
|
|
1625
|
+
// unsubscribe token with it, so it decides whether opting out is
|
|
1626
|
+
// scoped to this campaign or the whole organization, and it names the
|
|
1627
|
+
// campaign in the footer. Sending without it silently broadens every
|
|
1628
|
+
// opt-out to the entire organization.
|
|
1629
|
+
writes: [
|
|
1630
|
+
queueNotification({
|
|
1631
|
+
audience: "lead",
|
|
1632
|
+
campaign: (context == null ? void 0 : context.campaign) || null,
|
|
1633
|
+
lead: (context == null ? void 0 : context.lead) || null,
|
|
1634
|
+
message: interpolate((_a = step.settings) == null ? void 0 : _a.message, context),
|
|
1635
|
+
organization: workflow.organization,
|
|
1636
|
+
send: { type: "email", email: to },
|
|
1637
|
+
title: interpolate((_b = step.settings) == null ? void 0 : _b.subject, context),
|
|
1638
|
+
workflow: workflow.id
|
|
1639
|
+
})
|
|
1640
|
+
]
|
|
1641
|
+
};
|
|
1642
|
+
}
|
|
1386
1643
|
},
|
|
1387
1644
|
inbound: false,
|
|
1388
1645
|
lifecycle: false,
|
|
@@ -1392,8 +1649,174 @@ var drawbridge_default2 = {
|
|
|
1392
1649
|
products: false,
|
|
1393
1650
|
promotions: false
|
|
1394
1651
|
},
|
|
1395
|
-
segment: {
|
|
1396
|
-
|
|
1652
|
+
segment: {
|
|
1653
|
+
// RECALCULATE SEGMENT MEMBERSHIP. The one FAN-OUT hook: it evaluates every
|
|
1654
|
+
// contact in an organization against every segment, which is too much for
|
|
1655
|
+
// one job, so it returns chunks and the shell defers completion.
|
|
1656
|
+
//
|
|
1657
|
+
// Returning `chunks` is the only thing that makes it different. The
|
|
1658
|
+
// declaration, the guards, the step document and the price are the shell's,
|
|
1659
|
+
// exactly as they are for a step that finishes in one go.
|
|
1660
|
+
sync: async ({ context, step }, { chunkSize, logger: logger2, read, resolveContact } = {}) => {
|
|
1661
|
+
var _a, _b, _c;
|
|
1662
|
+
if (!chunkSize) throw new Error("segment.sync needs chunkSize from the shell");
|
|
1663
|
+
const organization2 = context == null ? void 0 : context.organization;
|
|
1664
|
+
const configured = (_a = step == null ? void 0 : step.settings) == null ? void 0 : _a.segment;
|
|
1665
|
+
const request2 = { organization: organization2 || null, segmentId: configured || null };
|
|
1666
|
+
const release = (ids, status = "active") => {
|
|
1667
|
+
const released = (ids || []).filter(Boolean);
|
|
1668
|
+
return {
|
|
1669
|
+
events: organization2 ? released.map((id) => ({
|
|
1670
|
+
event: "organization.segments",
|
|
1671
|
+
payload: { id, status },
|
|
1672
|
+
room: "organization." + organization2
|
|
1673
|
+
})) : [],
|
|
1674
|
+
writes: released.map((id) => ({
|
|
1675
|
+
collection: "segment",
|
|
1676
|
+
data: { $set: { status } },
|
|
1677
|
+
operation: "update",
|
|
1678
|
+
query: { id }
|
|
1679
|
+
}))
|
|
1680
|
+
};
|
|
1681
|
+
};
|
|
1682
|
+
if (!organization2) {
|
|
1683
|
+
return {
|
|
1684
|
+
...release([configured]),
|
|
1685
|
+
message: "Trigger data missing organization id \u2014 cannot sync segments.",
|
|
1686
|
+
request: request2,
|
|
1687
|
+
response: { skipped: true },
|
|
1688
|
+
skipped: true
|
|
1689
|
+
};
|
|
1690
|
+
}
|
|
1691
|
+
const segments = await read.aggregate({
|
|
1692
|
+
collection: "segment",
|
|
1693
|
+
pipeline: [{ $match: configured ? { id: configured, organization: organization2 } : { organization: organization2 } }]
|
|
1694
|
+
});
|
|
1695
|
+
if (!segments.length) {
|
|
1696
|
+
return {
|
|
1697
|
+
...release([configured]),
|
|
1698
|
+
message: "No segments matched the request \u2014 nothing to sync.",
|
|
1699
|
+
request: request2,
|
|
1700
|
+
response: { skipped: true },
|
|
1701
|
+
skipped: true
|
|
1702
|
+
};
|
|
1703
|
+
}
|
|
1704
|
+
const segmentIds = segments.map((entry) => entry.id);
|
|
1705
|
+
try {
|
|
1706
|
+
let backfilled = 0;
|
|
1707
|
+
if (segments.some((entry) => entry.system)) {
|
|
1708
|
+
const contacted = await read.aggregate({
|
|
1709
|
+
collection: "contact",
|
|
1710
|
+
pipeline: [
|
|
1711
|
+
{ $match: { organization: organization2 } },
|
|
1712
|
+
{ $project: { _id: 0, leads: 1 } },
|
|
1713
|
+
{ $unwind: "$leads" },
|
|
1714
|
+
{ $group: { _id: null, ids: { $addToSet: "$leads" } } }
|
|
1715
|
+
]
|
|
1716
|
+
});
|
|
1717
|
+
const uncontacted = await read.aggregate({
|
|
1718
|
+
collection: "lead",
|
|
1719
|
+
pipeline: [
|
|
1720
|
+
{ $match: { id: { $nin: ((_b = contacted[0]) == null ? void 0 : _b.ids) || [] }, organization: organization2 } },
|
|
1721
|
+
{ $project: { _id: 0, id: 1 } }
|
|
1722
|
+
]
|
|
1723
|
+
});
|
|
1724
|
+
for (const lead of uncontacted) {
|
|
1725
|
+
try {
|
|
1726
|
+
await resolveContact({ leadId: lead.id });
|
|
1727
|
+
backfilled += 1;
|
|
1728
|
+
} catch (error) {
|
|
1729
|
+
if (error.code !== 11e3) throw error;
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
(_c = logger2 == null ? void 0 : logger2.info) == null ? void 0 : _c.call(logger2, "segment.sync.backfill", { backfilled, organization: organization2, uncontacted: uncontacted.length });
|
|
1733
|
+
}
|
|
1734
|
+
const contacts2 = await read.aggregate({
|
|
1735
|
+
collection: "contact",
|
|
1736
|
+
pipeline: [
|
|
1737
|
+
{ $match: { organization: organization2 } },
|
|
1738
|
+
{ $project: { _id: 0, id: 1 } },
|
|
1739
|
+
{ $sort: { id: 1 } }
|
|
1740
|
+
]
|
|
1741
|
+
});
|
|
1742
|
+
if (!contacts2.length) {
|
|
1743
|
+
return {
|
|
1744
|
+
...release(segmentIds),
|
|
1745
|
+
message: "Organization has no contacts to evaluate against segments.",
|
|
1746
|
+
request: request2,
|
|
1747
|
+
response: { skipped: true },
|
|
1748
|
+
skipped: true
|
|
1749
|
+
};
|
|
1750
|
+
}
|
|
1751
|
+
const contactIds = contacts2.map((contact) => contact.id);
|
|
1752
|
+
const org = await read.get({ collection: "organization", query: { id: organization2 } });
|
|
1753
|
+
const chunks = [];
|
|
1754
|
+
for (let index = 0; index < contactIds.length; index += chunkSize) {
|
|
1755
|
+
chunks.push({
|
|
1756
|
+
contactIds: contactIds.slice(index, index + chunkSize),
|
|
1757
|
+
organization: organization2,
|
|
1758
|
+
segments: segmentIds,
|
|
1759
|
+
// A BACKFILL IS NOT BILLABLE. It creates the contacts this run
|
|
1760
|
+
// then evaluates, so charging for it would bill an organization
|
|
1761
|
+
// for work its own history made necessary.
|
|
1762
|
+
usage: (context == null ? void 0 : context.billable) === true && backfilled === 0 ? (org == null ? void 0 : org.usage) || null : null
|
|
1763
|
+
});
|
|
1764
|
+
}
|
|
1765
|
+
return {
|
|
1766
|
+
chunks,
|
|
1767
|
+
...configured && { extra: { segment: configured } },
|
|
1768
|
+
message: "Queued " + contactIds.length + " contacts across " + chunks.length + " chunks for segment evaluation.",
|
|
1769
|
+
queue: "segment",
|
|
1770
|
+
request: { ...request2, segments: segmentIds },
|
|
1771
|
+
response: { chunks: chunks.length, contacts: contactIds.length, segments: segments.length }
|
|
1772
|
+
};
|
|
1773
|
+
} catch (error) {
|
|
1774
|
+
throw Object.assign(error, release(segmentIds, "error"));
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
},
|
|
1778
|
+
sms: {
|
|
1779
|
+
// SMS TO A LEAD, through the merchant's own Twilio connection.
|
|
1780
|
+
//
|
|
1781
|
+
// WITHDRAWN from the builder — twilio went, and a connection-gated step
|
|
1782
|
+
// with no connection to gate on could only ever render permanently
|
|
1783
|
+
// disabled. Stored workflows still carry it, so it still runs.
|
|
1784
|
+
//
|
|
1785
|
+
// It looks its own connection up rather than relying on the shell, because
|
|
1786
|
+
// the step is declared by the PRIVATE drawbridge connection (which has
|
|
1787
|
+
// none) while the credential belongs to twilio (which has no manifest).
|
|
1788
|
+
// Platform SMS will remove that split the way it did for email.
|
|
1789
|
+
send: async ({ context, step, workflow }, { canSend, read } = {}) => {
|
|
1790
|
+
var _a, _b, _c;
|
|
1791
|
+
const to = (_a = context == null ? void 0 : context.phone) == null ? void 0 : _a.number;
|
|
1792
|
+
if (!to) throw new Error("No phone number on context (context.phone.number is required)");
|
|
1793
|
+
const request2 = { to };
|
|
1794
|
+
const connection2 = await read.get({
|
|
1795
|
+
collection: "connection",
|
|
1796
|
+
query: { organization: workflow.organization, slug: "twilio", status: "active" }
|
|
1797
|
+
});
|
|
1798
|
+
if (!connection2) return { message: "No active Twilio SMS connection \u2014 workflow-step SMS skipped.", request: request2, response: { skipped: true }, skipped: true };
|
|
1799
|
+
const { ok: sendable } = await canSend({ channel: "sms", to: context.phone });
|
|
1800
|
+
if (!sendable) return { message: "Recipient has opted out \u2014 skipped.", request: request2, response: { skipped: true }, skipped: true };
|
|
1801
|
+
return {
|
|
1802
|
+
message: "SMS queued for delivery to " + to + " via twilio.",
|
|
1803
|
+
request: request2,
|
|
1804
|
+
response: { provider: "twilio", queued: true },
|
|
1805
|
+
// QUEUES rather than sends: queue/notification.js owns delivery, the
|
|
1806
|
+
// carrier opt-out line and the segment count this is billed on.
|
|
1807
|
+
writes: [
|
|
1808
|
+
queueNotification({
|
|
1809
|
+
connection: connection2.id,
|
|
1810
|
+
message: interpolate((_b = step.settings) == null ? void 0 : _b.message, context),
|
|
1811
|
+
organization: workflow.organization,
|
|
1812
|
+
send: { phone: { number: to }, type: "phone" },
|
|
1813
|
+
title: interpolate((_c = step.settings) == null ? void 0 : _c.subject, context),
|
|
1814
|
+
workflow: workflow.id
|
|
1815
|
+
})
|
|
1816
|
+
]
|
|
1817
|
+
};
|
|
1818
|
+
}
|
|
1819
|
+
},
|
|
1397
1820
|
webhook: false
|
|
1398
1821
|
},
|
|
1399
1822
|
icon: drawbridge_default,
|
|
@@ -1435,11 +1858,11 @@ var drawbridge_default2 = {
|
|
|
1435
1858
|
key: "Email \u2014 Digest",
|
|
1436
1859
|
queue: "notification",
|
|
1437
1860
|
settings: {
|
|
1438
|
-
// The organization OWNER is always a recipient, resolved
|
|
1439
|
-
// so this is additional recipients rather than the list. It
|
|
1440
|
-
// be required: the members endpoint is owner-gated and the
|
|
1441
|
-
// not a member document, so a solo merchant has nothing to
|
|
1442
|
-
// could never save the step.
|
|
1861
|
+
// The organization OWNER is always a recipient, resolved by the
|
|
1862
|
+
// hook, so this is additional recipients rather than the list. It
|
|
1863
|
+
// cannot be required: the members endpoint is owner-gated and the
|
|
1864
|
+
// owner is not a member document, so a solo merchant has nothing to
|
|
1865
|
+
// pick and could never save the step.
|
|
1443
1866
|
members: { of: "string", type: "array" },
|
|
1444
1867
|
message: { required: true, type: "string" },
|
|
1445
1868
|
subject: { required: true, type: "string" }
|
|
@@ -1539,7 +1962,7 @@ var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
|
|
|
1539
1962
|
<path d="M365.047 327.038H134.954V172.964H365.047L316.856 250.001L365.047 327.038Z" fill="#232121"/>
|
|
1540
1963
|
</svg>`;
|
|
1541
1964
|
|
|
1542
|
-
// lib/connections/klaviyo.js
|
|
1965
|
+
// lib/connections/providers/klaviyo.js
|
|
1543
1966
|
var api = async (path, { fetcher = fetch, method = "GET", payload, token }) => {
|
|
1544
1967
|
const response = await fetcher("https://a.klaviyo.com/api" + path, {
|
|
1545
1968
|
...payload && { body: JSON.stringify(payload) },
|
|
@@ -1576,7 +1999,8 @@ var klaviyo_default2 = {
|
|
|
1576
1999
|
// differently, and it says so in hooks.auth.token rather than as a flag here.
|
|
1577
2000
|
auth: {
|
|
1578
2001
|
oauth: {
|
|
1579
|
-
// NAMES the
|
|
2002
|
+
// NAMES the credentials holding OUR application's client — keys into
|
|
2003
|
+
// the stored provider credentials, not env vars. One identity,
|
|
1580
2004
|
// every merchant — the token is the merchant's and arrives from their
|
|
1581
2005
|
// own consent, which is what stops one organization reading another's
|
|
1582
2006
|
// data.
|
|
@@ -1716,7 +2140,7 @@ var klaviyo_default2 = {
|
|
|
1716
2140
|
// renders an empty "Klaviyo account" field, because the merchant is
|
|
1717
2141
|
// never asked which account they connected — the consent already
|
|
1718
2142
|
// decided it, and asking again would be a question we can answer.
|
|
1719
|
-
connect: async ({
|
|
2143
|
+
connect: async ({ tokens }, { fetcher } = {}) => {
|
|
1720
2144
|
var _a, _b, _c;
|
|
1721
2145
|
const body = await api("/accounts", { fetcher, token: tokens.accessToken });
|
|
1722
2146
|
const account = (_a = body == null ? void 0 : body.data) == null ? void 0 : _a[0];
|
|
@@ -1731,7 +2155,7 @@ var klaviyo_default2 = {
|
|
|
1731
2155
|
//
|
|
1732
2156
|
// Basic auth with our client, exactly like the token exchange — the
|
|
1733
2157
|
// token being revoked is the subject, not the credential.
|
|
1734
|
-
disconnect: async ({ clientId, clientSecret, fetcher = fetch
|
|
2158
|
+
disconnect: async ({ clientId, clientSecret, manifest, settings }, { fetcher = fetch } = {}) => {
|
|
1735
2159
|
const token = (settings == null ? void 0 : settings.refreshToken) || (settings == null ? void 0 : settings.accessToken);
|
|
1736
2160
|
if (!token) return { revoked: false };
|
|
1737
2161
|
const response = await fetcher(manifest.auth.oauth.urls.revoke, {
|
|
@@ -1754,7 +2178,7 @@ var klaviyo_default2 = {
|
|
|
1754
2178
|
// the refresh token is the only thing that asks Klaviyo.
|
|
1755
2179
|
//
|
|
1756
2180
|
// It also keeps the grant warm against the 90-day idle window above.
|
|
1757
|
-
probe: async ({ clientId, clientSecret,
|
|
2181
|
+
probe: async ({ clientId, clientSecret, manifest, settings }, { fetcher } = {}) => {
|
|
1758
2182
|
const token = await accessToken({
|
|
1759
2183
|
clientId,
|
|
1760
2184
|
clientSecret,
|
|
@@ -1784,12 +2208,11 @@ var klaviyo_default2 = {
|
|
|
1784
2208
|
// the store's.
|
|
1785
2209
|
commerce: false,
|
|
1786
2210
|
// The verb the contacts.sync step points at. It does the work — including
|
|
1787
|
-
// writing the profile id back onto the lead — and returns what happened.
|
|
1788
2211
|
contacts: {
|
|
1789
2212
|
// Not yet. Suppression syncs an opt-out as unsubscribed, which is a
|
|
1790
2213
|
// different thing from deleting the profile.
|
|
1791
2214
|
remove: false,
|
|
1792
|
-
sync: async ({ contact,
|
|
2215
|
+
sync: async ({ contact, lead, settings, suppressed, token }, { fetcher } = {}) => {
|
|
1793
2216
|
var _a, _b, _c;
|
|
1794
2217
|
const list = settings == null ? void 0 : settings.list;
|
|
1795
2218
|
if (!list) return { message: "No Klaviyo list is chosen for this connection.", skipped: true };
|
|
@@ -1881,7 +2304,7 @@ var klaviyo_default2 = {
|
|
|
1881
2304
|
// it, so one call quietly returns the first ten lists and an account
|
|
1882
2305
|
// with more shows a picker missing the one they wanted, with nothing to
|
|
1883
2306
|
// indicate anything was cut.
|
|
1884
|
-
audiences: async ({ cursor,
|
|
2307
|
+
audiences: async ({ cursor, limit = 100, search, token }, { fetcher } = {}) => {
|
|
1885
2308
|
var _a, _b;
|
|
1886
2309
|
const audiences = [];
|
|
1887
2310
|
let next = cursor ? "/lists?page%5Bsize%5D=10&page%5Bcursor%5D=" + encodeURIComponent(cursor) : "/lists?page%5Bsize%5D=10";
|
|
@@ -1993,7 +2416,7 @@ var mailchimp_default = `<svg width="500" height="500" viewBox="0 0 500 500" fil
|
|
|
1993
2416
|
<path d="M360.476 284.243C360.35 283.835 359.618 281.204 358.647 278.052L356.621 272.648C360.575 266.696 360.645 261.405 360.124 258.393C359.531 254.519 357.693 250.944 354.89 248.205C351.766 244.94 345.363 241.563 336.385 239.044L331.671 237.736C331.643 237.524 331.418 226.619 331.235 221.933C331.08 218.555 330.798 213.264 329.152 208.058C327.182 200.993 323.791 194.858 319.527 190.876C331.277 178.717 338.594 165.307 338.58 153.81C338.538 131.703 311.379 124.976 277.902 138.851L270.824 141.863C270.795 141.835 258.004 129.283 257.821 129.128C219.63 95.8334 100.327 228.476 138.49 260.687L146.835 267.737C144.581 273.775 143.781 280.259 144.499 286.664C145.414 295.543 149.973 304.029 157.375 310.6C164.411 316.82 173.684 320.788 182.648 320.774C197.494 354.998 231.408 375.965 271.175 377.161C313.842 378.427 349.641 358.403 364.67 322.435C365.641 319.916 369.806 308.546 369.806 298.513C369.792 288.409 364.093 284.229 360.476 284.243ZM185.913 311.149C184.613 311.381 183.293 311.48 181.973 311.445C169.083 311.079 155.166 299.483 153.787 285.735C152.253 270.537 160.02 258.829 173.783 256.071C175.415 255.72 177.414 255.537 179.552 255.635C187.264 256.085 198.606 261.996 201.209 278.784C203.517 293.63 199.858 308.785 185.913 311.149ZM171.545 246.953C163.179 248.499 155.744 253.244 150.817 260.18C148.045 257.873 142.909 253.426 142.008 251.681C134.635 237.693 150.043 210.478 160.823 195.111C187.405 157.145 229.086 128.424 248.393 133.603C251.517 134.503 261.902 146.563 261.902 146.563C261.902 146.563 242.623 157.244 224.724 172.16C200.646 190.735 182.423 217.697 171.545 246.953ZM306.792 305.464C306.937 305.403 307.057 305.295 307.134 305.157C307.211 305.019 307.239 304.86 307.214 304.704C307.205 304.61 307.178 304.519 307.133 304.436C307.088 304.353 307.027 304.28 306.954 304.221C306.88 304.162 306.796 304.118 306.705 304.092C306.614 304.066 306.519 304.059 306.426 304.071C306.426 304.071 286.246 307.054 267.179 300.089C269.247 293.348 274.792 295.754 283.137 296.444C296.108 297.209 309.116 295.802 321.623 292.279C330.25 289.788 341.592 284.905 350.401 277.953C353.384 284.497 354.425 291.674 354.425 291.674C354.425 291.674 356.719 291.265 358.647 292.447C360.476 293.573 361.799 295.895 360.898 301.89C359.027 313.119 354.271 322.224 346.235 330.611C341.236 336.036 335.277 340.492 328.659 343.754C324.983 345.691 321.151 347.32 317.205 348.623C286.964 358.487 256.006 347.638 246.029 324.321C245.224 322.535 244.556 320.691 244.03 318.804C239.781 303.438 243.383 285.032 254.655 273.408C255.372 272.676 256.09 271.804 256.09 270.706C256.09 269.806 255.499 268.835 255.007 268.131C251.066 262.418 237.374 252.666 240.132 233.795C242.088 220.23 253.951 210.689 265.012 211.252L267.826 211.421C272.611 211.702 276.79 212.307 280.73 212.49C287.344 212.758 293.268 211.801 300.304 205.947C302.683 203.949 304.582 202.246 307.791 201.711C308.128 201.627 308.973 201.359 310.647 201.416C312.365 201.485 314.032 202.015 315.474 202.949C321.103 206.693 321.905 215.783 322.214 222.439C322.383 226.225 322.848 235.414 322.988 238.031C323.354 244.054 324.944 244.912 328.125 245.954C329.94 246.573 331.615 246.995 334.077 247.713C341.521 249.781 345.968 251.934 348.754 254.65C350.198 256.049 351.13 257.893 351.4 259.885C352.315 266.316 346.432 274.252 330.925 281.457C313.954 289.324 293.367 291.322 279.154 289.732L274.173 289.169C262.774 287.649 256.315 302.34 263.14 312.402C267.545 318.889 279.52 323.11 291.523 323.11C319.006 323.139 340.142 311.402 348.023 301.242L348.642 300.356C349.008 299.765 348.712 299.469 348.22 299.779C341.817 304.169 313.279 321.619 282.771 316.384C282.771 316.384 279.056 315.765 275.678 314.442C273.005 313.429 267.362 310.811 266.686 305.042C291.27 312.683 306.792 305.478 306.792 305.464ZM220.671 194.971C230.127 184.051 241.765 174.538 252.206 169.219C252.558 169.022 252.938 169.43 252.741 169.754C251.46 172 250.476 174.403 249.814 176.902C249.73 177.282 250.138 177.592 250.461 177.353C256.963 172.934 268.248 168.192 278.155 167.601C278.251 167.584 278.351 167.601 278.436 167.65C278.521 167.698 278.586 167.775 278.621 167.866C278.656 167.957 278.658 168.058 278.627 168.151C278.596 168.244 278.533 168.323 278.451 168.375C276.809 169.634 275.342 171.105 274.088 172.751C273.891 173.032 274.074 173.44 274.426 173.44C281.378 173.483 291.186 175.903 297.56 179.491C297.982 179.745 297.673 180.575 297.209 180.462C287.527 178.253 271.724 176.564 255.288 180.575C240.597 184.149 229.396 189.666 221.248 195.618C220.826 195.899 220.333 195.351 220.671 194.971Z" fill="#231E15"/>
|
|
1994
2417
|
</svg>`;
|
|
1995
2418
|
|
|
1996
|
-
// lib/connections/mailchimp.js
|
|
2419
|
+
// lib/connections/providers/mailchimp.js
|
|
1997
2420
|
var base = (dc) => {
|
|
1998
2421
|
if (!dc) throw new Error("This Mailchimp connection has no data centre stored, so there is no host to call");
|
|
1999
2422
|
return "https://" + dc + ".api.mailchimp.com/3.0";
|
|
@@ -2082,7 +2505,7 @@ var mailchimp_default2 = {
|
|
|
2082
2505
|
// The header here is `OAuth <token>`, not Bearer — that is specific to
|
|
2083
2506
|
// the metadata endpoint. Marketing API calls take Bearer; see the
|
|
2084
2507
|
// audiences hook.
|
|
2085
|
-
connect: async ({ fetcher = fetch
|
|
2508
|
+
connect: async ({ tokens }, { fetcher = fetch } = {}) => {
|
|
2086
2509
|
const response = await fetcher("https://login.mailchimp.com/oauth2/metadata", {
|
|
2087
2510
|
headers: {
|
|
2088
2511
|
authorization: "OAuth " + (tokens == null ? void 0 : tokens.accessToken)
|
|
@@ -2134,7 +2557,7 @@ var mailchimp_default2 = {
|
|
|
2134
2557
|
// successful — the same silent truncation Klaviyo has, at a different
|
|
2135
2558
|
// number. Paged against total_items so an account past a thousand still
|
|
2136
2559
|
// resolves.
|
|
2137
|
-
audiences: async ({ cursor,
|
|
2560
|
+
audiences: async ({ cursor, limit = 100, search, settings, token }, { fetcher = fetch } = {}) => {
|
|
2138
2561
|
const dc = settings == null ? void 0 : settings.dc;
|
|
2139
2562
|
const count = Math.min(limit, 1e3);
|
|
2140
2563
|
const offset = Number(cursor || 0);
|
|
@@ -2213,6 +2636,10 @@ var mailchimp_default2 = {
|
|
|
2213
2636
|
title: "Mailchimp"
|
|
2214
2637
|
};
|
|
2215
2638
|
|
|
2639
|
+
// lib/connections/providers/shopify.js
|
|
2640
|
+
import { randomUUID } from "crypto";
|
|
2641
|
+
import { customAlphabet as customAlphabet2 } from "nanoid";
|
|
2642
|
+
|
|
2216
2643
|
// lib/connections/icons/shopify.js
|
|
2217
2644
|
var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2218
2645
|
<rect width="500" height="500" fill="white"/>
|
|
@@ -2223,12 +2650,15 @@ var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
|
|
|
2223
2650
|
|
|
2224
2651
|
// lib/connections/inbound.js
|
|
2225
2652
|
import { createHmac, timingSafeEqual } from "crypto";
|
|
2226
|
-
var verifySignature = ({ body, descriptor, headers }) => {
|
|
2653
|
+
var verifySignature = ({ body, descriptor, headers, secret }) => {
|
|
2654
|
+
if (!secret) {
|
|
2655
|
+
throw Object.assign(new Error("Missing webhook secret: " + descriptor.signature.secret), { status: 500 });
|
|
2656
|
+
}
|
|
2227
2657
|
const provided = headers[descriptor.headers.signature];
|
|
2228
2658
|
if (!provided) {
|
|
2229
2659
|
throw Object.assign(new Error("Missing webhook signature"), { status: 401 });
|
|
2230
2660
|
}
|
|
2231
|
-
const digest = createHmac(descriptor.signature.algorithm,
|
|
2661
|
+
const digest = createHmac(descriptor.signature.algorithm, secret).update(body).digest(descriptor.signature.encoding);
|
|
2232
2662
|
const digestBuffer = Buffer.from(digest, descriptor.signature.encoding);
|
|
2233
2663
|
const providedBuffer = Buffer.from(provided, descriptor.signature.encoding);
|
|
2234
2664
|
if (digestBuffer.length !== providedBuffer.length || !timingSafeEqual(digestBuffer, providedBuffer)) {
|
|
@@ -2238,7 +2668,72 @@ var verifySignature = ({ body, descriptor, headers }) => {
|
|
|
2238
2668
|
};
|
|
2239
2669
|
var readEventHeader = ({ descriptor, headers }) => headers[descriptor.headers.event];
|
|
2240
2670
|
|
|
2241
|
-
// lib/
|
|
2671
|
+
// lib/email.js
|
|
2672
|
+
var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
|
|
2673
|
+
var toCanonicalEmail = (value) => {
|
|
2674
|
+
if (!value || typeof value !== "string") return null;
|
|
2675
|
+
const email = value.trim().toLowerCase();
|
|
2676
|
+
const at = email.lastIndexOf("@");
|
|
2677
|
+
if (at < 1 || at === email.length - 1) return null;
|
|
2678
|
+
let local = email.slice(0, at);
|
|
2679
|
+
const domain = email.slice(at + 1);
|
|
2680
|
+
const plus = local.indexOf("+");
|
|
2681
|
+
if (plus > 0) local = local.slice(0, plus);
|
|
2682
|
+
if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
|
|
2683
|
+
if (!local) return null;
|
|
2684
|
+
return local + "@" + domain;
|
|
2685
|
+
};
|
|
2686
|
+
|
|
2687
|
+
// lib/phone.js
|
|
2688
|
+
import { AsYouType, parsePhoneNumberFromString, isValidPhoneNumber } from "libphonenumber-js";
|
|
2689
|
+
var toE164 = (value, country) => {
|
|
2690
|
+
if (!value) return null;
|
|
2691
|
+
try {
|
|
2692
|
+
const parsed = parsePhoneNumberFromString(String(value), country);
|
|
2693
|
+
return parsed ? parsed.number : null;
|
|
2694
|
+
} catch {
|
|
2695
|
+
return null;
|
|
2696
|
+
}
|
|
2697
|
+
};
|
|
2698
|
+
|
|
2699
|
+
// lib/connections/providers/shopify.js
|
|
2700
|
+
var toLine = ({
|
|
2701
|
+
price,
|
|
2702
|
+
product_id: productId,
|
|
2703
|
+
quantity,
|
|
2704
|
+
title,
|
|
2705
|
+
variant_id: variantId,
|
|
2706
|
+
variant_title: variantTitle
|
|
2707
|
+
}) => ({
|
|
2708
|
+
price: parseFloat(price) || 0,
|
|
2709
|
+
productId: productId ? "gid://shopify/Product/" + productId : null,
|
|
2710
|
+
quantity: quantity || 1,
|
|
2711
|
+
title: title || null,
|
|
2712
|
+
variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
|
|
2713
|
+
variantTitle: variantTitle || null
|
|
2714
|
+
});
|
|
2715
|
+
var attributeLineItems = (lineItems = []) => lineItems.reduce(
|
|
2716
|
+
(acc, item) => {
|
|
2717
|
+
const attrs = (item.properties || []).reduce(
|
|
2718
|
+
(map, { name, value }) => {
|
|
2719
|
+
map[name] = value;
|
|
2720
|
+
return map;
|
|
2721
|
+
},
|
|
2722
|
+
{}
|
|
2723
|
+
);
|
|
2724
|
+
if (!attrs["_drwbrdg_ca"]) return acc;
|
|
2725
|
+
if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
|
|
2726
|
+
const line = toLine(item);
|
|
2727
|
+
acc.attributedGross += line.price * line.quantity;
|
|
2728
|
+
acc.attributedLines.push(line);
|
|
2729
|
+
return acc;
|
|
2730
|
+
},
|
|
2731
|
+
{ attrMap: {}, attributedGross: 0, attributedLines: [] }
|
|
2732
|
+
);
|
|
2733
|
+
var generateDiscountCode = customAlphabet2("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
|
|
2734
|
+
var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
|
|
2735
|
+
var OAUTH_ERROR_SOURCE = "oauth";
|
|
2736
|
+
var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
|
|
2242
2737
|
var inbound = {
|
|
2243
2738
|
headers: {
|
|
2244
2739
|
event: "x-shopify-topic",
|
|
@@ -2355,20 +2850,476 @@ var shopify_default2 = {
|
|
|
2355
2850
|
//
|
|
2356
2851
|
// `shopify` is injected for the same reason it is everywhere else — this
|
|
2357
2852
|
// package cannot import @drawbridge/shopify, which depends on it.
|
|
2358
|
-
scopes: ({ scope, shopify }) => scope ? shopify.oauth.missingScopes(scope) : null,
|
|
2853
|
+
scopes: ({ scope }, { shopify } = {}) => scope ? shopify.oauth.missingScopes(scope) : null,
|
|
2359
2854
|
// Shopify's install grant is exchanged inside its own app flow, not
|
|
2360
2855
|
// through the shared OAuth runner.
|
|
2361
2856
|
token: false
|
|
2362
2857
|
},
|
|
2363
|
-
//
|
|
2364
|
-
//
|
|
2365
|
-
//
|
|
2366
|
-
//
|
|
2858
|
+
// THE VENDOR'S OWN WORK, here in full. Every body describes its writes,
|
|
2859
|
+
// enqueues and events for the shell to perform — see contract.js — and
|
|
2860
|
+
// everything it needs arrives as an argument: `read` (the controller's
|
|
2861
|
+
// read methods, nothing that writes), `shopify` (the SDK, injected because
|
|
2862
|
+
// this package cannot import what depends on it), `adminToken` (minted by
|
|
2863
|
+
// the shell, which persists rotations), `mintId` (so one described write
|
|
2864
|
+
// can reference another), `dispatch` (the caller's own coordinator table,
|
|
2865
|
+
// for the hooks that are dispatches).
|
|
2367
2866
|
commerce: {
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2867
|
+
// MINT A DISCOUNT CODE against the merchant's chosen discount, mapped to
|
|
2868
|
+
// one lead — which is what lets an order that redeems it be attributed
|
|
2869
|
+
// back.
|
|
2870
|
+
code: async ({ connection: connection2, context, step }, { adminToken, shopify } = {}) => {
|
|
2871
|
+
var _a;
|
|
2872
|
+
const discount = (_a = step.settings) == null ? void 0 : _a.discount;
|
|
2873
|
+
const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
|
|
2874
|
+
if (!(context == null ? void 0 : context.email)) return { message: "Lead email is missing.", request: request2, response: { skipped: true }, skipped: true };
|
|
2875
|
+
if (!(context == null ? void 0 : context.lead)) return { message: "Lead id is missing.", request: request2, response: { skipped: true }, skipped: true };
|
|
2876
|
+
if (!(discount == null ? void 0 : discount.id)) return { message: "Discount is not configured on this step.", request: request2, response: { skipped: true }, skipped: true };
|
|
2877
|
+
const adminAccessToken = await adminToken();
|
|
2878
|
+
if (!context.shopifyCustomerId) {
|
|
2879
|
+
const customer = await shopify.admin.getOrCreateCustomer({ adminAccessToken, domain: connection2.shop, email: context.email });
|
|
2880
|
+
if (!(customer == null ? void 0 : customer.id)) return { message: "Shopify did not return a customer id \u2014 create/lookup failed.", request: request2, response: { skipped: true }, skipped: true };
|
|
2881
|
+
}
|
|
2882
|
+
const discountCode = await shopify.admin.createDiscountCode({
|
|
2883
|
+
adminAccessToken,
|
|
2884
|
+
code: "DB-" + generateDiscountCode(),
|
|
2885
|
+
discountId: discount.id,
|
|
2886
|
+
domain: connection2.shop
|
|
2887
|
+
});
|
|
2888
|
+
if (!discountCode) return { message: "Shopify did not return a discount code \u2014 create failed.", request: request2, response: { skipped: true }, skipped: true };
|
|
2889
|
+
return {
|
|
2890
|
+
context: {
|
|
2891
|
+
shopifyDiscountCode: discountCode.code,
|
|
2892
|
+
shopifyDiscountId: String(discountCode.id)
|
|
2893
|
+
},
|
|
2894
|
+
message: "Discount code created and linked to lead.",
|
|
2895
|
+
request: request2,
|
|
2896
|
+
response: { code: discountCode.code, id: String(discountCode.id) },
|
|
2897
|
+
// bypassDocumentValidation because these are vendor ids on a
|
|
2898
|
+
// Drawbridge document the schema does not declare — the
|
|
2899
|
+
// canonical-identity work resolves it properly.
|
|
2900
|
+
writes: [{
|
|
2901
|
+
collection: "lead",
|
|
2902
|
+
data: {
|
|
2903
|
+
$set: {
|
|
2904
|
+
shopifyDiscountCode: discountCode.code,
|
|
2905
|
+
shopifyDiscountId: String(discountCode.id)
|
|
2906
|
+
}
|
|
2907
|
+
},
|
|
2908
|
+
operation: "update",
|
|
2909
|
+
options: { bypassDocumentValidation: true },
|
|
2910
|
+
query: { id: context.lead }
|
|
2911
|
+
}]
|
|
2912
|
+
};
|
|
2913
|
+
},
|
|
2914
|
+
// CREATE THE BUYER AT THE STORE, so an order can be attributed to them.
|
|
2915
|
+
//
|
|
2916
|
+
// IDEMPOTENT THREE WAYS, because this runs on every entry and a duplicate
|
|
2917
|
+
// customer at the store is a support ticket: the context may already
|
|
2918
|
+
// carry the id from an earlier step, the lead may already be linked from
|
|
2919
|
+
// an earlier run, and Shopify's own get-or-create settles the rest.
|
|
2920
|
+
customer: async ({ connection: connection2, context }, { adminToken, read, shopify } = {}) => {
|
|
2921
|
+
const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
|
|
2922
|
+
if (!(context == null ? void 0 : context.email)) return { message: "Lead email is missing \u2014 cannot create Shopify customer.", request: request2, response: { skipped: true }, skipped: true };
|
|
2923
|
+
if (!(context == null ? void 0 : context.lead)) return { message: "Lead id is missing \u2014 cannot create Shopify customer.", request: request2, response: { skipped: true }, skipped: true };
|
|
2924
|
+
if (context.shopifyCustomerId) {
|
|
2925
|
+
return {
|
|
2926
|
+
context: { shopifyCustomerId: context.shopifyCustomerId },
|
|
2927
|
+
message: "Trigger data already includes a Shopify customer id \u2014 reusing.",
|
|
2928
|
+
request: request2,
|
|
2929
|
+
response: { shopifyCustomerId: context.shopifyCustomerId },
|
|
2930
|
+
// Reusing an id is not a creation, so it does not bill.
|
|
2931
|
+
skipped: true
|
|
2932
|
+
};
|
|
2933
|
+
}
|
|
2934
|
+
const lead = await read.get({ collection: "lead", query: { id: context.lead } });
|
|
2935
|
+
if (lead == null ? void 0 : lead.shopifyCustomerId) {
|
|
2936
|
+
return {
|
|
2937
|
+
context: { shopifyCustomerId: lead.shopifyCustomerId },
|
|
2938
|
+
message: "Lead already has a Shopify customer id \u2014 reusing.",
|
|
2939
|
+
request: request2,
|
|
2940
|
+
response: { shopifyCustomerId: lead.shopifyCustomerId },
|
|
2941
|
+
skipped: true
|
|
2942
|
+
};
|
|
2943
|
+
}
|
|
2944
|
+
const adminAccessToken = await adminToken();
|
|
2945
|
+
const parts = ((lead == null ? void 0 : lead.name) || "").trim().split(/\s+/).filter(Boolean);
|
|
2946
|
+
const customer = await shopify.admin.getOrCreateCustomer({
|
|
2947
|
+
adminAccessToken,
|
|
2948
|
+
domain: connection2.shop,
|
|
2949
|
+
email: context.email,
|
|
2950
|
+
firstName: parts.length ? parts[0] : null,
|
|
2951
|
+
lastName: parts.length > 1 ? parts.slice(1).join(" ") : null,
|
|
2952
|
+
source: "drawbridge"
|
|
2953
|
+
});
|
|
2954
|
+
if (!(customer == null ? void 0 : customer.id)) return { message: "Shopify did not return a customer id \u2014 create/lookup failed.", request: request2, response: { skipped: true }, skipped: true };
|
|
2955
|
+
return {
|
|
2956
|
+
context: { shopifyCustomerId: customer.id },
|
|
2957
|
+
message: "Shopify customer created/linked to lead.",
|
|
2958
|
+
request: request2,
|
|
2959
|
+
response: { shopifyCustomerId: customer.id },
|
|
2960
|
+
// The hook's own result, described beside the call that produced it.
|
|
2961
|
+
writes: [{
|
|
2962
|
+
collection: "lead",
|
|
2963
|
+
data: { $set: { shopifyCustomerId: customer.id } },
|
|
2964
|
+
operation: "update",
|
|
2965
|
+
options: { bypassDocumentValidation: true },
|
|
2966
|
+
query: { id: context.lead }
|
|
2967
|
+
}]
|
|
2968
|
+
};
|
|
2969
|
+
},
|
|
2970
|
+
// AN ORDER ARRIVED AT THE STORE. The largest hook in the family, because
|
|
2971
|
+
// attribution genuinely is: an order can reach Drawbridge two ways and
|
|
2972
|
+
// they bill differently.
|
|
2973
|
+
//
|
|
2974
|
+
// CONVERSION — a `_drwbrdg_ca` line-item property, injected at
|
|
2975
|
+
// add-to-cart. Causal: the campaign produced the sale, so
|
|
2976
|
+
// it carries a fee.
|
|
2977
|
+
// REDEMPTION — a DB- discount code matched to a lead. Associative: we
|
|
2978
|
+
// cannot claim we caused the purchase, so it is fee-free.
|
|
2979
|
+
//
|
|
2980
|
+
// Both can be true, and an order already recorded as a conversion can
|
|
2981
|
+
// later have a redemption backfilled onto it — `backfill` below.
|
|
2982
|
+
//
|
|
2983
|
+
// IDEMPOTENT THROUGH THE RETRY, one layer up: two deliveries of the same
|
|
2984
|
+
// order race, the loser's transaction hits a duplicate key, the step
|
|
2985
|
+
// fails and BullMQ redelivers — and the re-run's read at the top finds
|
|
2986
|
+
// what the winner wrote and skips instead of double-billing a merchant
|
|
2987
|
+
// for one purchase. The hook used to loop for this itself; describing
|
|
2988
|
+
// the writes moved the retry to the queue, with the same guarantee.
|
|
2989
|
+
order: async ({ connection: connection2, context }, { logger: logger2, mintId, read } = {}) => {
|
|
2990
|
+
var _a, _b, _c, _d, _e, _f;
|
|
2991
|
+
const {
|
|
2992
|
+
advertisement,
|
|
2993
|
+
created_at: createdAt,
|
|
2994
|
+
currency,
|
|
2995
|
+
customer: orderCustomer,
|
|
2996
|
+
email,
|
|
2997
|
+
id: orderId,
|
|
2998
|
+
line_items: lineItems = [],
|
|
2999
|
+
organization: organization2,
|
|
3000
|
+
phone
|
|
3001
|
+
} = context || {};
|
|
3002
|
+
const request2 = { orderId: orderId ? String(orderId) : null, organization: organization2 };
|
|
3003
|
+
const [existingOrder, existingRedemption] = await Promise.all([
|
|
3004
|
+
read.get({ collection: "order", query: { "provider.id": String(orderId), "provider.slug": "shopify" } }),
|
|
3005
|
+
read.get({ collection: "redemption", query: { "provider.id": String(orderId), "provider.slug": "shopify" } })
|
|
3006
|
+
]);
|
|
3007
|
+
if (existingRedemption) {
|
|
3008
|
+
return {
|
|
3009
|
+
message: "Order/redemption already recorded \u2014 skipping duplicate.",
|
|
3010
|
+
request: request2,
|
|
3011
|
+
response: {
|
|
3012
|
+
existingOrderId: (existingOrder == null ? void 0 : existingOrder.id) || null,
|
|
3013
|
+
existingRedemptionId: existingRedemption.id,
|
|
3014
|
+
skipped: true
|
|
3015
|
+
},
|
|
3016
|
+
skipped: true
|
|
3017
|
+
};
|
|
3018
|
+
}
|
|
3019
|
+
const backfill = !!existingOrder;
|
|
3020
|
+
const { attrMap, attributedGross, attributedLines } = attributeLineItems(lineItems);
|
|
3021
|
+
const campaign = attrMap["_drwbrdg_ca"] || null;
|
|
3022
|
+
const discountCodes = Array.isArray(context == null ? void 0 : context.discount_codes) ? context.discount_codes : [];
|
|
3023
|
+
const codes = [...new Set(discountCodes.map((dc) => dc == null ? void 0 : dc.code).filter(Boolean))];
|
|
3024
|
+
const matchedLeads = codes.length ? await read.aggregate({
|
|
3025
|
+
collection: "lead",
|
|
3026
|
+
pipeline: [{ $match: { organization: organization2, shopifyDiscountCode: { $in: codes } } }]
|
|
3027
|
+
}) : [];
|
|
3028
|
+
const codeToLead = {};
|
|
3029
|
+
for (const found of matchedLeads) {
|
|
3030
|
+
if (found.shopifyDiscountCode) codeToLead[found.shopifyDiscountCode] = found;
|
|
3031
|
+
}
|
|
3032
|
+
const matchedDiscounts = discountCodes.filter((dc) => (dc == null ? void 0 : dc.code) && codeToLead[dc.code]).map((dc) => ({
|
|
3033
|
+
amount: parseFloat(dc.amount) || 0,
|
|
3034
|
+
code: dc.code,
|
|
3035
|
+
id: codeToLead[dc.code].shopifyDiscountId || null
|
|
3036
|
+
}));
|
|
3037
|
+
const matchedLead = matchedDiscounts.length ? codeToLead[matchedDiscounts[0].code] : null;
|
|
3038
|
+
const discount = matchedDiscounts.length ? {
|
|
3039
|
+
amount: matchedDiscounts.reduce((sum, entry) => sum + entry.amount, 0),
|
|
3040
|
+
codes: matchedDiscounts
|
|
3041
|
+
} : null;
|
|
3042
|
+
const matchedCodes = new Set(matchedDiscounts.map((entry) => entry.code));
|
|
3043
|
+
const unmatched = codes.filter((code2) => code2.startsWith("DB-") && !matchedCodes.has(code2));
|
|
3044
|
+
if (unmatched.length) {
|
|
3045
|
+
(_a = logger2 == null ? void 0 : logger2.warn) == null ? void 0 : _a.call(logger2, "shopify.order.discount.unmatched", {
|
|
3046
|
+
campaign: campaign || null,
|
|
3047
|
+
codes: JSON.stringify(unmatched),
|
|
3048
|
+
isConversion: !!campaign,
|
|
3049
|
+
orderId: String(orderId),
|
|
3050
|
+
organization: organization2
|
|
3051
|
+
});
|
|
3052
|
+
}
|
|
3053
|
+
if (!campaign && !discount || backfill && !discount) {
|
|
3054
|
+
return {
|
|
3055
|
+
message: backfill ? "Order already recorded and no Drawbridge discount code matched \u2014 nothing to backfill." : "Order has no Drawbridge attribution \u2014 not recording.",
|
|
3056
|
+
request: request2,
|
|
3057
|
+
response: { skipped: true },
|
|
3058
|
+
skipped: true
|
|
3059
|
+
};
|
|
3060
|
+
}
|
|
3061
|
+
let advertisementId = null;
|
|
3062
|
+
let affiliateId = null;
|
|
3063
|
+
let campaignOrganization = organization2;
|
|
3064
|
+
let gross = 0;
|
|
3065
|
+
let leadId = null;
|
|
3066
|
+
let lines = [];
|
|
3067
|
+
let orderCampaign = null;
|
|
3068
|
+
let pageId = null;
|
|
3069
|
+
const isConversion = !!campaign;
|
|
3070
|
+
const customerPhone = toE164((orderCustomer == null ? void 0 : orderCustomer.phone) || phone) || null;
|
|
3071
|
+
const matchPhones = [...new Set([
|
|
3072
|
+
customerPhone,
|
|
3073
|
+
toE164((_b = context == null ? void 0 : context.billing_address) == null ? void 0 : _b.phone),
|
|
3074
|
+
toE164((_c = context == null ? void 0 : context.shipping_address) == null ? void 0 : _c.phone)
|
|
3075
|
+
].filter(Boolean))];
|
|
3076
|
+
if (isConversion) {
|
|
3077
|
+
const campaignDoc = await read.get({ collection: "campaign", query: { id: campaign } });
|
|
3078
|
+
if (!campaignDoc || campaignDoc.organization !== organization2) {
|
|
3079
|
+
return {
|
|
3080
|
+
message: "Order carried a campaign attribution that does not belong to this store \u2014 not recording.",
|
|
3081
|
+
request: request2,
|
|
3082
|
+
response: { skipped: true },
|
|
3083
|
+
skipped: true
|
|
3084
|
+
};
|
|
3085
|
+
}
|
|
3086
|
+
advertisementId = attrMap["_drwbrdg_ad"] || advertisement || null;
|
|
3087
|
+
affiliateId = attrMap["_drwbrdg_af"] || null;
|
|
3088
|
+
campaignOrganization = campaignDoc.organization;
|
|
3089
|
+
gross = attributedGross;
|
|
3090
|
+
lines = attributedLines;
|
|
3091
|
+
orderCampaign = campaign;
|
|
3092
|
+
pageId = attrMap["_drwbrdg_pg"] || null;
|
|
3093
|
+
const identifiers = [];
|
|
3094
|
+
const canonicalEmail = toCanonicalEmail(email);
|
|
3095
|
+
if (email) identifiers.push({ email: email.toLowerCase() });
|
|
3096
|
+
if (canonicalEmail) identifiers.push({ "canonical.email.value": canonicalEmail });
|
|
3097
|
+
if (matchPhones.length) identifiers.push({ "phone.number": { $in: matchPhones } });
|
|
3098
|
+
if (matchPhones.length) identifiers.push({ "canonical.phone.value": { $in: matchPhones } });
|
|
3099
|
+
if (identifiers.length) {
|
|
3100
|
+
const lead = await read.get({
|
|
3101
|
+
collection: "lead",
|
|
3102
|
+
query: {
|
|
3103
|
+
campaigns: { $in: [campaign] },
|
|
3104
|
+
organization: campaignOrganization,
|
|
3105
|
+
$or: identifiers
|
|
3106
|
+
}
|
|
3107
|
+
});
|
|
3108
|
+
leadId = (lead == null ? void 0 : lead.id) || null;
|
|
3109
|
+
if (!leadId) {
|
|
3110
|
+
const orgLead = await read.get({
|
|
3111
|
+
collection: "lead",
|
|
3112
|
+
query: { organization: campaignOrganization, $or: identifiers }
|
|
3113
|
+
});
|
|
3114
|
+
leadId = (orgLead == null ? void 0 : orgLead.id) || null;
|
|
3115
|
+
}
|
|
3116
|
+
}
|
|
3117
|
+
} else {
|
|
3118
|
+
leadId = matchedLead.id;
|
|
3119
|
+
orderCampaign = (matchedLead.campaigns || []).length === 1 ? matchedLead.campaigns[0] : null;
|
|
3120
|
+
gross = lineItems.reduce((sum, item) => {
|
|
3121
|
+
const line = toLine(item);
|
|
3122
|
+
return sum + line.price * line.quantity;
|
|
3123
|
+
}, 0);
|
|
3124
|
+
lines = lineItems.map(toLine);
|
|
3125
|
+
}
|
|
3126
|
+
const org = await read.get({ collection: "organization", query: { id: campaignOrganization } });
|
|
3127
|
+
let rate = 0;
|
|
3128
|
+
if (isConversion) {
|
|
3129
|
+
const subscription = await read.get({ collection: "subscription", query: { id: org == null ? void 0 : org.subscription } });
|
|
3130
|
+
rate = conversionRate(subscription);
|
|
3131
|
+
}
|
|
3132
|
+
const fee = isConversion ? Math.round(gross * rate) / 100 : 0;
|
|
3133
|
+
const net2 = Math.round((gross - fee) * 100) / 100;
|
|
3134
|
+
const currencyCode = (currency || "usd").toLowerCase();
|
|
3135
|
+
const purchasedAt = new Date(createdAt || Date.now());
|
|
3136
|
+
const customer = orderCustomer || email || phone ? {
|
|
3137
|
+
acceptsMarketing: ((_d = orderCustomer == null ? void 0 : orderCustomer.email_marketing_consent) == null ? void 0 : _d.state) ? orderCustomer.email_marketing_consent.state === "subscribed" : typeof (orderCustomer == null ? void 0 : orderCustomer.accepts_marketing) === "boolean" ? orderCustomer.accepts_marketing : null,
|
|
3138
|
+
email: (orderCustomer == null ? void 0 : orderCustomer.email) || email || null,
|
|
3139
|
+
firstName: (orderCustomer == null ? void 0 : orderCustomer.first_name) || null,
|
|
3140
|
+
id: (orderCustomer == null ? void 0 : orderCustomer.id) ? String(orderCustomer.id) : null,
|
|
3141
|
+
lastName: (orderCustomer == null ? void 0 : orderCustomer.last_name) || null,
|
|
3142
|
+
phone: customerPhone
|
|
3143
|
+
} : null;
|
|
3144
|
+
const source = (connection2 == null ? void 0 : connection2.source) ? { domain: connection2.source.domain, id: connection2.source.id } : void 0;
|
|
3145
|
+
const orderDocId = (existingOrder == null ? void 0 : existingOrder.id) || (isConversion && !backfill ? mintId() : null);
|
|
3146
|
+
const writes = [];
|
|
3147
|
+
if (isConversion && !backfill) {
|
|
3148
|
+
writes.push({
|
|
3149
|
+
collection: "order",
|
|
3150
|
+
data: {
|
|
3151
|
+
advertisement: advertisementId,
|
|
3152
|
+
affiliate: affiliateId,
|
|
3153
|
+
campaign: orderCampaign,
|
|
3154
|
+
currency: currencyCode,
|
|
3155
|
+
customer,
|
|
3156
|
+
discount,
|
|
3157
|
+
fee,
|
|
3158
|
+
gross,
|
|
3159
|
+
id: orderDocId,
|
|
3160
|
+
lead: leadId,
|
|
3161
|
+
lines,
|
|
3162
|
+
net: net2,
|
|
3163
|
+
organization: campaignOrganization,
|
|
3164
|
+
page: pageId,
|
|
3165
|
+
provider: { id: String(orderId), slug: "shopify" },
|
|
3166
|
+
purchasedAt,
|
|
3167
|
+
rate,
|
|
3168
|
+
source,
|
|
3169
|
+
status: "completed"
|
|
3170
|
+
},
|
|
3171
|
+
operation: "create"
|
|
3172
|
+
});
|
|
3173
|
+
if (org == null ? void 0 : org.usage) {
|
|
3174
|
+
writes.push({
|
|
3175
|
+
collection: "usage",
|
|
3176
|
+
data: { $inc: { "totals.revenue": gross } },
|
|
3177
|
+
operation: "update",
|
|
3178
|
+
query: { id: org.usage }
|
|
3179
|
+
});
|
|
3180
|
+
}
|
|
3181
|
+
if (leadId) {
|
|
3182
|
+
writes.push({
|
|
3183
|
+
collection: "lead",
|
|
3184
|
+
data: { $inc: { "totals.orders": 1 } },
|
|
3185
|
+
operation: "update",
|
|
3186
|
+
options: { bypassDocumentValidation: true },
|
|
3187
|
+
query: { id: leadId }
|
|
3188
|
+
});
|
|
3189
|
+
}
|
|
3190
|
+
}
|
|
3191
|
+
if (discount) {
|
|
3192
|
+
writes.push({
|
|
3193
|
+
collection: "redemption",
|
|
3194
|
+
data: {
|
|
3195
|
+
advertisement: advertisementId,
|
|
3196
|
+
affiliate: affiliateId,
|
|
3197
|
+
campaign: orderCampaign,
|
|
3198
|
+
code: ((_e = matchedDiscounts[0]) == null ? void 0 : _e.code) || null,
|
|
3199
|
+
currency: currencyCode,
|
|
3200
|
+
customer,
|
|
3201
|
+
discount,
|
|
3202
|
+
gross,
|
|
3203
|
+
lead: leadId,
|
|
3204
|
+
order: orderDocId,
|
|
3205
|
+
organization: campaignOrganization,
|
|
3206
|
+
page: pageId,
|
|
3207
|
+
provider: { id: String(orderId), slug: "shopify" },
|
|
3208
|
+
purchasedAt,
|
|
3209
|
+
source,
|
|
3210
|
+
status: "completed"
|
|
3211
|
+
},
|
|
3212
|
+
operation: "create"
|
|
3213
|
+
});
|
|
3214
|
+
if (org == null ? void 0 : org.usage) {
|
|
3215
|
+
writes.push({
|
|
3216
|
+
collection: "usage",
|
|
3217
|
+
data: { $inc: { "totals.redemptions": 1 } },
|
|
3218
|
+
operation: "update",
|
|
3219
|
+
query: { id: org.usage }
|
|
3220
|
+
});
|
|
3221
|
+
}
|
|
3222
|
+
if (leadId) {
|
|
3223
|
+
writes.push({
|
|
3224
|
+
collection: "lead",
|
|
3225
|
+
data: { $inc: { "totals.redemptions": 1 } },
|
|
3226
|
+
operation: "update",
|
|
3227
|
+
options: { bypassDocumentValidation: true },
|
|
3228
|
+
query: { id: leadId }
|
|
3229
|
+
});
|
|
3230
|
+
}
|
|
3231
|
+
}
|
|
3232
|
+
const enqueues = (org == null ? void 0 : org.billingProvider) === "shopify" && fee > 0 && ((_f = connection2 == null ? void 0 : connection2.source) == null ? void 0 : _f.id) && !backfill ? [{
|
|
3233
|
+
data: {
|
|
3234
|
+
idempotencyKey: String(orderId),
|
|
3235
|
+
orderDocId,
|
|
3236
|
+
orderId: String(orderId),
|
|
3237
|
+
rate,
|
|
3238
|
+
shopId: connection2.source.id,
|
|
3239
|
+
// The App Events API returns no event id, so one is generated
|
|
3240
|
+
// here — the event handle plus the order id — and sent as the
|
|
3241
|
+
// event's `reference`. queue/usage.js stamps the same id onto
|
|
3242
|
+
// the order as billed.transaction.
|
|
3243
|
+
transaction: "drawbridge-orders." + orderId,
|
|
3244
|
+
value: Math.round(fee * 100)
|
|
3245
|
+
},
|
|
3246
|
+
name: "billing",
|
|
3247
|
+
options: { jobId: "shopify.usage." + orderId },
|
|
3248
|
+
queue: "usage"
|
|
3249
|
+
}] : [];
|
|
3250
|
+
return {
|
|
3251
|
+
enqueues,
|
|
3252
|
+
message: backfill ? "Redemption backfilled for an already-recorded order." : isConversion ? "Order recorded." : "Discount redemption recorded (fee-free).",
|
|
3253
|
+
request: request2,
|
|
3254
|
+
response: {
|
|
3255
|
+
campaign: orderCampaign,
|
|
3256
|
+
currency: currencyCode,
|
|
3257
|
+
discount,
|
|
3258
|
+
fee,
|
|
3259
|
+
gross,
|
|
3260
|
+
lead: leadId,
|
|
3261
|
+
lines: lines.length,
|
|
3262
|
+
net: net2,
|
|
3263
|
+
orderId: String(orderId)
|
|
3264
|
+
},
|
|
3265
|
+
// ONE TRANSACTION. The order, the redemption and both totals
|
|
3266
|
+
// counters land together or not at all — a half-written attribution
|
|
3267
|
+
// is revenue counted twice or not at all, and neither is
|
|
3268
|
+
// recoverable by hand.
|
|
3269
|
+
transaction: writes.length > 0,
|
|
3270
|
+
writes
|
|
3271
|
+
};
|
|
3272
|
+
},
|
|
3273
|
+
// A PRODUCT CHANGED AT THE STORE. Upserts the product row and hands it to
|
|
3274
|
+
// the product pipeline; the actual field sync happens there.
|
|
3275
|
+
//
|
|
3276
|
+
// The shell has already refused a missing or inactive Shopify connection,
|
|
3277
|
+
// so what is left is the two things only this hook can know are wrong.
|
|
3278
|
+
product: async ({ connection: connection2, context, workflow }, { mintId } = {}) => {
|
|
3279
|
+
const request2 = {
|
|
3280
|
+
numericId: (context == null ? void 0 : context.id) || null,
|
|
3281
|
+
organizationId: workflow.organization,
|
|
3282
|
+
title: (context == null ? void 0 : context.title) || null
|
|
3283
|
+
};
|
|
3284
|
+
if (!(context == null ? void 0 : context.id)) return { message: "Skipped \u2014 product webhook payload had no id.", request: request2, response: { skipped: true }, skipped: true };
|
|
3285
|
+
if (!connection2.shop) return { message: "Skipped \u2014 Shopify connection is missing shop domain.", request: request2, response: { skipped: true }, skipped: true };
|
|
3286
|
+
const providerId = "gid://shopify/Product/" + context.id;
|
|
3287
|
+
const productId = mintId();
|
|
3288
|
+
return {
|
|
3289
|
+
enqueues: [{
|
|
3290
|
+
data: { product: productId, providerId, shop: connection2.shop },
|
|
3291
|
+
name: "workflow",
|
|
3292
|
+
options: { jobId: "product.workflow.shopify." + providerId + "." + Date.now() },
|
|
3293
|
+
queue: "product.shopify"
|
|
3294
|
+
}],
|
|
3295
|
+
message: "Product sync queued from Shopify webhook.",
|
|
3296
|
+
request: request2,
|
|
3297
|
+
response: { productId, providerId, title: (context == null ? void 0 : context.title) || null },
|
|
3298
|
+
// KEYED ON PROVIDER + SHOP, so the same product in two stores stays
|
|
3299
|
+
// two rows. `connections` accumulates rather than replaces: one
|
|
3300
|
+
// store can be linked to several organizations, and each keeps its
|
|
3301
|
+
// own claim on the row.
|
|
3302
|
+
writes: [{
|
|
3303
|
+
collection: "product",
|
|
3304
|
+
data: {
|
|
3305
|
+
$addToSet: { connections: connection2.id },
|
|
3306
|
+
$setOnInsert: {
|
|
3307
|
+
id: productId,
|
|
3308
|
+
provider: { id: providerId, slug: "shopify" },
|
|
3309
|
+
"source.id": connection2.id,
|
|
3310
|
+
status: "active"
|
|
3311
|
+
}
|
|
3312
|
+
},
|
|
3313
|
+
operation: "update",
|
|
3314
|
+
options: { upsert: true },
|
|
3315
|
+
query: {
|
|
3316
|
+
"provider.id": providerId,
|
|
3317
|
+
"provider.slug": "shopify",
|
|
3318
|
+
"source.domain": connection2.shop
|
|
3319
|
+
}
|
|
3320
|
+
}]
|
|
3321
|
+
};
|
|
3322
|
+
}
|
|
2372
3323
|
},
|
|
2373
3324
|
contacts: { remove: false, sync: false },
|
|
2374
3325
|
// verify and event lean entirely on the shared HMAC helper — Shopify's
|
|
@@ -2386,7 +3337,16 @@ var shopify_default2 = {
|
|
|
2386
3337
|
sms: false,
|
|
2387
3338
|
inbound: {
|
|
2388
3339
|
event: (args) => readEventHeader({ ...args, descriptor: inbound }),
|
|
2389
|
-
|
|
3340
|
+
// One hook over the whole topic table, because that is what this
|
|
3341
|
+
// manifest declares: Shopify processes its own buffered events. The
|
|
3342
|
+
// topic rides in on the context rather than being a second hook name per
|
|
3343
|
+
// topic; the caller's handler table arrives as a prop.
|
|
3344
|
+
process: async ({ context }, { dispatch } = {}) => {
|
|
3345
|
+
const key = "shopify." + (context == null ? void 0 : context.topic);
|
|
3346
|
+
const handled = await dispatch({ data: context == null ? void 0 : context.data, handler: key });
|
|
3347
|
+
if (!handled) return { message: "No handler for " + key, skipped: true };
|
|
3348
|
+
return { message: "Processed " + key, request: { topic: context == null ? void 0 : context.topic } };
|
|
3349
|
+
},
|
|
2390
3350
|
receive: ({ channel, event, headers, payload }) => {
|
|
2391
3351
|
if (channel === "compliance" && !COMPLIANCE_TOPICS.has(event)) {
|
|
2392
3352
|
throw Object.assign(new Error("Unrecognized compliance topic: " + event), { status: 401 });
|
|
@@ -2402,7 +3362,107 @@ var shopify_default2 = {
|
|
|
2402
3362
|
},
|
|
2403
3363
|
verify: (args) => verifySignature({ ...args, descriptor: inbound })
|
|
2404
3364
|
},
|
|
2405
|
-
lifecycle: {
|
|
3365
|
+
lifecycle: {
|
|
3366
|
+
// DISPATCHES INTO THE CALLER'S OWN COORDINATORS. These three are
|
|
3367
|
+
// declarations made true: the work is queue orchestration over
|
|
3368
|
+
// Drawbridge's own collections, which is coordinator work and stays in
|
|
3369
|
+
// the repo that owns the queues. The hook receives the dispatch table as
|
|
3370
|
+
// a prop and picks the entry, so the manifest owns the SEAM — asking
|
|
3371
|
+
// Shopify whether it handles its own lifecycle now gets a real function
|
|
3372
|
+
// instead of `unimplemented` while the work happened anyway.
|
|
3373
|
+
cleanup: async ({ context }, { dispatch } = {}) => {
|
|
3374
|
+
await dispatch({ data: context, handler: "cleanup" });
|
|
3375
|
+
return { message: "Ran shopify lifecycle.cleanup", request: context || null };
|
|
3376
|
+
},
|
|
3377
|
+
// KEEP STORE ACCESS WORKING. Not a webhook monitor, despite the name the
|
|
3378
|
+
// step once carried — webhooks are declarative, declared in the app's
|
|
3379
|
+
// toml and applied by Shopify to every install, so nothing here registers
|
|
3380
|
+
// or checks them.
|
|
3381
|
+
//
|
|
3382
|
+
// It rotates the refresh token before its window closes, proves the
|
|
3383
|
+
// access token still works, reconciles the scopes the store granted
|
|
3384
|
+
// against the ones the app now needs, and queues a webhook
|
|
3385
|
+
// reconciliation.
|
|
3386
|
+
health: async ({ connection: connection2, workflow }, { adminToken, read, reconcileScopes, resolveSettings, rotateToken, shopify } = {}) => {
|
|
3387
|
+
const request2 = {
|
|
3388
|
+
connectionId: workflow.connection,
|
|
3389
|
+
organizationId: workflow.organization,
|
|
3390
|
+
shop: connection2.shop
|
|
3391
|
+
};
|
|
3392
|
+
const refreshTokenAtStart = (await resolveSettings()).refreshToken || null;
|
|
3393
|
+
try {
|
|
3394
|
+
const adminAccessToken = await adminToken();
|
|
3395
|
+
const settings = await resolveSettings();
|
|
3396
|
+
const refreshTokenExpiresAt = settings.refreshTokenExpiresAt;
|
|
3397
|
+
const needsRotation = refreshTokenExpiresAt && new Date(refreshTokenExpiresAt) < new Date(Date.now() + REFRESH_TOKEN_FRESHNESS_BUFFER_MS);
|
|
3398
|
+
let refreshTokenRotated = false;
|
|
3399
|
+
if (needsRotation) {
|
|
3400
|
+
await rotateToken();
|
|
3401
|
+
refreshTokenRotated = true;
|
|
3402
|
+
}
|
|
3403
|
+
await shopify.oauth.ping({ adminAccessToken, domain: connection2.shop });
|
|
3404
|
+
const scopesMissing = await reconcileScopes({ shop: connection2.shop });
|
|
3405
|
+
return {
|
|
3406
|
+
enqueues: [{
|
|
3407
|
+
data: {
|
|
3408
|
+
data: {
|
|
3409
|
+
connectionId: workflow.connection,
|
|
3410
|
+
organizationId: workflow.organization
|
|
3411
|
+
},
|
|
3412
|
+
event: "shopify.register.webhooks"
|
|
3413
|
+
},
|
|
3414
|
+
name: "register",
|
|
3415
|
+
options: { jobId: "connection.update.register." + workflow.connection + "." + randomUUID() },
|
|
3416
|
+
queue: "connection"
|
|
3417
|
+
}],
|
|
3418
|
+
message: (scopesMissing == null ? void 0 : scopesMissing.length) ? "Health check: ping ok, webhooks reconciled \u2014 connection errored, granted scopes are missing: " + scopesMissing.join(", ") + "." : refreshTokenRotated ? "Health check passed \u2014 refresh token rotated, ping ok, webhooks reconciled." : "Health check passed \u2014 ping ok, webhooks reconciled.",
|
|
3419
|
+
request: request2,
|
|
3420
|
+
response: {
|
|
3421
|
+
pingedAt: /* @__PURE__ */ new Date(),
|
|
3422
|
+
refreshTokenExpiresAt: refreshTokenExpiresAt || null,
|
|
3423
|
+
refreshTokenRotated,
|
|
3424
|
+
scopesMissing,
|
|
3425
|
+
webhookReconciliationQueued: true
|
|
3426
|
+
}
|
|
3427
|
+
};
|
|
3428
|
+
} catch (error) {
|
|
3429
|
+
if (OAUTH_GRANT_REVOKED_CODES.includes(error.code)) {
|
|
3430
|
+
const current = await read.get({ collection: "connection", query: { id: connection2.id } });
|
|
3431
|
+
const refreshTokenStored = current ? (await resolveSettings(current)).refreshToken || null : null;
|
|
3432
|
+
const rotated = error.code === "invalid_grant" && refreshTokenStored !== refreshTokenAtStart;
|
|
3433
|
+
if (current && !rotated) {
|
|
3434
|
+
const others = (current.errors || []).filter((entry) => entry.source !== OAUTH_ERROR_SOURCE);
|
|
3435
|
+
error.writes = [{
|
|
3436
|
+
collection: "connection",
|
|
3437
|
+
data: {
|
|
3438
|
+
$set: {
|
|
3439
|
+
errors: [
|
|
3440
|
+
...others,
|
|
3441
|
+
{
|
|
3442
|
+
message: "Shopify disconnected this store. Open the Drawbridge app in your Shopify admin to reconnect.",
|
|
3443
|
+
source: OAUTH_ERROR_SOURCE
|
|
3444
|
+
}
|
|
3445
|
+
],
|
|
3446
|
+
status: "error"
|
|
3447
|
+
}
|
|
3448
|
+
},
|
|
3449
|
+
operation: "update",
|
|
3450
|
+
query: { id: connection2.id }
|
|
3451
|
+
}];
|
|
3452
|
+
}
|
|
3453
|
+
}
|
|
3454
|
+
throw error;
|
|
3455
|
+
}
|
|
3456
|
+
},
|
|
3457
|
+
register: async ({ context }, { dispatch } = {}) => {
|
|
3458
|
+
await dispatch({ data: context, handler: "register" });
|
|
3459
|
+
return { message: "Ran shopify lifecycle.register", request: context || null };
|
|
3460
|
+
},
|
|
3461
|
+
rehydrate: async ({ context }, { dispatch } = {}) => {
|
|
3462
|
+
await dispatch({ data: context, handler: "rehydrate" });
|
|
3463
|
+
return { message: "Ran shopify lifecycle.rehydrate", request: context || null };
|
|
3464
|
+
}
|
|
3465
|
+
},
|
|
2406
3466
|
resources: {
|
|
2407
3467
|
audiences: false,
|
|
2408
3468
|
// Shopify has no separate price resource — a price belongs to a product
|
|
@@ -2422,7 +3482,7 @@ var shopify_default2 = {
|
|
|
2422
3482
|
// credential is the caller's job because it is Drawbridge's job: the
|
|
2423
3483
|
// admin token refreshes and writes itself back, which is service work,
|
|
2424
3484
|
// not vendor work.
|
|
2425
|
-
products: async ({ cursor, limit = 100, search, settings,
|
|
3485
|
+
products: async ({ cursor, limit = 100, search, settings, sort }, { shopify } = {}) => {
|
|
2426
3486
|
var _a, _b, _c, _d;
|
|
2427
3487
|
const products = await shopify.storefront.getProducts({
|
|
2428
3488
|
cursor,
|
|
@@ -2442,7 +3502,7 @@ var shopify_default2 = {
|
|
|
2442
3502
|
}
|
|
2443
3503
|
};
|
|
2444
3504
|
},
|
|
2445
|
-
promotions: async ({ cursor, limit = 100, search, settings, shopify }) => {
|
|
3505
|
+
promotions: async ({ cursor, limit = 100, search, settings }, { shopify } = {}) => {
|
|
2446
3506
|
var _a, _b;
|
|
2447
3507
|
const discounts = await shopify.admin.getDiscounts({
|
|
2448
3508
|
adminAccessToken: settings == null ? void 0 : settings.adminAccessToken,
|
|
@@ -2521,9 +3581,6 @@ var shopify_default2 = {
|
|
|
2521
3581
|
// workflow document, and those strings cannot be renamed without a backfill.
|
|
2522
3582
|
//
|
|
2523
3583
|
// EVERY LEAF IS A FUNCTION so a step can read the merchant's own connection.
|
|
2524
|
-
// The bodies these point at still live in drawbridge-sync; moving them is the
|
|
2525
|
-
// next unit, and commerce.order.record is the one that decides whether the
|
|
2526
|
-
// shape holds — 569 lines and 15 controller calls.
|
|
2527
3584
|
steps: {
|
|
2528
3585
|
commerce: {
|
|
2529
3586
|
code: {
|
|
@@ -2628,7 +3685,7 @@ var shopify_default2 = {
|
|
|
2628
3685
|
title: "Shopify"
|
|
2629
3686
|
};
|
|
2630
3687
|
|
|
2631
|
-
// lib/connections/webhook.js
|
|
3688
|
+
// lib/connections/providers/webhook.js
|
|
2632
3689
|
import crypto from "crypto";
|
|
2633
3690
|
|
|
2634
3691
|
// lib/safe-http.js
|
|
@@ -2766,7 +3823,7 @@ var safeRequest = async ({
|
|
|
2766
3823
|
}
|
|
2767
3824
|
};
|
|
2768
3825
|
|
|
2769
|
-
// lib/connections/webhook.js
|
|
3826
|
+
// lib/connections/providers/webhook.js
|
|
2770
3827
|
var webhook_default = {
|
|
2771
3828
|
// Connecting GENERATES the secret rather than storing one the merchant typed,
|
|
2772
3829
|
// so the buttons say what actually happens.
|
|
@@ -2853,11 +3910,10 @@ var webhook_default = {
|
|
|
2853
3910
|
// That is the rule the whole split runs on: a hook lives in sync only if it
|
|
2854
3911
|
// needs Drawbridge's own database, sockets or queues. This one does not.
|
|
2855
3912
|
webhook: {
|
|
2856
|
-
send: async ({ context,
|
|
3913
|
+
send: async ({ context, lead, settings, step }, { request: send2 = safeRequest } = {}) => {
|
|
2857
3914
|
const { headers = {}, method = "POST", url } = step.settings || {};
|
|
2858
3915
|
const request2 = { method, url: url || null };
|
|
2859
3916
|
if (!url) return { message: "Outgoing webhook URL is not configured for this step.", request: request2, response: { skipped: true }, skipped: true };
|
|
2860
|
-
const lead = (context == null ? void 0 : context.lead) ? await controller.get({ collection: "lead", query: { id: context.lead } }) : null;
|
|
2861
3917
|
const body = lead || context;
|
|
2862
3918
|
request2.body = body;
|
|
2863
3919
|
const outgoing = { ...headers };
|
|
@@ -3214,19 +4270,24 @@ var isLive = (slug, settings) => {
|
|
|
3214
4270
|
};
|
|
3215
4271
|
var mask = (value) => {
|
|
3216
4272
|
if (!value) return null;
|
|
3217
|
-
if (String(value).length <
|
|
4273
|
+
if (String(value).length < 16) return "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";
|
|
3218
4274
|
return String(value).slice(0, 3) + "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022" + String(value).slice(-4);
|
|
3219
4275
|
};
|
|
3220
|
-
var
|
|
3221
|
-
var
|
|
3222
|
-
|
|
4276
|
+
var providerMemo = /* @__PURE__ */ new Map();
|
|
4277
|
+
var MEMO_TTL_MS = 60 * 1e3;
|
|
4278
|
+
var clearProviderMemo = () => providerMemo.clear();
|
|
4279
|
+
var providerSettings = async ({ controller, slug }) => {
|
|
4280
|
+
const memoized = providerMemo.get(slug);
|
|
4281
|
+
if (memoized && Date.now() - memoized.at < MEMO_TTL_MS) return memoized.value;
|
|
4282
|
+
const row = await controller.get({
|
|
3223
4283
|
collection: "provider",
|
|
3224
4284
|
query: { slug }
|
|
3225
4285
|
});
|
|
3226
|
-
const
|
|
3227
|
-
|
|
4286
|
+
const value = (row == null ? void 0 : row.settings) ? decrypt(row.settings) : {};
|
|
4287
|
+
providerMemo.set(slug, { at: Date.now(), value });
|
|
4288
|
+
return value;
|
|
3228
4289
|
};
|
|
3229
|
-
var saveProviderSettings = async ({ authenticated,
|
|
4290
|
+
var saveProviderSettings = async ({ authenticated, clear, controller, settings, slug }) => {
|
|
3230
4291
|
const fields2 = providerFields(slug);
|
|
3231
4292
|
if (!fields2.length) return null;
|
|
3232
4293
|
const existing = await controller.get({
|
|
@@ -3254,37 +4315,35 @@ var saveProviderSettings = async ({ authenticated, cache, clear, controller, set
|
|
|
3254
4315
|
},
|
|
3255
4316
|
query: { slug }
|
|
3256
4317
|
});
|
|
3257
|
-
|
|
4318
|
+
providerMemo.delete(slug);
|
|
3258
4319
|
return result;
|
|
3259
4320
|
};
|
|
3260
4321
|
var providerEnvNames = () => new Set(
|
|
3261
4322
|
providerSlugs().flatMap((slug) => providerFields(slug)).map((field2) => field2.env).filter(Boolean)
|
|
3262
4323
|
);
|
|
3263
|
-
var providerCredentials = async ({
|
|
4324
|
+
var providerCredentials = async ({ controller }) => {
|
|
3264
4325
|
const credentials2 = {};
|
|
3265
4326
|
for (const slug of providerSlugs()) {
|
|
3266
|
-
|
|
3267
|
-
|
|
3268
|
-
const
|
|
3269
|
-
|
|
4327
|
+
try {
|
|
4328
|
+
const settings = await providerSettings({ controller, slug });
|
|
4329
|
+
for (const field2 of providerFields(slug)) {
|
|
4330
|
+
const value = settings == null ? void 0 : settings[field2.key];
|
|
4331
|
+
if (field2.env && value) credentials2[field2.env] = value;
|
|
4332
|
+
}
|
|
4333
|
+
} catch {
|
|
4334
|
+
continue;
|
|
3270
4335
|
}
|
|
3271
4336
|
}
|
|
3272
4337
|
return credentials2;
|
|
3273
4338
|
};
|
|
3274
|
-
var hydrateEnvironment = async ({ cache, controller, env = process.env }) => {
|
|
3275
|
-
const credentials2 = await providerCredentials({ cache, controller });
|
|
3276
|
-
for (const name of providerEnvNames()) delete env[name];
|
|
3277
|
-
Object.assign(env, credentials2);
|
|
3278
|
-
return Object.keys(credentials2).sort();
|
|
3279
|
-
};
|
|
3280
4339
|
export {
|
|
3281
|
-
|
|
3282
|
-
hydrateEnvironment,
|
|
4340
|
+
clearProviderMemo,
|
|
3283
4341
|
isLive,
|
|
3284
4342
|
mask,
|
|
3285
4343
|
providerCredentials,
|
|
3286
4344
|
providerEnvNames,
|
|
3287
4345
|
providerFields,
|
|
4346
|
+
providerMemo,
|
|
3288
4347
|
providerSettings,
|
|
3289
4348
|
providerSlugs,
|
|
3290
4349
|
saveProviderSettings
|