@drawbridge/drawbridge-utils 0.0.118 → 0.0.124

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/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,56 @@ 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/phone.js
408
+ import { AsYouType, parsePhoneNumberFromString, isValidPhoneNumber } from "libphonenumber-js";
409
+ var toE164 = (value, country) => {
410
+ if (!value) return null;
411
+ try {
412
+ const parsed = parsePhoneNumberFromString(String(value), country);
413
+ return parsed ? parsed.number : null;
414
+ } catch {
415
+ return null;
416
+ }
417
+ };
418
+ var detectCountry = (value) => {
419
+ if (!value) return null;
420
+ try {
421
+ const parser = new AsYouType();
422
+ parser.input(String(value));
423
+ return parser.getCountry() || null;
424
+ } catch {
425
+ return null;
426
+ }
427
+ };
428
+
429
+ // lib/connections/providers/attentive.js
430
+ var api = async (path, { fetcher = fetch, method = "GET", payload, token }) => {
431
+ const response = await fetcher("https://api.attentivemobile.com" + path, {
432
+ ...payload && { body: JSON.stringify(payload) },
433
+ headers: {
434
+ authorization: "Bearer " + token,
435
+ ...payload && { "content-type": "application/json" }
436
+ },
437
+ method,
438
+ signal: AbortSignal.timeout(15e3)
439
+ });
440
+ if (!response.ok) {
441
+ throw Object.assign(
442
+ new Error("Attentive refused the request (" + response.status + ")"),
443
+ { status: response.status }
444
+ );
445
+ }
446
+ return response.json().catch(() => null);
447
+ };
361
448
  var attentive_default2 = {
362
449
  auth: {
363
450
  oauth: {
364
- // NAMES of the env vars holding OUR app's client — set at registration,
365
- // never before. No `headers` on the client: Attentive takes credentials
366
- // as form fields, which is the runner's default.
451
+ // NAMES of the credentials holding OUR app's client — keys into the map
452
+ // the provider collection answers, entered on the admin screen at
453
+ // registration, never before. (The names are the env vars they once
454
+ // were; the vocabulary stayed when the storage moved.) No `headers` on
455
+ // the client: Attentive takes credentials as form fields, which is the
456
+ // runner's default.
367
457
  client: {
368
458
  id: "ATTENTIVE_OAUTH_CLIENT_ID",
369
459
  secret: "ATTENTIVE_OAUTH_CLIENT_SECRET"
@@ -388,9 +478,10 @@ var attentive_default2 = {
388
478
  // has to say so rather than let them believe otherwise.
389
479
  confirm: "Disconnecting removes Drawbridge's stored Attentive token. Attentive does not offer a way for us to revoke it, so remove the Drawbridge integration in Attentive as well if you want its access fully withdrawn. Your subscribers stay in both Attentive and Drawbridge \u2014 neither list is deleted.",
390
480
  description: [
391
- "Attentive is where your SMS marketing lives, and this connection is becoming the way your Drawbridge contacts sync into an Attentive segment.",
481
+ "Attentive is where your SMS marketing lives, and this connection syncs the contacts your campaigns collect into an Attentive segment \u2014 subscribed for marketing and added to the segment you choose.",
392
482
  "You authorize Drawbridge from inside Attentive and can revoke that access there at any time. Drawbridge never sees or stores your Attentive password.",
393
- "Subscriber syncing is not live yet, so connecting today does nothing except choose the segment it will use when it ships."
483
+ "Anyone who has opted out in Drawbridge is sent to Attentive as an unsubscribe rather than omitted, so a person who asked not to be contacted stays suppressed in both systems instead of quietly reappearing.",
484
+ "Attentive accepts these updates and applies them in the background, so a contact appears in your segment shortly after the sync rather than the instant it runs."
394
485
  ],
395
486
  excerpt: "Sync your Drawbridge contacts into an Attentive segment.",
396
487
  guide: [
@@ -411,6 +502,10 @@ var attentive_default2 = {
411
502
  message: "Contacts your campaigns collect are synced into this segment.",
412
503
  hook: "resources.audiences",
413
504
  required: true
505
+ // CONSUMED BY THE MEMBERSHIP CALL, not by the subscribe. Attentive's
506
+ // /v1/subscriptions takes no segment id — subscription and segment
507
+ // membership are two operations here — so contacts.sync makes both calls
508
+ // and this value is the externalId the second one carries.
414
509
  // No `search : false` here, and that is a first: /v2/segments takes a
415
510
  // `name` filter (partial match, cited above), so this picker searches
416
511
  // the ACCOUNT — Klaviyo and Mailchimp can only match the fetched page.
@@ -423,17 +518,25 @@ var attentive_default2 = {
423
518
  // and contacts.sync are the first to flip.
424
519
  hooks: {
425
520
  auth: {
426
- // The exchange already yields the tokens, and Attentive documents no
427
- // account-identity endpoint to enrich them with — Klaviyo's connect
428
- // reads the account name back; this has nothing cited to read. The
429
- // callback stores the tokens and skips enrichment on `unimplemented`.
430
521
  // FALSE, NOT {}. `{}` means "supported, implemented in the repo with the
431
- // dependencies", and nothing anywhere implements either of these —
432
- // there is nothing for them to do. The exchange already yields the
433
- // tokens and Attentive documents no account-identity endpoint to
434
- // enrich them with, so connect has nothing to add; and they document
435
- // no revocation endpoint at all, so disconnect has nothing to call.
436
- // Recorded as a decision rather than left as an unkept promise.
522
+ // dependencies", and nothing anywhere implements either of these — there
523
+ // is nothing for them to do. They document no revocation endpoint at all,
524
+ // so disconnect has nothing to call. Recorded as a decision rather than
525
+ // left as an unkept promise.
526
+ //
527
+ // STILL FALSE AFTER LOOKING AGAIN, and this is the reason written down so
528
+ // nobody re-derives it. Klaviyo's connect reads the account name back so
529
+ // the card is not blank; Attentive's card stays blank. There IS an
530
+ // endpoint — GET https://api.attentivemobile.com/v1/me, Bearer, described
531
+ // on docs.attentive.com/pages/authentication/ as returning "information
532
+ // specific to your company" — but its RESPONSE SCHEMA is published
533
+ // nowhere we can read: the docs show the curl and no body. Reading
534
+ // `body.name` would be a guess, and a guess here fails at the worst
535
+ // moment, in the callback, after the merchant has already consented.
536
+ //
537
+ // A live token settles it in one call, alongside the three registration
538
+ // checks in the header. Until then the honest state is a blank field, not
539
+ // a hopeful one.
437
540
  connect: false,
438
541
  disconnect: false,
439
542
  probe: false,
@@ -455,7 +558,112 @@ var attentive_default2 = {
455
558
  }
456
559
  },
457
560
  commerce: false,
458
- contacts: { remove: false, sync: false },
561
+ // The verb the contacts.sync step points at.
562
+ contacts: {
563
+ // Not yet. Suppression syncs an opt-out as unsubscribed, which is a
564
+ // different thing from erasing the subscriber — Attentive's deletion sits
565
+ // behind their privacy-request API, which is a different grant.
566
+ remove: false,
567
+ // TWO CALLS, BECAUSE ATTENTIVE HAS TWO IDEAS.
568
+ //
569
+ // Subscribing and being in a segment are NOT the same operation here —
570
+ // unlike Klaviyo, where a subscription is created against the list itself.
571
+ // /v1/subscriptions takes no segment id at all, so the segment a merchant
572
+ // picked on this connection can only be honoured by the bulk segment
573
+ // membership API:
574
+ //
575
+ // subscribe POST /v1/subscriptions
576
+ // { user : { email, phone }, locale, subscriptionType } — the
577
+ // docs require EITHER signUpSourceId OR (locale +
578
+ // subscriptionType), and we hold no sign-up source. 202.
579
+ //
580
+ // membership POST /v2/bulk/segments/members
581
+ // { externalId, members : [ { email, phone } ] }, 1-10,000
582
+ // members, 202 with a batchJobId
583
+ // (docs.attentive.com/reference/postbulksegmentmembers).
584
+ //
585
+ // unsubscribe POST /v1/subscriptions/unsubscribe
586
+ // { user, subscriptions : [ { type, channel } ] }. 202.
587
+ //
588
+ // EVERY ONE OF THEM ANSWERS 202 ACCEPTED, which means Attentive took the
589
+ // job, not that it ran — the same distinction the Shopify usage charge
590
+ // makes between a 202 and a charge. The message below says accepted, and
591
+ // must keep saying accepted.
592
+ sync: async ({ lead, settings, suppressed, token }, { fetcher } = {}) => {
593
+ var _a, _b, _c, _d;
594
+ const segment = settings == null ? void 0 : settings.segment;
595
+ if (!segment) return { message: "No Attentive segment is chosen for this connection.", skipped: true };
596
+ const email = ((_b = (_a = lead == null ? void 0 : lead.canonical) == null ? void 0 : _a.email) == null ? void 0 : _b.value) || (lead == null ? void 0 : lead.email);
597
+ const phone = toE164(((_d = (_c = lead == null ? void 0 : lead.canonical) == null ? void 0 : _c.phone) == null ? void 0 : _d.value) || (lead == null ? void 0 : lead.phone));
598
+ if (!email && !phone) return { message: "That lead has no email address or phone number to sync.", skipped: true };
599
+ const user = {
600
+ ...email && { email },
601
+ ...phone && { phone }
602
+ };
603
+ if (suppressed) {
604
+ await api("/v1/subscriptions/unsubscribe", {
605
+ fetcher,
606
+ method: "POST",
607
+ payload: {
608
+ // One entry per channel we can actually name them by. MARKETING
609
+ // is the only type Drawbridge ever subscribed them to.
610
+ subscriptions: [
611
+ ...phone ? [{ channel: "TEXT", type: "MARKETING" }] : [],
612
+ ...email ? [{ channel: "EMAIL", type: "MARKETING" }] : []
613
+ ],
614
+ user
615
+ },
616
+ token
617
+ });
618
+ return {
619
+ message: "Attentive accepted an unsubscribe for this contact \u2014 they have opted out.",
620
+ response: { accepted: true, unsubscribed: true }
621
+ };
622
+ }
623
+ await api("/v1/subscriptions", {
624
+ fetcher,
625
+ method: "POST",
626
+ payload: {
627
+ // LOCALE, because we hold no signUpSourceId and the docs require
628
+ // one or the other. The country is READ OFF the number when there
629
+ // is one — libphonenumber knows it from the calling code — rather
630
+ // than assumed; only the fallback pair below is a default, and it
631
+ // is the one value here that no vendor document dictates.
632
+ //
633
+ // ponytail: en/US default. A `signUpSourceId` field on the
634
+ // connection is the upgrade — Attentive's sign-up sources carry
635
+ // the consent language, which is a better answer than any locale
636
+ // we can infer — and it replaces this branch entirely.
637
+ locale: {
638
+ country: phone && detectCountry(phone) || "US",
639
+ language: "en"
640
+ },
641
+ subscriptionType: "MARKETING",
642
+ user
643
+ },
644
+ token
645
+ });
646
+ const membership = await api("/v2/bulk/segments/members", {
647
+ fetcher,
648
+ method: "POST",
649
+ payload: {
650
+ externalId: segment,
651
+ members: [user]
652
+ },
653
+ token
654
+ });
655
+ return {
656
+ // ACCEPTED, NOT LIVE. Both writes answered 202, which means Attentive
657
+ // queued them — a merchant who reads "synced" and looks for the person
658
+ // in Attentive a second later has been told the wrong thing.
659
+ message: "Attentive accepted this contact for the segment. Attentive processes these asynchronously, so it appears there shortly.",
660
+ response: {
661
+ accepted: true,
662
+ ...(membership == null ? void 0 : membership.batchJobId) && { batchJobId: membership.batchJobId }
663
+ }
664
+ };
665
+ }
666
+ },
459
667
  email: false,
460
668
  inbound: false,
461
669
  lifecycle: false,
@@ -468,26 +676,13 @@ var attentive_default2 = {
468
676
  // show a picker quietly missing most of a real account. The response's
469
677
  // only identifier is `externalId`, so an entry without one cannot be
470
678
  // stored and is dropped.
471
- audiences: async ({ cursor, fetcher = fetch, limit = 100, search, token }) => {
679
+ audiences: async ({ cursor, limit = 100, search, token }, { fetcher } = {}) => {
472
680
  const query = new URLSearchParams({
473
681
  limit: String(Math.min(limit, 1e3)),
474
682
  ...cursor && { cursor },
475
683
  ...(search == null ? void 0 : search.value) && { name: String(search.value).trim() }
476
684
  });
477
- const response = await fetcher(
478
- "https://api.attentivemobile.com/v2/segments?" + query,
479
- {
480
- headers: { authorization: "Bearer " + token },
481
- signal: AbortSignal.timeout(15e3)
482
- }
483
- );
484
- if (!response.ok) {
485
- throw Object.assign(
486
- new Error("Attentive refused the request (" + response.status + ")"),
487
- { status: response.status }
488
- );
489
- }
490
- const body = await response.json();
685
+ const body = await api("/v2/segments?" + query, { fetcher, token });
491
686
  return {
492
687
  items: ((body == null ? void 0 : body.segments) || []).filter((segment) => segment == null ? void 0 : segment.externalId).map((segment) => ({ id: segment.externalId, title: (segment == null ? void 0 : segment.name) || segment.externalId })),
493
688
  pageInfo: {
@@ -505,33 +700,67 @@ var attentive_default2 = {
505
700
  webhook: false
506
701
  },
507
702
  icon: attentive_default,
703
+ // DRAWBRIDGE'S OWN CREDENTIALS for this vendor, as opposed to a merchant's —
704
+ // what an admin types on the provider screen, and the only declaration of it.
705
+ // It lives beside `requires`, which names the same variables: the manifest
706
+ // says what it needs and this says how someone supplies it, so a credential
707
+ // cannot be required by a vendor that offers nowhere to enter it.
708
+ //
709
+ // `redact` marks a secret — never returned by the api, and blank on save means
710
+ // keep the stored value. `required` drives the live check.
711
+ provider: {
712
+ fields: [
713
+ { input: "text", key: "clientId", credential: "ATTENTIVE_OAUTH_CLIENT_ID", label: "Client ID", required: true },
714
+ { input: "password", key: "clientSecret", credential: "ATTENTIVE_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
715
+ ]
716
+ },
508
717
  requires: [
509
718
  "ATTENTIVE_OAUTH_CLIENT_ID",
510
719
  "ATTENTIVE_OAUTH_CLIENT_SECRET"
511
720
  ],
512
721
  slug: "attentive",
513
- // A consent with no segment chosen is authenticated and inert — the sync,
514
- // when it ships, needs somewhere to put people.
722
+ // A consent with no segment chosen is authenticated and inert — the sync needs
723
+ // somewhere to put people so the card says Pending rather than Active over
724
+ // nothing.
515
725
  status: (data2) => {
516
726
  var _a;
517
727
  return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.segment) ? data2.status : "pending";
518
728
  },
519
- // No steps: subscriber sync has not shipped, so this vendor contributes
520
- // nothing to a workflow yet. An empty steps object is the honest declaration.
521
- steps: {},
729
+ steps: {
730
+ contacts: {
731
+ // A DECLARATION, not the work. The nesting IS the name: this is
732
+ // `step.contacts.sync`, the string a workflow document stores. Klaviyo and
733
+ // Mailchimp declare the same type — a step belongs to the capability, not
734
+ // to whoever implements it — and the connection on the step document is
735
+ // what says which vendor runs.
736
+ sync: ({ data: data2 }) => ({
737
+ hook: "contacts.sync",
738
+ // NO ACCOUNT NAME TO INTERPOLATE, unlike Klaviyo: auth.connect is false
739
+ // because Attentive publishes no account-identity response we can read
740
+ // (see its comment), and settings.segment is an opaque externalId no
741
+ // merchant would recognise in a builder label.
742
+ key: "Sync contact to Attentive",
743
+ queue: "connection",
744
+ // Nothing for a merchant to configure on the step itself — the segment
745
+ // is chosen once on the connection. Declared empty rather than omitted,
746
+ // so "this step takes no settings" and "nobody thought about settings"
747
+ // stay different statements.
748
+ settings: {},
749
+ // BOTH triggers, for the same reason as Klaviyo: lead.insert alone only
750
+ // ever fires for someone with no history yet, and crossing into a
751
+ // segment is the other moment a contact is worth pushing.
752
+ triggers: ["lead.insert", "segment.contact.add"],
753
+ usage: { actions: 1 }
754
+ })
755
+ }
756
+ },
757
+ // WHY, in the merchant's words, and what to do about it.
522
758
  tasks: (data2) => {
523
759
  var _a;
524
- return [
525
- ...((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.segment) ? [] : [
526
- {
527
- message: "Choose which Attentive segment your contacts should sync into. Until you do, nothing is being synced.",
528
- title: "Choose a segment"
529
- }
530
- ],
760
+ return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.segment) ? [] : [
531
761
  {
532
- message: "Contact syncing to Attentive segments has not shipped yet. Nothing is being sent to Attentive right now.",
533
- title: "Subscriber sync not available yet",
534
- type: "warning"
762
+ message: "Choose which Attentive segment your contacts should sync into. Until you do, nothing is being synced.",
763
+ title: "Choose a segment"
535
764
  }
536
765
  ];
537
766
  },
@@ -584,10 +813,11 @@ var request = async ({
584
813
  // lib/hubspot.js
585
814
  var HUBSPOT_BASE = "https://api.hubapi.com";
586
815
  var hubspotRequest = ({ body, fetcher, method, path, query, token }) => {
816
+ if (!token) throw new Error("HubSpot access token missing \u2014 pass token (the drawbridge provider's hubspotToken)");
587
817
  return (fetcher || request)({
588
818
  body,
589
819
  headers: {
590
- "Authorization": "Bearer " + (token || process.env.HUBSPOT_ACCESS_TOKEN)
820
+ "Authorization": "Bearer " + token
591
821
  },
592
822
  method,
593
823
  query,
@@ -689,16 +919,15 @@ var contacts = {
689
919
  // FORGET A CONTACT, by id or by email. Account deletion — the caller had
690
920
  // to search then remove, which is one round trip it should not have to
691
921
  // know about.
692
- remove: async ({ email, fetcher, id, token }) => {
693
- const key = token || process.env.HUBSPOT_ACCESS_TOKEN;
694
- if (!key) return;
695
- const contact = id || await lookup({ email, fetcher, token: key });
922
+ remove: async ({ email, id, token }, { fetcher } = {}) => {
923
+ if (!token) return;
924
+ const contact = id || await lookup({ email, fetcher, token });
696
925
  if (!contact) return;
697
926
  return hubspotRequest({
698
927
  fetcher,
699
928
  method: "DELETE",
700
929
  path: "/crm/v3/objects/contacts/" + contact,
701
- token: key
930
+ token
702
931
  });
703
932
  },
704
933
  // Connect an account to its contact by email, creating it if absent, and
@@ -707,24 +936,23 @@ var contacts = {
707
936
  // no delete-old-then-create-new.
708
937
  //
709
938
  // Prefer the cached hubspotId; fall back to a search; create last.
710
- sync: async ({ doc, fetcher, token }) => {
939
+ sync: async ({ doc, token }, { fetcher } = {}) => {
711
940
  var _a, _b;
712
- const key = token || process.env.HUBSPOT_ACCESS_TOKEN;
713
- if (!key) return;
941
+ if (!token) return;
714
942
  if (doc == null ? void 0 : doc.hubspotId) {
715
943
  try {
716
- return (_a = await send({ doc, fetcher, method: "PATCH", path: "/crm/v3/objects/contacts/" + doc.hubspotId, token: key })) == null ? void 0 : _a.id;
944
+ return (_a = await send({ doc, fetcher, method: "PATCH", path: "/crm/v3/objects/contacts/" + doc.hubspotId, token })) == null ? void 0 : _a.id;
717
945
  } catch (error) {
718
946
  if ((error == null ? void 0 : error.status) !== 404) throw error;
719
947
  }
720
948
  }
721
- const existing = await lookup({ email: doc == null ? void 0 : doc.email, fetcher, token: key });
949
+ const existing = await lookup({ email: doc == null ? void 0 : doc.email, fetcher, token });
722
950
  return (_b = await send({
723
951
  doc,
724
952
  fetcher,
725
953
  method: existing ? "PATCH" : "POST",
726
954
  path: existing ? "/crm/v3/objects/contacts/" + existing : "/crm/v3/objects/contacts",
727
- token: key
955
+ token
728
956
  })) == null ? void 0 : _b.id;
729
957
  }
730
958
  };
@@ -734,7 +962,7 @@ var drawbridge_default = `<svg width="500" height="500" viewBox="0 0 500 500" fi
734
962
  <rect width="500" height="500" fill="#BAEC5F"/>
735
963
  <g clip-path="url(#clip0_2115_2832)">
736
964
  <path d="M140.224 127.586L174.803 188.73V311.176L140 372.32L176.084 392.031L216.111 321.753V178.278L176.341 108L140.224 127.586Z" fill="#0D1314"/>
737
- <path d="M360.001 127.523L323.693 108.282L284.948 178.498V321.596L322.923 391.749L359.393 372.79L326.224 311.52V188.73L360.001 127.523Z" fill="#0D1314"/>
965
+ <path d="M360.002 127.523L323.694 108.282L284.949 178.498V321.596L322.924 391.749L359.394 372.79L326.225 311.52V188.73L360.002 127.523Z" fill="#0D1314"/>
738
966
  </g>
739
967
  <defs>
740
968
  <clipPath id="clip0_2115_2832">
@@ -1180,6 +1408,36 @@ var plans = {
1180
1408
  conversion: 0.5
1181
1409
  }
1182
1410
  };
1411
+ var resolvePlan = (subscription) => {
1412
+ var _a, _b;
1413
+ const custom = subscription == null ? void 0 : subscription.custom;
1414
+ if (!custom) return plans[subscription == null ? void 0 : subscription.plan] ?? free;
1415
+ return {
1416
+ // Reusing all.features / all.limits is what keeps a custom plan the same
1417
+ // SHAPE as a catalog one: the base feature grants every plan carries, the
1418
+ // campaign limits that are always infinite, and members defaulting to
1419
+ // infinite when a deal does not name it.
1420
+ conversion: custom.conversion ?? free.conversion,
1421
+ custom: true,
1422
+ // A custom plan is a negotiated PAID deal, so it carries the paid-tier
1423
+ // baseline whether or not the deal thought to name it. Today that is the
1424
+ // sending domain: every catalog paid tier grants it, and a custom plan
1425
+ // silently lacking it would be a support ticket, not a pricing decision.
1426
+ features: all.features([organization.networking.key, ...((_a = custom.features) == null ? void 0 : _a.granted) || []]),
1427
+ limits: all.limits(((_b = custom.limits) == null ? void 0 : _b.organization) || {}),
1428
+ // A custom plan stores its overage BARE on `custom.overages` — a different
1429
+ // shape from the catalog's nested one. Number() so a deal stored as a string
1430
+ // still resolves to cents-per-action; an unnamed overage stays undefined
1431
+ // (it bills nothing) rather than becoming NaN.
1432
+ actionCents: custom.overages == null ? void 0 : Number(custom.overages),
1433
+ overages: { actions: custom.overages },
1434
+ title: custom.title || "Custom"
1435
+ };
1436
+ };
1437
+ var conversionRate = (subscription) => {
1438
+ var _a;
1439
+ return ((_a = resolvePlan(subscription)) == null ? void 0 : _a.conversion) ?? free.conversion;
1440
+ };
1183
1441
 
1184
1442
  // lib/transactions.js
1185
1443
  import { currentTraceId } from "@drawbridge/drawbridge-telemetry";
@@ -1334,7 +1592,36 @@ var channels = {
1334
1592
  }
1335
1593
  };
1336
1594
 
1337
- // lib/connections/drawbridge.js
1595
+ // lib/connections/providers/drawbridge.js
1596
+ var interpolate = (template, data2) => {
1597
+ if (!template) return template;
1598
+ return template.replace(/\{\{(\w+)\}\}/g, (_, key) => (data2 == null ? void 0 : data2[key]) != null ? String(data2[key]) : "{{" + key + "}}");
1599
+ };
1600
+ var teamRecipients = async ({ memberIds = [], organization: organization2, read }) => {
1601
+ const org = await read.get({ collection: "organization", query: { id: organization2 } });
1602
+ const owner = (org == null ? void 0 : org.owner) ? await read.get({ collection: "user", query: { id: org.owner } }) : null;
1603
+ const members = memberIds.length ? await read.aggregate({
1604
+ collection: "member",
1605
+ pipeline: [
1606
+ {
1607
+ $match: {
1608
+ id: { $in: memberIds },
1609
+ organization: organization2,
1610
+ status: "accepted"
1611
+ }
1612
+ }
1613
+ ]
1614
+ }) : [];
1615
+ const seen = /* @__PURE__ */ new Set();
1616
+ return [owner, ...members].filter((member) => {
1617
+ if (!(member == null ? void 0 : member.id) || !(member == null ? void 0 : member.email)) return false;
1618
+ const address = member.email.toLowerCase();
1619
+ if (seen.has(address)) return false;
1620
+ seen.add(address);
1621
+ return true;
1622
+ });
1623
+ };
1624
+ var queueNotification = (data2) => ({ collection: "notification", data: data2, operation: "create" });
1338
1625
  var drawbridge_default2 = {
1339
1626
  auth: {
1340
1627
  type: "none"
@@ -1352,10 +1639,15 @@ var drawbridge_default2 = {
1352
1639
  exclusive: false,
1353
1640
  fields: [],
1354
1641
  group: "developer",
1355
- // EVERY BODY LIVES IN drawbridge-sync. Sending needs the provider clients, the
1356
- // suppression collection and the queues; segment sync needs the streams. A
1357
- // published package carrying those makes every consumer carry them, which is
1358
- // the reason `{}` exists as an answer.
1642
+ // THE BODIES LIVE HERE, beside the declarations that name them. They used to
1643
+ // live in drawbridge-sync because they touch the database, the queues and the
1644
+ // sockets and a published package cannot carry a controller.
1645
+ //
1646
+ // It does not have to. A hook is a function, so everything it needs is PASSED
1647
+ // IN: `read` for the reads, `canSend` for the opt-out floor, `resolveContact`
1648
+ // for the one write whose RESULT the hook has to count. Everything else a hook
1649
+ // wants done it DESCRIBES — `writes`, `enqueues`, `events` — and the shell
1650
+ // performs it. See lib/connections/contract.js for that shape.
1359
1651
  hooks: {
1360
1652
  auth: {
1361
1653
  // Nothing to connect, revoke, probe or re-scope.
@@ -1376,13 +1668,157 @@ var drawbridge_default2 = {
1376
1668
  // accounts DRAWBRIDGE holds rather than ones a merchant connects.
1377
1669
  contacts,
1378
1670
  email: {
1379
- digest: {},
1380
- // To organization members. NEVER suppressed and never billed: an
1381
- // entrant's opt-out must not silence an alert to staff, and staff mail is
1382
- // not a metered send.
1383
- notify: {},
1384
- // To a lead. Suppression applies and the send is billed.
1385
- send: {}
1671
+ // A PERIODIC SUMMARY to the team, on a schedule trigger rather than per
1672
+ // lead.
1673
+ //
1674
+ // The count is the point: `email.notify` tells the owner one lead arrived
1675
+ // and dampens a spike to one message per bucket, which is deliberately not
1676
+ // a count. This is where "you got 43 entries this week" comes from.
1677
+ digest: async ({ context, step, workflow }, { read } = {}) => {
1678
+ var _a, _b, _c, _d;
1679
+ const days = { day: 1, month: 30, week: 7 }[(_a = workflow == null ? void 0 : workflow.trigger) == null ? void 0 : _a.event] || 7;
1680
+ const since = new Date(Date.now() - days * 24 * 60 * 60 * 1e3);
1681
+ const campaign = ((_c = (_b = workflow == null ? void 0 : workflow.trigger) == null ? void 0 : _b.filters) == null ? void 0 : _c.campaign) || null;
1682
+ const [counted] = await read.aggregate({
1683
+ collection: "lead",
1684
+ pipeline: [
1685
+ {
1686
+ $match: {
1687
+ createdAt: { $gte: since },
1688
+ organization: workflow.organization,
1689
+ ...campaign && { campaigns: { $in: [campaign] } }
1690
+ }
1691
+ },
1692
+ { $count: "count" }
1693
+ ]
1694
+ });
1695
+ const count = Number((counted == null ? void 0 : counted.count) || 0);
1696
+ const request2 = { campaign, count, days };
1697
+ if (!count) return { message: "No new leads in the period \u2014 digest skipped.", request: request2, response: { skipped: true }, skipped: true };
1698
+ const recipients = await teamRecipients({
1699
+ memberIds: ((_d = step.settings) == null ? void 0 : _d.members) || [],
1700
+ organization: workflow.organization,
1701
+ read
1702
+ });
1703
+ const values = { ...context, count };
1704
+ return {
1705
+ message: "Digest of " + count + " new lead(s) queued for " + recipients.length + " recipient(s).",
1706
+ request: request2,
1707
+ response: { count, notified: recipients.length },
1708
+ writes: recipients.map((member) => {
1709
+ var _a2, _b2;
1710
+ return queueNotification({
1711
+ audience: "member",
1712
+ message: interpolate((_a2 = step.settings) == null ? void 0 : _a2.message, values),
1713
+ organization: workflow.organization,
1714
+ send: { type: "email", email: member.email },
1715
+ title: interpolate((_b2 = step.settings) == null ? void 0 : _b2.subject, values),
1716
+ workflow: workflow.id
1717
+ });
1718
+ })
1719
+ };
1720
+ },
1721
+ // To the organization's OWN PEOPLE. Never suppressed, never
1722
+ // subscription-gated, no unsubscribe footer — telling an org's staff about
1723
+ // their own leads is not commercial mail to a stranger.
1724
+ //
1725
+ // FREE, permanently. The lead that triggered this run already consumed the
1726
+ // billable action, and `members` is a list — billing here would turn one
1727
+ // lead into five more charges and the org would be paying to read its own
1728
+ // mail. The declaration prices it at zero; the shell bills nothing for
1729
+ // zero.
1730
+ notify: async ({ context, step, workflow }, { read } = {}) => {
1731
+ var _a;
1732
+ const memberIds = ((_a = step.settings) == null ? void 0 : _a.members) || [];
1733
+ const request2 = { members: memberIds.length };
1734
+ const recipients = await teamRecipients({ memberIds, organization: workflow.organization, read });
1735
+ if (!recipients.length) {
1736
+ return {
1737
+ message: "No owner or accepted member with an email address \u2014 team notification skipped.",
1738
+ request: request2,
1739
+ response: { skipped: true },
1740
+ skipped: true
1741
+ };
1742
+ }
1743
+ const bucket = Math.floor(Date.now() / (15 * 60 * 1e3));
1744
+ return {
1745
+ message: "Team notification queued for " + recipients.length + " recipient(s).",
1746
+ request: request2,
1747
+ response: { notified: recipients.length },
1748
+ writes: recipients.map((member) => {
1749
+ var _a2, _b;
1750
+ return {
1751
+ ...queueNotification({
1752
+ audience: "member",
1753
+ // Per workflow, recipient AND bucket, so one recipient's damper
1754
+ // can never swallow another's mail and a later bucket is never
1755
+ // mistaken for a duplicate of an earlier one.
1756
+ key: "team.notify." + workflow.id + "." + member.id + "." + bucket,
1757
+ message: interpolate((_a2 = step.settings) == null ? void 0 : _a2.message, context),
1758
+ organization: workflow.organization,
1759
+ send: { type: "email", email: member.email },
1760
+ title: interpolate((_b = step.settings) == null ? void 0 : _b.subject, context),
1761
+ workflow: workflow.id
1762
+ }),
1763
+ // E11000 IS THE DAMPER WORKING: this recipient has already been
1764
+ // told within the bucket. Declared per write rather than assumed by
1765
+ // the shell, because on every other write here a duplicate key is a
1766
+ // real failure.
1767
+ ignoreDuplicate: true
1768
+ };
1769
+ })
1770
+ };
1771
+ },
1772
+ // Drawbridge sends lead-facing email itself — no merchant provider gates
1773
+ // it.
1774
+ //
1775
+ // This QUEUES rather than sends: queue/notification.js owns delivery, the
1776
+ // unsubscribe token and the CAN-SPAM footer. The step's job is to say who
1777
+ // and what, correctly, and to refuse early when it must not send at all.
1778
+ send: async ({ context, step, workflow }, { canSend, read } = {}) => {
1779
+ var _a, _b;
1780
+ const to = context == null ? void 0 : context.email;
1781
+ if (!to) throw new Error("No email address on context (context.email is required)");
1782
+ const request2 = { to };
1783
+ const { ok: sendable } = await canSend({ channel: "email", to });
1784
+ if (!sendable) return { message: "Recipient has opted out \u2014 skipped.", request: request2, response: { skipped: true }, skipped: true };
1785
+ const organization2 = await read.get({ collection: "organization", query: { id: workflow.organization } });
1786
+ const subscription = (organization2 == null ? void 0 : organization2.subscription) ? await read.get({ collection: "subscription", query: { id: organization2.subscription } }) : null;
1787
+ if ((subscription == null ? void 0 : subscription.status) !== "active") {
1788
+ return {
1789
+ message: "Organization has no active subscription \u2014 workflow-step email skipped.",
1790
+ request: request2,
1791
+ response: { skipped: true },
1792
+ skipped: true
1793
+ };
1794
+ }
1795
+ return {
1796
+ message: "Email queued for delivery to " + to + ".",
1797
+ request: request2,
1798
+ response: { queued: true },
1799
+ // NO `connection` FIELD, deliberately: the platform sends this.
1800
+ // `audience : 'lead'` states what the queue would otherwise infer from
1801
+ // shape.
1802
+ //
1803
+ // `campaign` is not decoration. queue/notification.js mints the
1804
+ // unsubscribe token with it, so it decides whether opting out is
1805
+ // scoped to this campaign or the whole organization, and it names the
1806
+ // campaign in the footer. Sending without it silently broadens every
1807
+ // opt-out to the entire organization.
1808
+ writes: [
1809
+ queueNotification({
1810
+ audience: "lead",
1811
+ campaign: (context == null ? void 0 : context.campaign) || null,
1812
+ lead: (context == null ? void 0 : context.lead) || null,
1813
+ message: interpolate((_a = step.settings) == null ? void 0 : _a.message, context),
1814
+ organization: workflow.organization,
1815
+ send: { type: "email", email: to },
1816
+ title: interpolate((_b = step.settings) == null ? void 0 : _b.subject, context),
1817
+ workflow: workflow.id
1818
+ })
1819
+ ]
1820
+ };
1821
+ }
1386
1822
  },
1387
1823
  inbound: false,
1388
1824
  lifecycle: false,
@@ -1392,13 +1828,207 @@ var drawbridge_default2 = {
1392
1828
  products: false,
1393
1829
  promotions: false
1394
1830
  },
1395
- segment: { sync: {} },
1396
- sms: { send: {} },
1831
+ segment: {
1832
+ // RECALCULATE SEGMENT MEMBERSHIP. The one FAN-OUT hook: it evaluates every
1833
+ // contact in an organization against every segment, which is too much for
1834
+ // one job, so it returns chunks and the shell defers completion.
1835
+ //
1836
+ // Returning `chunks` is the only thing that makes it different. The
1837
+ // declaration, the guards, the step document and the price are the shell's,
1838
+ // exactly as they are for a step that finishes in one go.
1839
+ sync: async ({ context, step }, { chunkSize, logger: logger2, read, resolveContact } = {}) => {
1840
+ var _a, _b, _c;
1841
+ if (!chunkSize) throw new Error("segment.sync needs chunkSize from the shell");
1842
+ const organization2 = context == null ? void 0 : context.organization;
1843
+ const configured = (_a = step == null ? void 0 : step.settings) == null ? void 0 : _a.segment;
1844
+ const request2 = { organization: organization2 || null, segmentId: configured || null };
1845
+ const release = (ids, status = "active") => {
1846
+ const released = (ids || []).filter(Boolean);
1847
+ return {
1848
+ events: organization2 ? released.map((id) => ({
1849
+ event: "organization.segments",
1850
+ payload: { id, status },
1851
+ room: "organization." + organization2
1852
+ })) : [],
1853
+ writes: released.map((id) => ({
1854
+ collection: "segment",
1855
+ data: { $set: { status } },
1856
+ operation: "update",
1857
+ query: { id }
1858
+ }))
1859
+ };
1860
+ };
1861
+ if (!organization2) {
1862
+ return {
1863
+ ...release([configured]),
1864
+ message: "Trigger data missing organization id \u2014 cannot sync segments.",
1865
+ request: request2,
1866
+ response: { skipped: true },
1867
+ skipped: true
1868
+ };
1869
+ }
1870
+ const segments = await read.aggregate({
1871
+ collection: "segment",
1872
+ pipeline: [{ $match: configured ? { id: configured, organization: organization2 } : { organization: organization2 } }]
1873
+ });
1874
+ if (!segments.length) {
1875
+ return {
1876
+ ...release([configured]),
1877
+ message: "No segments matched the request \u2014 nothing to sync.",
1878
+ request: request2,
1879
+ response: { skipped: true },
1880
+ skipped: true
1881
+ };
1882
+ }
1883
+ const segmentIds = segments.map((entry) => entry.id);
1884
+ try {
1885
+ let backfilled = 0;
1886
+ if (segments.some((entry) => entry.system)) {
1887
+ const contacted = await read.aggregate({
1888
+ collection: "contact",
1889
+ pipeline: [
1890
+ { $match: { organization: organization2 } },
1891
+ { $project: { _id: 0, leads: 1 } },
1892
+ { $unwind: "$leads" },
1893
+ { $group: { _id: null, ids: { $addToSet: "$leads" } } }
1894
+ ]
1895
+ });
1896
+ const uncontacted = await read.aggregate({
1897
+ collection: "lead",
1898
+ pipeline: [
1899
+ { $match: { id: { $nin: ((_b = contacted[0]) == null ? void 0 : _b.ids) || [] }, organization: organization2 } },
1900
+ { $project: { _id: 0, id: 1 } }
1901
+ ]
1902
+ });
1903
+ for (const lead of uncontacted) {
1904
+ try {
1905
+ await resolveContact({ leadId: lead.id });
1906
+ backfilled += 1;
1907
+ } catch (error) {
1908
+ if (error.code !== 11e3) throw error;
1909
+ }
1910
+ }
1911
+ (_c = logger2 == null ? void 0 : logger2.info) == null ? void 0 : _c.call(logger2, "segment.sync.backfill", { backfilled, organization: organization2, uncontacted: uncontacted.length });
1912
+ }
1913
+ const contacts2 = await read.aggregate({
1914
+ collection: "contact",
1915
+ pipeline: [
1916
+ { $match: { organization: organization2 } },
1917
+ { $project: { _id: 0, id: 1 } },
1918
+ { $sort: { id: 1 } }
1919
+ ]
1920
+ });
1921
+ if (!contacts2.length) {
1922
+ return {
1923
+ ...release(segmentIds),
1924
+ message: "Organization has no contacts to evaluate against segments.",
1925
+ request: request2,
1926
+ response: { skipped: true },
1927
+ skipped: true
1928
+ };
1929
+ }
1930
+ const contactIds = contacts2.map((contact) => contact.id);
1931
+ const org = await read.get({ collection: "organization", query: { id: organization2 } });
1932
+ const chunks = [];
1933
+ for (let index = 0; index < contactIds.length; index += chunkSize) {
1934
+ chunks.push({
1935
+ contactIds: contactIds.slice(index, index + chunkSize),
1936
+ organization: organization2,
1937
+ segments: segmentIds,
1938
+ // A BACKFILL IS NOT BILLABLE. It creates the contacts this run
1939
+ // then evaluates, so charging for it would bill an organization
1940
+ // for work its own history made necessary.
1941
+ usage: (context == null ? void 0 : context.billable) === true && backfilled === 0 ? (org == null ? void 0 : org.usage) || null : null
1942
+ });
1943
+ }
1944
+ return {
1945
+ chunks,
1946
+ ...configured && { extra: { segment: configured } },
1947
+ message: "Queued " + contactIds.length + " contacts across " + chunks.length + " chunks for segment evaluation.",
1948
+ queue: "segment",
1949
+ request: { ...request2, segments: segmentIds },
1950
+ response: { chunks: chunks.length, contacts: contactIds.length, segments: segments.length }
1951
+ };
1952
+ } catch (error) {
1953
+ throw Object.assign(error, release(segmentIds, "error"));
1954
+ }
1955
+ }
1956
+ },
1957
+ sms: {
1958
+ // SMS TO A LEAD, through the merchant's own Twilio connection.
1959
+ //
1960
+ // WITHDRAWN from the builder — twilio went, and a connection-gated step
1961
+ // with no connection to gate on could only ever render permanently
1962
+ // disabled. Stored workflows still carry it, so it still runs.
1963
+ //
1964
+ // It looks its own connection up rather than relying on the shell, because
1965
+ // the step is declared by the PRIVATE drawbridge connection (which has
1966
+ // none) while the credential belongs to twilio (which has no manifest).
1967
+ // Platform SMS will remove that split the way it did for email.
1968
+ send: async ({ context, step, workflow }, { canSend, read } = {}) => {
1969
+ var _a, _b, _c;
1970
+ const to = (_a = context == null ? void 0 : context.phone) == null ? void 0 : _a.number;
1971
+ if (!to) throw new Error("No phone number on context (context.phone.number is required)");
1972
+ const request2 = { to };
1973
+ const connection2 = await read.get({
1974
+ collection: "connection",
1975
+ query: { organization: workflow.organization, slug: "twilio", status: "active" }
1976
+ });
1977
+ if (!connection2) return { message: "No active Twilio SMS connection \u2014 workflow-step SMS skipped.", request: request2, response: { skipped: true }, skipped: true };
1978
+ const { ok: sendable } = await canSend({ channel: "sms", to: context.phone });
1979
+ if (!sendable) return { message: "Recipient has opted out \u2014 skipped.", request: request2, response: { skipped: true }, skipped: true };
1980
+ return {
1981
+ message: "SMS queued for delivery to " + to + " via twilio.",
1982
+ request: request2,
1983
+ response: { provider: "twilio", queued: true },
1984
+ // QUEUES rather than sends: queue/notification.js owns delivery, the
1985
+ // carrier opt-out line and the segment count this is billed on.
1986
+ writes: [
1987
+ queueNotification({
1988
+ connection: connection2.id,
1989
+ message: interpolate((_b = step.settings) == null ? void 0 : _b.message, context),
1990
+ organization: workflow.organization,
1991
+ send: { phone: { number: to }, type: "phone" },
1992
+ title: interpolate((_c = step.settings) == null ? void 0 : _c.subject, context),
1993
+ workflow: workflow.id
1994
+ })
1995
+ ]
1996
+ };
1997
+ }
1998
+ },
1397
1999
  webhook: false
1398
2000
  },
1399
2001
  icon: drawbridge_default,
1400
2002
  // PRIVATE: never in the catalog, always available to the builder.
1401
2003
  private: true,
2004
+ // THE PLATFORM'S OWN SENDING CREDENTIALS — SendGrid, Twilio, and the internal
2005
+ // HubSpot portal. No merchant ever sees these; they are what an admin types on
2006
+ // the provider screen so that Drawbridge itself can send.
2007
+ //
2008
+ // They belong on THIS manifest because this is the connection that sends: the
2009
+ // email, sms and segment hooks below are the only things that spend them, and
2010
+ // a private connection is still where a vendor fact lives.
2011
+ //
2012
+ // UNLIKE every public vendor, none of these appear in `requires` — see the
2013
+ // comment there. Availability and configuration are different questions, and a
2014
+ // missing CRM token must not take every base workflow step away.
2015
+ provider: {
2016
+ fields: [
2017
+ { input: "email", key: "accountSender", credential: "SENDGRID_FROM_ADDRESS", label: "Account sender", message: "Verification codes and security alerts send from here.", required: true },
2018
+ { input: "password", key: "apiKey", credential: "SENDGRID_API_KEY", label: "SendGrid API key", redact: true, required: true },
2019
+ // NOT required. The CRM sync is best-effort internal tooling and no-ops
2020
+ // without a token — requiring it would make the whole drawbridge provider
2021
+ // read not-live over something no merchant ever sees.
2022
+ { input: "password", key: "hubspotToken", credential: "HUBSPOT_ACCESS_TOKEN", label: "HubSpot access token", message: "Drawbridge's own CRM portal. Internal \u2014 no merchant sees this.", redact: true },
2023
+ // Optional: SENDGRID_SEND_FROM_ADDRESS is not boot-required in sync
2024
+ // either. Unset, it degrades to the account sender rather than
2025
+ // refusing to start.
2026
+ { input: "email", key: "leadSender", credential: "SENDGRID_SEND_FROM_ADDRESS", label: "Lead sender", message: "The default for lead-facing mail when a merchant has not verified their own domain." },
2027
+ { input: "text", key: "smsFrom", credential: "TWILIO_ACCOUNT_FROM", label: "SMS number", required: true },
2028
+ { input: "password", key: "smsSid", credential: "TWILIO_ACCOUNT_SID", label: "Twilio account SID", redact: true, required: true },
2029
+ { input: "password", key: "smsToken", credential: "TWILIO_AUTH_TOKEN", label: "Twilio auth token", redact: true, required: true }
2030
+ ]
2031
+ },
1402
2032
  // NOTHING, and HUBSPOT_ACCESS_TOKEN in particular must not be here.
1403
2033
  //
1404
2034
  // `requires` gates AVAILABILITY: a name in it that is unset removes the whole
@@ -1435,11 +2065,11 @@ var drawbridge_default2 = {
1435
2065
  key: "Email \u2014 Digest",
1436
2066
  queue: "notification",
1437
2067
  settings: {
1438
- // The organization OWNER is always a recipient, resolved in sync,
1439
- // so this is additional recipients rather than the list. It cannot
1440
- // be required: the members endpoint is owner-gated and the owner is
1441
- // not a member document, so a solo merchant has nothing to pick and
1442
- // could never save the step.
2068
+ // The organization OWNER is always a recipient, resolved by the
2069
+ // hook, so this is additional recipients rather than the list. It
2070
+ // cannot be required: the members endpoint is owner-gated and the
2071
+ // owner is not a member document, so a solo merchant has nothing to
2072
+ // pick and could never save the step.
1443
2073
  members: { of: "string", type: "array" },
1444
2074
  message: { required: true, type: "string" },
1445
2075
  subject: { required: true, type: "string" }
@@ -1535,12 +2165,12 @@ var drawbridge_default2 = {
1535
2165
 
1536
2166
  // lib/connections/icons/klaviyo.js
1537
2167
  var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
1538
- <rect width="500" height="500" fill="white"/>
2168
+ <rect width="500" height="500" fill="#FF4B32"/>
1539
2169
  <path d="M365.047 327.038H134.954V172.964H365.047L316.856 250.001L365.047 327.038Z" fill="#232121"/>
1540
2170
  </svg>`;
1541
2171
 
1542
- // lib/connections/klaviyo.js
1543
- var api = async (path, { fetcher = fetch, method = "GET", payload, token }) => {
2172
+ // lib/connections/providers/klaviyo.js
2173
+ var api2 = async (path, { fetcher = fetch, method = "GET", payload, token }) => {
1544
2174
  const response = await fetcher("https://a.klaviyo.com/api" + path, {
1545
2175
  ...payload && { body: JSON.stringify(payload) },
1546
2176
  headers: {
@@ -1576,7 +2206,8 @@ var klaviyo_default2 = {
1576
2206
  // differently, and it says so in hooks.auth.token rather than as a flag here.
1577
2207
  auth: {
1578
2208
  oauth: {
1579
- // NAMES the env vars holding OUR application's client. One identity,
2209
+ // NAMES the credentials holding OUR application's client keys into
2210
+ // the stored provider credentials, not env vars. One identity,
1580
2211
  // every merchant — the token is the merchant's and arrives from their
1581
2212
  // own consent, which is what stops one organization reading another's
1582
2213
  // data.
@@ -1716,9 +2347,9 @@ var klaviyo_default2 = {
1716
2347
  // renders an empty "Klaviyo account" field, because the merchant is
1717
2348
  // never asked which account they connected — the consent already
1718
2349
  // decided it, and asking again would be a question we can answer.
1719
- connect: async ({ fetcher, tokens }) => {
2350
+ connect: async ({ tokens }, { fetcher } = {}) => {
1720
2351
  var _a, _b, _c;
1721
- const body = await api("/accounts", { fetcher, token: tokens.accessToken });
2352
+ const body = await api2("/accounts", { fetcher, token: tokens.accessToken });
1722
2353
  const account = (_a = body == null ? void 0 : body.data) == null ? void 0 : _a[0];
1723
2354
  return {
1724
2355
  account: ((_c = (_b = account == null ? void 0 : account.attributes) == null ? void 0 : _b.contact_information) == null ? void 0 : _c.organization_name) || (account == null ? void 0 : account.id) || null,
@@ -1731,7 +2362,7 @@ var klaviyo_default2 = {
1731
2362
  //
1732
2363
  // Basic auth with our client, exactly like the token exchange — the
1733
2364
  // token being revoked is the subject, not the credential.
1734
- disconnect: async ({ clientId, clientSecret, fetcher = fetch, manifest, settings }) => {
2365
+ disconnect: async ({ clientId, clientSecret, manifest, settings }, { fetcher = fetch } = {}) => {
1735
2366
  const token = (settings == null ? void 0 : settings.refreshToken) || (settings == null ? void 0 : settings.accessToken);
1736
2367
  if (!token) return { revoked: false };
1737
2368
  const response = await fetcher(manifest.auth.oauth.urls.revoke, {
@@ -1754,7 +2385,7 @@ var klaviyo_default2 = {
1754
2385
  // the refresh token is the only thing that asks Klaviyo.
1755
2386
  //
1756
2387
  // It also keeps the grant warm against the 90-day idle window above.
1757
- probe: async ({ clientId, clientSecret, fetcher, manifest, settings }) => {
2388
+ probe: async ({ clientId, clientSecret, manifest, settings }, { fetcher } = {}) => {
1758
2389
  const token = await accessToken({
1759
2390
  clientId,
1760
2391
  clientSecret,
@@ -1784,19 +2415,18 @@ var klaviyo_default2 = {
1784
2415
  // the store's.
1785
2416
  commerce: false,
1786
2417
  // 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
2418
  contacts: {
1789
2419
  // Not yet. Suppression syncs an opt-out as unsubscribed, which is a
1790
2420
  // different thing from deleting the profile.
1791
2421
  remove: false,
1792
- sync: async ({ contact, fetcher, lead, settings, suppressed, token }) => {
2422
+ sync: async ({ contact, lead, settings, suppressed, token }, { fetcher } = {}) => {
1793
2423
  var _a, _b, _c;
1794
2424
  const list = settings == null ? void 0 : settings.list;
1795
2425
  if (!list) return { message: "No Klaviyo list is chosen for this connection.", skipped: true };
1796
2426
  const email = ((_b = (_a = lead == null ? void 0 : lead.canonical) == null ? void 0 : _a.email) == null ? void 0 : _b.value) || (lead == null ? void 0 : lead.email);
1797
2427
  if (!email) return { message: "That lead has no email address to sync.", skipped: true };
1798
2428
  const totals = (contact == null ? void 0 : contact.totals) || {};
1799
- const profile = await api("/profiles/", {
2429
+ const profile = await api2("/profiles/", {
1800
2430
  fetcher,
1801
2431
  method: "POST",
1802
2432
  payload: {
@@ -1824,7 +2454,7 @@ var klaviyo_default2 = {
1824
2454
  });
1825
2455
  const profileId = (_c = profile == null ? void 0 : profile.data) == null ? void 0 : _c.id;
1826
2456
  if (!profileId) return { message: "Klaviyo returned no profile id.", skipped: true };
1827
- await api("/profile-subscription-bulk-create-jobs/", {
2457
+ await api2("/profile-subscription-bulk-create-jobs/", {
1828
2458
  fetcher,
1829
2459
  method: "POST",
1830
2460
  payload: {
@@ -1881,13 +2511,13 @@ var klaviyo_default2 = {
1881
2511
  // it, so one call quietly returns the first ten lists and an account
1882
2512
  // with more shows a picker missing the one they wanted, with nothing to
1883
2513
  // indicate anything was cut.
1884
- audiences: async ({ cursor, fetcher, limit = 100, search, token }) => {
2514
+ audiences: async ({ cursor, limit = 100, search, token }, { fetcher } = {}) => {
1885
2515
  var _a, _b;
1886
2516
  const audiences = [];
1887
2517
  let next = cursor ? "/lists?page%5Bsize%5D=10&page%5Bcursor%5D=" + encodeURIComponent(cursor) : "/lists?page%5Bsize%5D=10";
1888
2518
  let pages = 0;
1889
2519
  while (next && audiences.length < limit && pages < 20) {
1890
- const body = await api(next, { fetcher, token });
2520
+ const body = await api2(next, { fetcher, token });
1891
2521
  for (const list of (body == null ? void 0 : body.data) || []) {
1892
2522
  audiences.push({ id: list.id, title: ((_a = list == null ? void 0 : list.attributes) == null ? void 0 : _a.name) || list.id });
1893
2523
  }
@@ -1913,6 +2543,16 @@ var klaviyo_default2 = {
1913
2543
  webhook: false
1914
2544
  },
1915
2545
  icon: klaviyo_default,
2546
+ // DRAWBRIDGE'S OWN CREDENTIALS for this vendor, as opposed to a merchant's —
2547
+ // what an admin types on the provider screen. Declared here rather than in a
2548
+ // table in lib/providers.js, so a vendor's credentials sit beside the
2549
+ // `requires` that names the same variables.
2550
+ provider: {
2551
+ fields: [
2552
+ { input: "text", key: "clientId", credential: "KLAVIYO_OAUTH_CLIENT_ID", label: "Client ID", required: true },
2553
+ { input: "password", key: "clientSecret", credential: "KLAVIYO_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
2554
+ ]
2555
+ },
1916
2556
  requires: [
1917
2557
  "KLAVIYO_OAUTH_CLIENT_ID",
1918
2558
  "KLAVIYO_OAUTH_CLIENT_SECRET"
@@ -1986,6 +2626,9 @@ var klaviyo_default2 = {
1986
2626
  title: "Klaviyo"
1987
2627
  };
1988
2628
 
2629
+ // lib/connections/providers/mailchimp.js
2630
+ import { createHash as createHash2 } from "crypto";
2631
+
1989
2632
  // lib/connections/icons/mailchimp.js
1990
2633
  var mailchimp_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
1991
2634
  <rect width="500" height="500" fill="#FFE01B"/>
@@ -1993,11 +2636,30 @@ var mailchimp_default = `<svg width="500" height="500" viewBox="0 0 500 500" fil
1993
2636
  <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
2637
  </svg>`;
1995
2638
 
1996
- // lib/connections/mailchimp.js
2639
+ // lib/connections/providers/mailchimp.js
1997
2640
  var base = (dc) => {
1998
2641
  if (!dc) throw new Error("This Mailchimp connection has no data centre stored, so there is no host to call");
1999
2642
  return "https://" + dc + ".api.mailchimp.com/3.0";
2000
2643
  };
2644
+ var api3 = async (path, { dc, fetcher = fetch, method = "GET", payload, token }) => {
2645
+ const response = await fetcher(base(dc) + path, {
2646
+ ...payload && { body: JSON.stringify(payload) },
2647
+ headers: {
2648
+ authorization: "Bearer " + token,
2649
+ ...payload && { "content-type": "application/json" }
2650
+ },
2651
+ method,
2652
+ signal: AbortSignal.timeout(15e3)
2653
+ });
2654
+ if (!response.ok) {
2655
+ throw Object.assign(
2656
+ new Error("Mailchimp refused the request (" + response.status + ")"),
2657
+ { status: response.status }
2658
+ );
2659
+ }
2660
+ return response.json();
2661
+ };
2662
+ var subscriberHash = (email) => createHash2("md5").update(String(email).trim().toLowerCase()).digest("hex");
2001
2663
  var mailchimp_default2 = {
2002
2664
  // OAUTH 2, authorization code. Every url below is quoted from
2003
2665
  // mailchimp.com/developer/marketing/guides/access-user-data-oauth-2/ rather
@@ -2040,7 +2702,9 @@ var mailchimp_default2 = {
2040
2702
  confirm: "Disconnecting removes Drawbridge's stored Mailchimp access. You can also remove Drawbridge from the Authorized Apps page in your Mailchimp account. Your contacts stay in both Drawbridge and Mailchimp \u2014 neither list is deleted.",
2041
2703
  description: [
2042
2704
  "Drawbridge no longer sends email through Mailchimp. Notification email now sends from Drawbridge itself, and verifying a domain under Networking in your organization settings puts your own brand in the from line.",
2043
- "This connection is becoming the way your Drawbridge contacts sync into a Mailchimp audience. Audience syncing is not live yet, so connecting today does nothing except choose the audience it will use when it ships."
2705
+ "Connecting Mailchimp lets Drawbridge sync the contacts your campaigns collect into a Mailchimp audience, so the people who enter a giveaway can be marketed to alongside the rest of your list.",
2706
+ "Anyone who has opted out in Drawbridge is synced as unsubscribed rather than omitted, so a person who asked not to be contacted stays suppressed in both systems instead of quietly reappearing.",
2707
+ "Someone who unsubscribed inside Mailchimp keeps that choice: a resync only sets the status of a subscriber Mailchimp has never seen before."
2044
2708
  ],
2045
2709
  excerpt: "Sync your Drawbridge contacts into a Mailchimp audience.",
2046
2710
  guide: [
@@ -2082,7 +2746,7 @@ var mailchimp_default2 = {
2082
2746
  // The header here is `OAuth <token>`, not Bearer — that is specific to
2083
2747
  // the metadata endpoint. Marketing API calls take Bearer; see the
2084
2748
  // audiences hook.
2085
- connect: async ({ fetcher = fetch, tokens }) => {
2749
+ connect: async ({ tokens }, { fetcher = fetch } = {}) => {
2086
2750
  const response = await fetcher("https://login.mailchimp.com/oauth2/metadata", {
2087
2751
  headers: {
2088
2752
  authorization: "OAuth " + (tokens == null ? void 0 : tokens.accessToken)
@@ -2115,7 +2779,51 @@ var mailchimp_default2 = {
2115
2779
  token: authToken
2116
2780
  },
2117
2781
  commerce: false,
2118
- contacts: { remove: false, sync: false },
2782
+ // The verb the contacts.sync step points at.
2783
+ contacts: {
2784
+ // Not yet. Suppression syncs an opt-out as unsubscribed, which is a
2785
+ // different thing from deleting the member — and Mailchimp's own delete is
2786
+ // permanent, so the address can never be re-added.
2787
+ remove: false,
2788
+ // PUT /lists/{list_id}/members/{subscriber_hash} — an UPSERT, which is
2789
+ // why there is no create-or-update branch here. Quoted from Mailchimp's
2790
+ // Marketing API reference for the list-members resource.
2791
+ sync: async ({ lead, settings, suppressed, token }, { fetcher } = {}) => {
2792
+ var _a, _b;
2793
+ const audience = settings == null ? void 0 : settings.audience;
2794
+ if (!audience) return { message: "No Mailchimp audience is chosen for this connection.", skipped: true };
2795
+ const email = ((_b = (_a = lead == null ? void 0 : lead.canonical) == null ? void 0 : _a.email) == null ? void 0 : _b.value) || (lead == null ? void 0 : lead.email);
2796
+ if (!email) return { message: "That lead has no email address to sync.", skipped: true };
2797
+ const hash = subscriberHash(email);
2798
+ const member = await api3("/lists/" + audience + "/members/" + hash, {
2799
+ dc: settings == null ? void 0 : settings.dc,
2800
+ fetcher,
2801
+ method: "PUT",
2802
+ payload: {
2803
+ email_address: email,
2804
+ // FNAME ONLY. Unlike Klaviyo, Mailchimp's custom fields are not
2805
+ // schemaless — a merge tag that does not exist on the audience is
2806
+ // refused, taking the whole request with it — and FNAME is one of
2807
+ // the two tags every audience is created with. The Drawbridge
2808
+ // totals Klaviyo receives cannot travel until something registers
2809
+ // merge fields on the chosen audience, which is lifecycle.register's
2810
+ // job and is not built.
2811
+ ...(lead == null ? void 0 : lead.name) && { merge_fields: { FNAME: String(lead.name).trim().split(/\s+/)[0] } },
2812
+ ...suppressed && { status: "unsubscribed" },
2813
+ status_if_new: suppressed ? "unsubscribed" : "subscribed"
2814
+ },
2815
+ token
2816
+ });
2817
+ return {
2818
+ // Merged into `context` for later steps in this run.
2819
+ context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash },
2820
+ message: suppressed ? "Synced to Mailchimp as unsubscribed \u2014 this contact has opted out." : "Synced to the Mailchimp audience.",
2821
+ // Recorded on the run for support to read back, not a write
2822
+ // instruction — the hook has already written what it needed to.
2823
+ response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash }
2824
+ };
2825
+ }
2826
+ },
2119
2827
  // Drawbridge sends its own notification email and SMS, and owns its own
2120
2828
  // segments — see the private `drawbridge` manifest. A vendor answering
2121
2829
  // these would be a second sender, which is the arrangement the platform
@@ -2134,24 +2842,13 @@ var mailchimp_default2 = {
2134
2842
  // successful — the same silent truncation Klaviyo has, at a different
2135
2843
  // number. Paged against total_items so an account past a thousand still
2136
2844
  // resolves.
2137
- audiences: async ({ cursor, fetcher = fetch, limit = 100, search, settings, token }) => {
2138
- const dc = settings == null ? void 0 : settings.dc;
2845
+ audiences: async ({ cursor, limit = 100, search, settings, token }, { fetcher } = {}) => {
2139
2846
  const count = Math.min(limit, 1e3);
2140
2847
  const offset = Number(cursor || 0);
2141
- const response = await fetcher(
2142
- base(dc) + "/lists?count=" + count + "&offset=" + offset + "&fields=lists.id,lists.name,total_items",
2143
- {
2144
- headers: { authorization: "Bearer " + token },
2145
- signal: AbortSignal.timeout(15e3)
2146
- }
2848
+ const body = await api3(
2849
+ "/lists?count=" + count + "&offset=" + offset + "&fields=lists.id,lists.name,total_items",
2850
+ { dc: settings == null ? void 0 : settings.dc, fetcher, token }
2147
2851
  );
2148
- if (!response.ok) {
2149
- throw Object.assign(
2150
- new Error("Mailchimp refused the request (" + response.status + ")"),
2151
- { status: response.status }
2152
- );
2153
- }
2154
- const body = await response.json();
2155
2852
  const audiences = ((body == null ? void 0 : body.lists) || []).map((list) => ({ id: list.id, title: (list == null ? void 0 : list.name) || list.id }));
2156
2853
  const term = String((search == null ? void 0 : search.value) || "").trim().toLowerCase();
2157
2854
  const items = term ? audiences.filter((entry) => entry.title.toLowerCase().includes(term)) : audiences;
@@ -2173,6 +2870,15 @@ var mailchimp_default2 = {
2173
2870
  webhook: false
2174
2871
  },
2175
2872
  icon: mailchimp_default,
2873
+ // DRAWBRIDGE'S OWN CREDENTIALS for this vendor, as opposed to a merchant's —
2874
+ // what an admin types on the provider screen, beside the `requires` naming the
2875
+ // same variables.
2876
+ provider: {
2877
+ fields: [
2878
+ { input: "text", key: "clientId", credential: "MAILCHIMP_OAUTH_CLIENT_ID", label: "Client ID", required: true },
2879
+ { input: "password", key: "clientSecret", credential: "MAILCHIMP_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
2880
+ ]
2881
+ },
2176
2882
  // The OAuth client this deployment registered. Without both, the vendor drops
2177
2883
  // out of availableConnections rather than offering a Connect button that
2178
2884
  // cannot complete.
@@ -2181,54 +2887,82 @@ var mailchimp_default2 = {
2181
2887
  "MAILCHIMP_OAUTH_CLIENT_SECRET"
2182
2888
  ],
2183
2889
  slug: "mailchimp",
2184
- // A key with no audience chosen is authenticated and inert. Mailchimp also
2185
- // needs its merge fields created on that audience before any Drawbridge total
2186
- // can be written to a member unlike Klaviyo, its custom fields are not
2187
- // schemaless so the audience must be picked before lifecycle.register has
2188
- // anything to register against.
2890
+ // A grant with no audience chosen is authenticated and useless the sync has
2891
+ // nowhere to put anyone so the card must say Pending rather than Active over
2892
+ // nothing. Mailchimp also needs its merge fields created on that audience
2893
+ // before any Drawbridge total can be written to a member — unlike Klaviyo, its
2894
+ // custom fields are not schemaless — so the audience must be picked before
2895
+ // lifecycle.register has anything to register against.
2189
2896
  status: (data2) => {
2190
2897
  var _a;
2191
2898
  return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.audience) ? data2.status : "pending";
2192
2899
  },
2193
- // No steps: audience sync has not shipped, so this vendor contributes nothing
2194
- // to a workflow yet. An empty steps object is the honest declaration — the
2195
- // catalog renders the connection, and no builder offers a step it cannot run.
2196
- steps: {},
2900
+ steps: {
2901
+ contacts: {
2902
+ // A DECLARATION, not the work. It names the hook that does the work, and
2903
+ // the nesting IS the name: this is `step.contacts.sync`, the string a
2904
+ // workflow document stores. Klaviyo and Attentive declare the same type —
2905
+ // a step belongs to the capability, not to whoever implements it — and the
2906
+ // connection on the step document is what says which vendor runs.
2907
+ sync: ({ data: data2 }) => ({
2908
+ hook: "contacts.sync",
2909
+ // NO ACCOUNT NAME TO INTERPOLATE, unlike Klaviyo. Mailchimp's
2910
+ // auth.connect deliberately stores only the data centre (a test pins
2911
+ // that), and settings.audience is an opaque list id no merchant would
2912
+ // recognise in a builder label — so the label names the vendor rather
2913
+ // than showing a string like a1b2c3d4e5.
2914
+ key: "Sync contact to Mailchimp",
2915
+ queue: "connection",
2916
+ // Nothing for a merchant to configure on the step itself — the audience
2917
+ // is chosen once on the connection. Declared empty rather than omitted,
2918
+ // so "this step takes no settings" and "nobody thought about settings"
2919
+ // stay different statements.
2920
+ settings: {},
2921
+ // BOTH triggers, for the same reason as Klaviyo: lead.insert alone only
2922
+ // ever fires for someone with no history yet, and crossing into a
2923
+ // segment is the other moment a contact is worth pushing.
2924
+ triggers: ["lead.insert", "segment.contact.add"],
2925
+ // One source for cost: what the builder discloses before a merchant
2926
+ // adds this step, and what is charged when it runs.
2927
+ usage: { actions: 1 }
2928
+ })
2929
+ }
2930
+ },
2931
+ // WHY, in the merchant's words, and what to do about it.
2197
2932
  tasks: (data2) => {
2198
2933
  var _a;
2199
- return [
2200
- ...((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.audience) ? [] : [
2201
- {
2202
- message: "Choose which Mailchimp audience your contacts should sync into. Until you do, nothing is being synced.",
2203
- title: "Choose an audience"
2204
- }
2205
- ],
2934
+ return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.audience) ? [] : [
2206
2935
  {
2207
- message: "Contact syncing to Mailchimp audiences has not shipped yet, and this connection no longer sends your email. Nothing is being sent to Mailchimp right now.",
2208
- title: "Audience sync not available yet",
2209
- type: "warning"
2936
+ message: "Choose which Mailchimp audience your contacts should sync into. Until you do, nothing is being synced.",
2937
+ title: "Choose an audience"
2210
2938
  }
2211
2939
  ];
2212
2940
  },
2213
2941
  title: "Mailchimp"
2214
2942
  };
2215
2943
 
2944
+ // lib/connections/providers/shopify.js
2945
+ import { randomUUID } from "crypto";
2946
+ import { customAlphabet as customAlphabet2 } from "nanoid";
2947
+
2216
2948
  // lib/connections/icons/shopify.js
2217
2949
  var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
2218
- <rect width="500" height="500" fill="white"/>
2219
- <path fill-rule="evenodd" clip-rule="evenodd" d="M309.524 407.192L308.799 128.423C306.921 126.545 303.258 127.112 301.827 127.531L292.29 130.487C291.113 126.613 289.585 122.854 287.726 119.258C280.959 106.337 271.069 99.5052 259.096 99.4866H259.059C258.259 99.4866 257.469 99.5609 256.67 99.626L256.577 99.6353C256.231 99.2089 255.871 98.7935 255.499 98.3897C250.293 92.8125 243.601 90.0889 235.588 90.3213C220.139 90.7675 204.755 101.941 192.271 121.786C183.487 135.757 176.823 153.298 174.917 166.878L144.493 176.313C135.542 179.129 135.263 179.408 134.082 187.858C133.199 194.253 109.766 375.69 109.766 375.69L306.159 409.692L309.524 407.192ZM245.181 103.065C242.569 101.346 239.511 100.546 235.885 100.621C212.033 101.308 191.23 138.611 185.923 163.467L208.771 156.384L212.851 155.119C215.845 139.336 223.355 122.957 233.181 112.416C236.616 108.639 240.671 105.477 245.172 103.065H245.181ZM224.145 151.615L256.94 141.446C257.042 132.894 256.112 120.252 251.836 111.329C247.282 113.207 243.452 116.497 240.7 119.444C233.329 127.373 227.315 139.466 224.155 151.615H224.145ZM267.211 138.267L282.455 133.536C280.02 125.616 274.238 112.342 262.517 110.111C266.161 119.527 267.099 130.431 267.211 138.267Z" fill="#95BF47"/>
2220
- <path d="M353.528 149.156C352.356 149.063 329.657 148.709 329.657 148.709C329.657 148.709 310.666 130.249 308.789 128.362C308.062 127.691 307.141 127.268 306.158 127.153V409.64L391.257 388.456C391.257 388.456 356.53 153.366 356.307 151.758C356.199 151.075 355.866 150.448 355.361 149.976C354.856 149.505 354.216 149.216 353.528 149.156Z" fill="#5E8E3E"/>
2221
- <path d="M258.993 193.019L249.103 230.052C249.103 230.052 238.079 225.023 225 225.85C205.833 227.059 205.628 239.171 205.824 242.21C206.865 258.756 250.376 262.381 252.821 301.171C254.745 331.688 236.656 352.574 210.592 354.21C179.313 356.19 162.089 337.711 162.089 337.711L168.716 309.472C168.716 309.472 186.052 322.569 199.921 321.686C208.993 321.119 212.228 313.738 211.903 308.514C210.536 286.921 175.102 288.185 172.862 252.695C170.985 222.811 190.57 192.554 233.803 189.821C250.46 188.762 258.993 193.028 258.993 193.028" fill="white"/>
2950
+ <rect width="500" height="500" fill="#95C049"/>
2951
+ <path d="M292.997 147.633C292.997 147.633 289.98 148.495 285.023 150.004C284.161 147.202 282.868 143.969 281.144 140.521C275.54 129.744 267.134 123.925 257.22 123.925C256.574 123.925 255.927 123.925 255.065 124.141C254.849 123.71 254.418 123.494 254.203 123.063C249.892 118.322 244.289 116.166 237.607 116.382C224.676 116.813 211.744 126.081 201.399 142.676C194.071 154.314 188.468 168.97 186.959 180.393C172.088 184.919 161.743 188.152 161.527 188.367C153.984 190.738 153.768 190.954 152.906 198.066C151.613 203.454 132 355.4 132 355.4L294.937 383.633V147.202C294.075 147.418 293.429 147.418 292.997 147.633ZM255.281 159.271C246.66 161.858 237.176 164.875 227.909 167.677C230.495 157.547 235.668 147.418 241.702 140.736C244.073 138.365 247.306 135.564 250.97 133.839C254.634 141.598 255.496 152.159 255.281 159.271ZM237.823 125.003C240.84 125.003 243.427 125.649 245.582 126.943C242.133 128.667 238.685 131.469 235.452 134.702C227.262 143.538 221.012 157.332 218.426 170.479C210.667 172.85 202.908 175.22 195.796 177.376C200.322 156.901 217.779 125.649 237.823 125.003ZM212.607 243.542C213.469 257.335 249.892 260.353 252.048 292.897C253.556 318.545 238.47 336.002 216.701 337.295C190.407 339.02 175.967 323.502 175.967 323.502L181.571 299.794C181.571 299.794 196.011 310.786 207.649 309.924C215.193 309.493 217.995 303.242 217.779 298.932C216.701 280.828 186.959 281.905 185.019 252.163C183.295 227.377 199.675 202.161 235.883 199.79C249.892 198.928 257.005 202.377 257.005 202.377L248.815 233.412C248.815 233.412 239.547 229.102 228.555 229.964C212.607 231.041 212.391 241.171 212.607 243.542ZM263.902 156.685C263.902 150.219 263.039 140.952 260.022 133.193C269.936 135.133 274.678 146.124 276.833 152.806C272.954 153.883 268.643 155.176 263.902 156.685Z" fill="white"/>
2952
+ <path d="M300.325 382.771L368 365.96C368 365.96 338.904 169.185 338.689 167.892C338.473 166.599 337.396 165.737 336.318 165.737C335.24 165.737 316.274 165.306 316.274 165.306C316.274 165.306 304.636 154.099 300.325 149.788V382.771Z" fill="white"/>
2222
2953
  </svg>`;
2223
2954
 
2224
2955
  // lib/connections/inbound.js
2225
2956
  import { createHmac, timingSafeEqual } from "crypto";
2226
- var verifySignature = ({ body, descriptor, headers }) => {
2957
+ var verifySignature = ({ body, descriptor, headers, secret }) => {
2958
+ if (!secret) {
2959
+ throw Object.assign(new Error("Missing webhook secret: " + descriptor.signature.secret), { status: 500 });
2960
+ }
2227
2961
  const provided = headers[descriptor.headers.signature];
2228
2962
  if (!provided) {
2229
2963
  throw Object.assign(new Error("Missing webhook signature"), { status: 401 });
2230
2964
  }
2231
- const digest = createHmac(descriptor.signature.algorithm, process.env[descriptor.signature.secret]).update(body).digest(descriptor.signature.encoding);
2965
+ const digest = createHmac(descriptor.signature.algorithm, secret).update(body).digest(descriptor.signature.encoding);
2232
2966
  const digestBuffer = Buffer.from(digest, descriptor.signature.encoding);
2233
2967
  const providedBuffer = Buffer.from(provided, descriptor.signature.encoding);
2234
2968
  if (digestBuffer.length !== providedBuffer.length || !timingSafeEqual(digestBuffer, providedBuffer)) {
@@ -2238,7 +2972,60 @@ var verifySignature = ({ body, descriptor, headers }) => {
2238
2972
  };
2239
2973
  var readEventHeader = ({ descriptor, headers }) => headers[descriptor.headers.event];
2240
2974
 
2241
- // lib/connections/shopify.js
2975
+ // lib/email.js
2976
+ var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
2977
+ var toCanonicalEmail = (value) => {
2978
+ if (!value || typeof value !== "string") return null;
2979
+ const email = value.trim().toLowerCase();
2980
+ const at = email.lastIndexOf("@");
2981
+ if (at < 1 || at === email.length - 1) return null;
2982
+ let local = email.slice(0, at);
2983
+ const domain = email.slice(at + 1);
2984
+ const plus = local.indexOf("+");
2985
+ if (plus > 0) local = local.slice(0, plus);
2986
+ if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
2987
+ if (!local) return null;
2988
+ return local + "@" + domain;
2989
+ };
2990
+
2991
+ // lib/connections/providers/shopify.js
2992
+ var toLine = ({
2993
+ price,
2994
+ product_id: productId,
2995
+ quantity,
2996
+ title,
2997
+ variant_id: variantId,
2998
+ variant_title: variantTitle
2999
+ }) => ({
3000
+ price: parseFloat(price) || 0,
3001
+ productId: productId ? "gid://shopify/Product/" + productId : null,
3002
+ quantity: quantity || 1,
3003
+ title: title || null,
3004
+ variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
3005
+ variantTitle: variantTitle || null
3006
+ });
3007
+ var attributeLineItems = (lineItems = []) => lineItems.reduce(
3008
+ (acc, item) => {
3009
+ const attrs = (item.properties || []).reduce(
3010
+ (map, { name, value }) => {
3011
+ map[name] = value;
3012
+ return map;
3013
+ },
3014
+ {}
3015
+ );
3016
+ if (!attrs["_drwbrdg_ca"]) return acc;
3017
+ if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
3018
+ const line = toLine(item);
3019
+ acc.attributedGross += line.price * line.quantity;
3020
+ acc.attributedLines.push(line);
3021
+ return acc;
3022
+ },
3023
+ { attrMap: {}, attributedGross: 0, attributedLines: [] }
3024
+ );
3025
+ var generateDiscountCode = customAlphabet2("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
3026
+ var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
3027
+ var OAUTH_ERROR_SOURCE = "oauth";
3028
+ var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
2242
3029
  var inbound = {
2243
3030
  headers: {
2244
3031
  event: "x-shopify-topic",
@@ -2300,7 +3087,7 @@ var shopify_default2 = {
2300
3087
  // the App Store listing, and the dashboard must never imply a store can be
2301
3088
  // linked from inside it.
2302
3089
  redirect: {
2303
- env: "SHOPIFY_APP_LISTING_URL",
3090
+ credential: "SHOPIFY_APP_LISTING_URL",
2304
3091
  title: "View on the Shopify App Store"
2305
3092
  }
2306
3093
  },
@@ -2355,20 +3142,476 @@ var shopify_default2 = {
2355
3142
  //
2356
3143
  // `shopify` is injected for the same reason it is everywhere else — this
2357
3144
  // package cannot import @drawbridge/shopify, which depends on it.
2358
- scopes: ({ scope, shopify }) => scope ? shopify.oauth.missingScopes(scope) : null,
3145
+ scopes: ({ scope }, { shopify } = {}) => scope ? shopify.oauth.missingScopes(scope) : null,
2359
3146
  // Shopify's install grant is exchanged inside its own app flow, not
2360
3147
  // through the shared OAuth runner.
2361
3148
  token: false
2362
3149
  },
2363
- // Implemented in drawbridge-sync, which owns the attribution and the
2364
- // controllers it needs. Declared here so the steps below can point at them:
2365
- // a step naming a hook the vendor does not implement is a workflow that
2366
- // accepts the step and then silently does nothing.
3150
+ // THE VENDOR'S OWN WORK, here in full. Every body describes its writes,
3151
+ // enqueues and events for the shell to perform see contract.js and
3152
+ // everything it needs arrives as an argument: `read` (the controller's
3153
+ // read methods, nothing that writes), `shopify` (the SDK, injected because
3154
+ // this package cannot import what depends on it), `adminToken` (minted by
3155
+ // the shell, which persists rotations), `mintId` (so one described write
3156
+ // can reference another), `dispatch` (the caller's own coordinator table,
3157
+ // for the hooks that are dispatches).
2367
3158
  commerce: {
2368
- code: {},
2369
- customer: {},
2370
- order: {},
2371
- product: {}
3159
+ // MINT A DISCOUNT CODE against the merchant's chosen discount, mapped to
3160
+ // one lead — which is what lets an order that redeems it be attributed
3161
+ // back.
3162
+ code: async ({ connection: connection2, context, step }, { adminToken, shopify } = {}) => {
3163
+ var _a;
3164
+ const discount = (_a = step.settings) == null ? void 0 : _a.discount;
3165
+ const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
3166
+ if (!(context == null ? void 0 : context.email)) return { message: "Lead email is missing.", request: request2, response: { skipped: true }, skipped: true };
3167
+ if (!(context == null ? void 0 : context.lead)) return { message: "Lead id is missing.", request: request2, response: { skipped: true }, skipped: true };
3168
+ if (!(discount == null ? void 0 : discount.id)) return { message: "Discount is not configured on this step.", request: request2, response: { skipped: true }, skipped: true };
3169
+ const adminAccessToken = await adminToken();
3170
+ if (!context.shopifyCustomerId) {
3171
+ const customer = await shopify.admin.getOrCreateCustomer({ adminAccessToken, domain: connection2.shop, email: context.email });
3172
+ 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 };
3173
+ }
3174
+ const discountCode = await shopify.admin.createDiscountCode({
3175
+ adminAccessToken,
3176
+ code: "DB-" + generateDiscountCode(),
3177
+ discountId: discount.id,
3178
+ domain: connection2.shop
3179
+ });
3180
+ if (!discountCode) return { message: "Shopify did not return a discount code \u2014 create failed.", request: request2, response: { skipped: true }, skipped: true };
3181
+ return {
3182
+ context: {
3183
+ shopifyDiscountCode: discountCode.code,
3184
+ shopifyDiscountId: String(discountCode.id)
3185
+ },
3186
+ message: "Discount code created and linked to lead.",
3187
+ request: request2,
3188
+ response: { code: discountCode.code, id: String(discountCode.id) },
3189
+ // bypassDocumentValidation because these are vendor ids on a
3190
+ // Drawbridge document the schema does not declare — the
3191
+ // canonical-identity work resolves it properly.
3192
+ writes: [{
3193
+ collection: "lead",
3194
+ data: {
3195
+ $set: {
3196
+ shopifyDiscountCode: discountCode.code,
3197
+ shopifyDiscountId: String(discountCode.id)
3198
+ }
3199
+ },
3200
+ operation: "update",
3201
+ options: { bypassDocumentValidation: true },
3202
+ query: { id: context.lead }
3203
+ }]
3204
+ };
3205
+ },
3206
+ // CREATE THE BUYER AT THE STORE, so an order can be attributed to them.
3207
+ //
3208
+ // IDEMPOTENT THREE WAYS, because this runs on every entry and a duplicate
3209
+ // customer at the store is a support ticket: the context may already
3210
+ // carry the id from an earlier step, the lead may already be linked from
3211
+ // an earlier run, and Shopify's own get-or-create settles the rest.
3212
+ customer: async ({ connection: connection2, context }, { adminToken, read, shopify } = {}) => {
3213
+ const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
3214
+ 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 };
3215
+ 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 };
3216
+ if (context.shopifyCustomerId) {
3217
+ return {
3218
+ context: { shopifyCustomerId: context.shopifyCustomerId },
3219
+ message: "Trigger data already includes a Shopify customer id \u2014 reusing.",
3220
+ request: request2,
3221
+ response: { shopifyCustomerId: context.shopifyCustomerId },
3222
+ // Reusing an id is not a creation, so it does not bill.
3223
+ skipped: true
3224
+ };
3225
+ }
3226
+ const lead = await read.get({ collection: "lead", query: { id: context.lead } });
3227
+ if (lead == null ? void 0 : lead.shopifyCustomerId) {
3228
+ return {
3229
+ context: { shopifyCustomerId: lead.shopifyCustomerId },
3230
+ message: "Lead already has a Shopify customer id \u2014 reusing.",
3231
+ request: request2,
3232
+ response: { shopifyCustomerId: lead.shopifyCustomerId },
3233
+ skipped: true
3234
+ };
3235
+ }
3236
+ const adminAccessToken = await adminToken();
3237
+ const parts = ((lead == null ? void 0 : lead.name) || "").trim().split(/\s+/).filter(Boolean);
3238
+ const customer = await shopify.admin.getOrCreateCustomer({
3239
+ adminAccessToken,
3240
+ domain: connection2.shop,
3241
+ email: context.email,
3242
+ firstName: parts.length ? parts[0] : null,
3243
+ lastName: parts.length > 1 ? parts.slice(1).join(" ") : null,
3244
+ source: "drawbridge"
3245
+ });
3246
+ 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 };
3247
+ return {
3248
+ context: { shopifyCustomerId: customer.id },
3249
+ message: "Shopify customer created/linked to lead.",
3250
+ request: request2,
3251
+ response: { shopifyCustomerId: customer.id },
3252
+ // The hook's own result, described beside the call that produced it.
3253
+ writes: [{
3254
+ collection: "lead",
3255
+ data: { $set: { shopifyCustomerId: customer.id } },
3256
+ operation: "update",
3257
+ options: { bypassDocumentValidation: true },
3258
+ query: { id: context.lead }
3259
+ }]
3260
+ };
3261
+ },
3262
+ // AN ORDER ARRIVED AT THE STORE. The largest hook in the family, because
3263
+ // attribution genuinely is: an order can reach Drawbridge two ways and
3264
+ // they bill differently.
3265
+ //
3266
+ // CONVERSION — a `_drwbrdg_ca` line-item property, injected at
3267
+ // add-to-cart. Causal: the campaign produced the sale, so
3268
+ // it carries a fee.
3269
+ // REDEMPTION — a DB- discount code matched to a lead. Associative: we
3270
+ // cannot claim we caused the purchase, so it is fee-free.
3271
+ //
3272
+ // Both can be true, and an order already recorded as a conversion can
3273
+ // later have a redemption backfilled onto it — `backfill` below.
3274
+ //
3275
+ // IDEMPOTENT THROUGH THE RETRY, one layer up: two deliveries of the same
3276
+ // order race, the loser's transaction hits a duplicate key, the step
3277
+ // fails and BullMQ redelivers — and the re-run's read at the top finds
3278
+ // what the winner wrote and skips instead of double-billing a merchant
3279
+ // for one purchase. The hook used to loop for this itself; describing
3280
+ // the writes moved the retry to the queue, with the same guarantee.
3281
+ order: async ({ connection: connection2, context }, { logger: logger2, mintId, read } = {}) => {
3282
+ var _a, _b, _c, _d, _e, _f;
3283
+ const {
3284
+ advertisement,
3285
+ created_at: createdAt,
3286
+ currency,
3287
+ customer: orderCustomer,
3288
+ email,
3289
+ id: orderId,
3290
+ line_items: lineItems = [],
3291
+ organization: organization2,
3292
+ phone
3293
+ } = context || {};
3294
+ const request2 = { orderId: orderId ? String(orderId) : null, organization: organization2 };
3295
+ const [existingOrder, existingRedemption] = await Promise.all([
3296
+ read.get({ collection: "order", query: { "provider.id": String(orderId), "provider.slug": "shopify" } }),
3297
+ read.get({ collection: "redemption", query: { "provider.id": String(orderId), "provider.slug": "shopify" } })
3298
+ ]);
3299
+ if (existingRedemption) {
3300
+ return {
3301
+ message: "Order/redemption already recorded \u2014 skipping duplicate.",
3302
+ request: request2,
3303
+ response: {
3304
+ existingOrderId: (existingOrder == null ? void 0 : existingOrder.id) || null,
3305
+ existingRedemptionId: existingRedemption.id,
3306
+ skipped: true
3307
+ },
3308
+ skipped: true
3309
+ };
3310
+ }
3311
+ const backfill = !!existingOrder;
3312
+ const { attrMap, attributedGross, attributedLines } = attributeLineItems(lineItems);
3313
+ const campaign = attrMap["_drwbrdg_ca"] || null;
3314
+ const discountCodes = Array.isArray(context == null ? void 0 : context.discount_codes) ? context.discount_codes : [];
3315
+ const codes = [...new Set(discountCodes.map((dc) => dc == null ? void 0 : dc.code).filter(Boolean))];
3316
+ const matchedLeads = codes.length ? await read.aggregate({
3317
+ collection: "lead",
3318
+ pipeline: [{ $match: { organization: organization2, shopifyDiscountCode: { $in: codes } } }]
3319
+ }) : [];
3320
+ const codeToLead = {};
3321
+ for (const found of matchedLeads) {
3322
+ if (found.shopifyDiscountCode) codeToLead[found.shopifyDiscountCode] = found;
3323
+ }
3324
+ const matchedDiscounts = discountCodes.filter((dc) => (dc == null ? void 0 : dc.code) && codeToLead[dc.code]).map((dc) => ({
3325
+ amount: parseFloat(dc.amount) || 0,
3326
+ code: dc.code,
3327
+ id: codeToLead[dc.code].shopifyDiscountId || null
3328
+ }));
3329
+ const matchedLead = matchedDiscounts.length ? codeToLead[matchedDiscounts[0].code] : null;
3330
+ const discount = matchedDiscounts.length ? {
3331
+ amount: matchedDiscounts.reduce((sum, entry) => sum + entry.amount, 0),
3332
+ codes: matchedDiscounts
3333
+ } : null;
3334
+ const matchedCodes = new Set(matchedDiscounts.map((entry) => entry.code));
3335
+ const unmatched = codes.filter((code2) => code2.startsWith("DB-") && !matchedCodes.has(code2));
3336
+ if (unmatched.length) {
3337
+ (_a = logger2 == null ? void 0 : logger2.warn) == null ? void 0 : _a.call(logger2, "shopify.order.discount.unmatched", {
3338
+ campaign: campaign || null,
3339
+ codes: JSON.stringify(unmatched),
3340
+ isConversion: !!campaign,
3341
+ orderId: String(orderId),
3342
+ organization: organization2
3343
+ });
3344
+ }
3345
+ if (!campaign && !discount || backfill && !discount) {
3346
+ return {
3347
+ message: backfill ? "Order already recorded and no Drawbridge discount code matched \u2014 nothing to backfill." : "Order has no Drawbridge attribution \u2014 not recording.",
3348
+ request: request2,
3349
+ response: { skipped: true },
3350
+ skipped: true
3351
+ };
3352
+ }
3353
+ let advertisementId = null;
3354
+ let affiliateId = null;
3355
+ let campaignOrganization = organization2;
3356
+ let gross = 0;
3357
+ let leadId = null;
3358
+ let lines = [];
3359
+ let orderCampaign = null;
3360
+ let pageId = null;
3361
+ const isConversion = !!campaign;
3362
+ const customerPhone = toE164((orderCustomer == null ? void 0 : orderCustomer.phone) || phone) || null;
3363
+ const matchPhones = [...new Set([
3364
+ customerPhone,
3365
+ toE164((_b = context == null ? void 0 : context.billing_address) == null ? void 0 : _b.phone),
3366
+ toE164((_c = context == null ? void 0 : context.shipping_address) == null ? void 0 : _c.phone)
3367
+ ].filter(Boolean))];
3368
+ if (isConversion) {
3369
+ const campaignDoc = await read.get({ collection: "campaign", query: { id: campaign } });
3370
+ if (!campaignDoc || campaignDoc.organization !== organization2) {
3371
+ return {
3372
+ message: "Order carried a campaign attribution that does not belong to this store \u2014 not recording.",
3373
+ request: request2,
3374
+ response: { skipped: true },
3375
+ skipped: true
3376
+ };
3377
+ }
3378
+ advertisementId = attrMap["_drwbrdg_ad"] || advertisement || null;
3379
+ affiliateId = attrMap["_drwbrdg_af"] || null;
3380
+ campaignOrganization = campaignDoc.organization;
3381
+ gross = attributedGross;
3382
+ lines = attributedLines;
3383
+ orderCampaign = campaign;
3384
+ pageId = attrMap["_drwbrdg_pg"] || null;
3385
+ const identifiers = [];
3386
+ const canonicalEmail = toCanonicalEmail(email);
3387
+ if (email) identifiers.push({ email: email.toLowerCase() });
3388
+ if (canonicalEmail) identifiers.push({ "canonical.email.value": canonicalEmail });
3389
+ if (matchPhones.length) identifiers.push({ "phone.number": { $in: matchPhones } });
3390
+ if (matchPhones.length) identifiers.push({ "canonical.phone.value": { $in: matchPhones } });
3391
+ if (identifiers.length) {
3392
+ const lead = await read.get({
3393
+ collection: "lead",
3394
+ query: {
3395
+ campaigns: { $in: [campaign] },
3396
+ organization: campaignOrganization,
3397
+ $or: identifiers
3398
+ }
3399
+ });
3400
+ leadId = (lead == null ? void 0 : lead.id) || null;
3401
+ if (!leadId) {
3402
+ const orgLead = await read.get({
3403
+ collection: "lead",
3404
+ query: { organization: campaignOrganization, $or: identifiers }
3405
+ });
3406
+ leadId = (orgLead == null ? void 0 : orgLead.id) || null;
3407
+ }
3408
+ }
3409
+ } else {
3410
+ leadId = matchedLead.id;
3411
+ orderCampaign = (matchedLead.campaigns || []).length === 1 ? matchedLead.campaigns[0] : null;
3412
+ gross = lineItems.reduce((sum, item) => {
3413
+ const line = toLine(item);
3414
+ return sum + line.price * line.quantity;
3415
+ }, 0);
3416
+ lines = lineItems.map(toLine);
3417
+ }
3418
+ const org = await read.get({ collection: "organization", query: { id: campaignOrganization } });
3419
+ let rate = 0;
3420
+ if (isConversion) {
3421
+ const subscription = await read.get({ collection: "subscription", query: { id: org == null ? void 0 : org.subscription } });
3422
+ rate = conversionRate(subscription);
3423
+ }
3424
+ const fee = isConversion ? Math.round(gross * rate) / 100 : 0;
3425
+ const net2 = Math.round((gross - fee) * 100) / 100;
3426
+ const currencyCode = (currency || "usd").toLowerCase();
3427
+ const purchasedAt = new Date(createdAt || Date.now());
3428
+ const customer = orderCustomer || email || phone ? {
3429
+ 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,
3430
+ email: (orderCustomer == null ? void 0 : orderCustomer.email) || email || null,
3431
+ firstName: (orderCustomer == null ? void 0 : orderCustomer.first_name) || null,
3432
+ id: (orderCustomer == null ? void 0 : orderCustomer.id) ? String(orderCustomer.id) : null,
3433
+ lastName: (orderCustomer == null ? void 0 : orderCustomer.last_name) || null,
3434
+ phone: customerPhone
3435
+ } : null;
3436
+ const source = (connection2 == null ? void 0 : connection2.source) ? { domain: connection2.source.domain, id: connection2.source.id } : void 0;
3437
+ const orderDocId = (existingOrder == null ? void 0 : existingOrder.id) || (isConversion && !backfill ? mintId() : null);
3438
+ const writes = [];
3439
+ if (isConversion && !backfill) {
3440
+ writes.push({
3441
+ collection: "order",
3442
+ data: {
3443
+ advertisement: advertisementId,
3444
+ affiliate: affiliateId,
3445
+ campaign: orderCampaign,
3446
+ currency: currencyCode,
3447
+ customer,
3448
+ discount,
3449
+ fee,
3450
+ gross,
3451
+ id: orderDocId,
3452
+ lead: leadId,
3453
+ lines,
3454
+ net: net2,
3455
+ organization: campaignOrganization,
3456
+ page: pageId,
3457
+ provider: { id: String(orderId), slug: "shopify" },
3458
+ purchasedAt,
3459
+ rate,
3460
+ source,
3461
+ status: "completed"
3462
+ },
3463
+ operation: "create"
3464
+ });
3465
+ if (org == null ? void 0 : org.usage) {
3466
+ writes.push({
3467
+ collection: "usage",
3468
+ data: { $inc: { "totals.revenue": gross } },
3469
+ operation: "update",
3470
+ query: { id: org.usage }
3471
+ });
3472
+ }
3473
+ if (leadId) {
3474
+ writes.push({
3475
+ collection: "lead",
3476
+ data: { $inc: { "totals.orders": 1 } },
3477
+ operation: "update",
3478
+ options: { bypassDocumentValidation: true },
3479
+ query: { id: leadId }
3480
+ });
3481
+ }
3482
+ }
3483
+ if (discount) {
3484
+ writes.push({
3485
+ collection: "redemption",
3486
+ data: {
3487
+ advertisement: advertisementId,
3488
+ affiliate: affiliateId,
3489
+ campaign: orderCampaign,
3490
+ code: ((_e = matchedDiscounts[0]) == null ? void 0 : _e.code) || null,
3491
+ currency: currencyCode,
3492
+ customer,
3493
+ discount,
3494
+ gross,
3495
+ lead: leadId,
3496
+ order: orderDocId,
3497
+ organization: campaignOrganization,
3498
+ page: pageId,
3499
+ provider: { id: String(orderId), slug: "shopify" },
3500
+ purchasedAt,
3501
+ source,
3502
+ status: "completed"
3503
+ },
3504
+ operation: "create"
3505
+ });
3506
+ if (org == null ? void 0 : org.usage) {
3507
+ writes.push({
3508
+ collection: "usage",
3509
+ data: { $inc: { "totals.redemptions": 1 } },
3510
+ operation: "update",
3511
+ query: { id: org.usage }
3512
+ });
3513
+ }
3514
+ if (leadId) {
3515
+ writes.push({
3516
+ collection: "lead",
3517
+ data: { $inc: { "totals.redemptions": 1 } },
3518
+ operation: "update",
3519
+ options: { bypassDocumentValidation: true },
3520
+ query: { id: leadId }
3521
+ });
3522
+ }
3523
+ }
3524
+ const enqueues = (org == null ? void 0 : org.billingProvider) === "shopify" && fee > 0 && ((_f = connection2 == null ? void 0 : connection2.source) == null ? void 0 : _f.id) && !backfill ? [{
3525
+ data: {
3526
+ idempotencyKey: String(orderId),
3527
+ orderDocId,
3528
+ orderId: String(orderId),
3529
+ rate,
3530
+ shopId: connection2.source.id,
3531
+ // The App Events API returns no event id, so one is generated
3532
+ // here — the event handle plus the order id — and sent as the
3533
+ // event's `reference`. queue/usage.js stamps the same id onto
3534
+ // the order as billed.transaction.
3535
+ transaction: "drawbridge-orders." + orderId,
3536
+ value: Math.round(fee * 100)
3537
+ },
3538
+ name: "billing",
3539
+ options: { jobId: "shopify.usage." + orderId },
3540
+ queue: "usage"
3541
+ }] : [];
3542
+ return {
3543
+ enqueues,
3544
+ message: backfill ? "Redemption backfilled for an already-recorded order." : isConversion ? "Order recorded." : "Discount redemption recorded (fee-free).",
3545
+ request: request2,
3546
+ response: {
3547
+ campaign: orderCampaign,
3548
+ currency: currencyCode,
3549
+ discount,
3550
+ fee,
3551
+ gross,
3552
+ lead: leadId,
3553
+ lines: lines.length,
3554
+ net: net2,
3555
+ orderId: String(orderId)
3556
+ },
3557
+ // ONE TRANSACTION. The order, the redemption and both totals
3558
+ // counters land together or not at all — a half-written attribution
3559
+ // is revenue counted twice or not at all, and neither is
3560
+ // recoverable by hand.
3561
+ transaction: writes.length > 0,
3562
+ writes
3563
+ };
3564
+ },
3565
+ // A PRODUCT CHANGED AT THE STORE. Upserts the product row and hands it to
3566
+ // the product pipeline; the actual field sync happens there.
3567
+ //
3568
+ // The shell has already refused a missing or inactive Shopify connection,
3569
+ // so what is left is the two things only this hook can know are wrong.
3570
+ product: async ({ connection: connection2, context, workflow }, { mintId } = {}) => {
3571
+ const request2 = {
3572
+ numericId: (context == null ? void 0 : context.id) || null,
3573
+ organizationId: workflow.organization,
3574
+ title: (context == null ? void 0 : context.title) || null
3575
+ };
3576
+ if (!(context == null ? void 0 : context.id)) return { message: "Skipped \u2014 product webhook payload had no id.", request: request2, response: { skipped: true }, skipped: true };
3577
+ if (!connection2.shop) return { message: "Skipped \u2014 Shopify connection is missing shop domain.", request: request2, response: { skipped: true }, skipped: true };
3578
+ const providerId = "gid://shopify/Product/" + context.id;
3579
+ const productId = mintId();
3580
+ return {
3581
+ enqueues: [{
3582
+ data: { product: productId, providerId, shop: connection2.shop },
3583
+ name: "workflow",
3584
+ options: { jobId: "product.workflow.shopify." + providerId + "." + Date.now() },
3585
+ queue: "product.shopify"
3586
+ }],
3587
+ message: "Product sync queued from Shopify webhook.",
3588
+ request: request2,
3589
+ response: { productId, providerId, title: (context == null ? void 0 : context.title) || null },
3590
+ // KEYED ON PROVIDER + SHOP, so the same product in two stores stays
3591
+ // two rows. `connections` accumulates rather than replaces: one
3592
+ // store can be linked to several organizations, and each keeps its
3593
+ // own claim on the row.
3594
+ writes: [{
3595
+ collection: "product",
3596
+ data: {
3597
+ $addToSet: { connections: connection2.id },
3598
+ $setOnInsert: {
3599
+ id: productId,
3600
+ provider: { id: providerId, slug: "shopify" },
3601
+ "source.id": connection2.id,
3602
+ status: "active"
3603
+ }
3604
+ },
3605
+ operation: "update",
3606
+ options: { upsert: true },
3607
+ query: {
3608
+ "provider.id": providerId,
3609
+ "provider.slug": "shopify",
3610
+ "source.domain": connection2.shop
3611
+ }
3612
+ }]
3613
+ };
3614
+ }
2372
3615
  },
2373
3616
  contacts: { remove: false, sync: false },
2374
3617
  // verify and event lean entirely on the shared HMAC helper — Shopify's
@@ -2386,7 +3629,16 @@ var shopify_default2 = {
2386
3629
  sms: false,
2387
3630
  inbound: {
2388
3631
  event: (args) => readEventHeader({ ...args, descriptor: inbound }),
2389
- process: {},
3632
+ // One hook over the whole topic table, because that is what this
3633
+ // manifest declares: Shopify processes its own buffered events. The
3634
+ // topic rides in on the context rather than being a second hook name per
3635
+ // topic; the caller's handler table arrives as a prop.
3636
+ process: async ({ context }, { dispatch } = {}) => {
3637
+ const key = "shopify." + (context == null ? void 0 : context.topic);
3638
+ const handled = await dispatch({ data: context == null ? void 0 : context.data, handler: key });
3639
+ if (!handled) return { message: "No handler for " + key, skipped: true };
3640
+ return { message: "Processed " + key, request: { topic: context == null ? void 0 : context.topic } };
3641
+ },
2390
3642
  receive: ({ channel, event, headers, payload }) => {
2391
3643
  if (channel === "compliance" && !COMPLIANCE_TOPICS.has(event)) {
2392
3644
  throw Object.assign(new Error("Unrecognized compliance topic: " + event), { status: 401 });
@@ -2402,7 +3654,107 @@ var shopify_default2 = {
2402
3654
  },
2403
3655
  verify: (args) => verifySignature({ ...args, descriptor: inbound })
2404
3656
  },
2405
- lifecycle: { cleanup: {}, health: {}, register: {}, rehydrate: {} },
3657
+ lifecycle: {
3658
+ // DISPATCHES INTO THE CALLER'S OWN COORDINATORS. These three are
3659
+ // declarations made true: the work is queue orchestration over
3660
+ // Drawbridge's own collections, which is coordinator work and stays in
3661
+ // the repo that owns the queues. The hook receives the dispatch table as
3662
+ // a prop and picks the entry, so the manifest owns the SEAM — asking
3663
+ // Shopify whether it handles its own lifecycle now gets a real function
3664
+ // instead of `unimplemented` while the work happened anyway.
3665
+ cleanup: async ({ context }, { dispatch } = {}) => {
3666
+ await dispatch({ data: context, handler: "cleanup" });
3667
+ return { message: "Ran shopify lifecycle.cleanup", request: context || null };
3668
+ },
3669
+ // KEEP STORE ACCESS WORKING. Not a webhook monitor, despite the name the
3670
+ // step once carried — webhooks are declarative, declared in the app's
3671
+ // toml and applied by Shopify to every install, so nothing here registers
3672
+ // or checks them.
3673
+ //
3674
+ // It rotates the refresh token before its window closes, proves the
3675
+ // access token still works, reconciles the scopes the store granted
3676
+ // against the ones the app now needs, and queues a webhook
3677
+ // reconciliation.
3678
+ health: async ({ connection: connection2, workflow }, { adminToken, read, reconcileScopes, resolveSettings, rotateToken, shopify } = {}) => {
3679
+ const request2 = {
3680
+ connectionId: workflow.connection,
3681
+ organizationId: workflow.organization,
3682
+ shop: connection2.shop
3683
+ };
3684
+ const refreshTokenAtStart = (await resolveSettings()).refreshToken || null;
3685
+ try {
3686
+ const adminAccessToken = await adminToken();
3687
+ const settings = await resolveSettings();
3688
+ const refreshTokenExpiresAt = settings.refreshTokenExpiresAt;
3689
+ const needsRotation = refreshTokenExpiresAt && new Date(refreshTokenExpiresAt) < new Date(Date.now() + REFRESH_TOKEN_FRESHNESS_BUFFER_MS);
3690
+ let refreshTokenRotated = false;
3691
+ if (needsRotation) {
3692
+ await rotateToken();
3693
+ refreshTokenRotated = true;
3694
+ }
3695
+ await shopify.oauth.ping({ adminAccessToken, domain: connection2.shop });
3696
+ const scopesMissing = await reconcileScopes({ shop: connection2.shop });
3697
+ return {
3698
+ enqueues: [{
3699
+ data: {
3700
+ data: {
3701
+ connectionId: workflow.connection,
3702
+ organizationId: workflow.organization
3703
+ },
3704
+ event: "shopify.register.webhooks"
3705
+ },
3706
+ name: "register",
3707
+ options: { jobId: "connection.update.register." + workflow.connection + "." + randomUUID() },
3708
+ queue: "connection"
3709
+ }],
3710
+ 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.",
3711
+ request: request2,
3712
+ response: {
3713
+ pingedAt: /* @__PURE__ */ new Date(),
3714
+ refreshTokenExpiresAt: refreshTokenExpiresAt || null,
3715
+ refreshTokenRotated,
3716
+ scopesMissing,
3717
+ webhookReconciliationQueued: true
3718
+ }
3719
+ };
3720
+ } catch (error) {
3721
+ if (OAUTH_GRANT_REVOKED_CODES.includes(error.code)) {
3722
+ const current = await read.get({ collection: "connection", query: { id: connection2.id } });
3723
+ const refreshTokenStored = current ? (await resolveSettings(current)).refreshToken || null : null;
3724
+ const rotated = error.code === "invalid_grant" && refreshTokenStored !== refreshTokenAtStart;
3725
+ if (current && !rotated) {
3726
+ const others = (current.errors || []).filter((entry) => entry.source !== OAUTH_ERROR_SOURCE);
3727
+ error.writes = [{
3728
+ collection: "connection",
3729
+ data: {
3730
+ $set: {
3731
+ errors: [
3732
+ ...others,
3733
+ {
3734
+ message: "Shopify disconnected this store. Open the Drawbridge app in your Shopify admin to reconnect.",
3735
+ source: OAUTH_ERROR_SOURCE
3736
+ }
3737
+ ],
3738
+ status: "error"
3739
+ }
3740
+ },
3741
+ operation: "update",
3742
+ query: { id: connection2.id }
3743
+ }];
3744
+ }
3745
+ }
3746
+ throw error;
3747
+ }
3748
+ },
3749
+ register: async ({ context }, { dispatch } = {}) => {
3750
+ await dispatch({ data: context, handler: "register" });
3751
+ return { message: "Ran shopify lifecycle.register", request: context || null };
3752
+ },
3753
+ rehydrate: async ({ context }, { dispatch } = {}) => {
3754
+ await dispatch({ data: context, handler: "rehydrate" });
3755
+ return { message: "Ran shopify lifecycle.rehydrate", request: context || null };
3756
+ }
3757
+ },
2406
3758
  resources: {
2407
3759
  audiences: false,
2408
3760
  // Shopify has no separate price resource — a price belongs to a product
@@ -2422,7 +3774,7 @@ var shopify_default2 = {
2422
3774
  // credential is the caller's job because it is Drawbridge's job: the
2423
3775
  // admin token refreshes and writes itself back, which is service work,
2424
3776
  // not vendor work.
2425
- products: async ({ cursor, limit = 100, search, settings, shopify, sort }) => {
3777
+ products: async ({ cursor, limit = 100, search, settings, sort }, { shopify } = {}) => {
2426
3778
  var _a, _b, _c, _d;
2427
3779
  const products = await shopify.storefront.getProducts({
2428
3780
  cursor,
@@ -2442,7 +3794,7 @@ var shopify_default2 = {
2442
3794
  }
2443
3795
  };
2444
3796
  },
2445
- promotions: async ({ cursor, limit = 100, search, settings, shopify }) => {
3797
+ promotions: async ({ cursor, limit = 100, search, settings }, { shopify } = {}) => {
2446
3798
  var _a, _b;
2447
3799
  const discounts = await shopify.admin.getDiscounts({
2448
3800
  adminAccessToken: settings == null ? void 0 : settings.adminAccessToken,
@@ -2488,6 +3840,19 @@ var shopify_default2 = {
2488
3840
  const shop = (data2 == null ? void 0 : data2.shop) || ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.domain);
2489
3841
  return shop ? "https://admin.shopify.com/store/" + String(shop).replace(".myshopify.com", "") + "/apps/" + (env == null ? void 0 : env.SHOPIFY_APP_HANDLE) : void 0;
2490
3842
  },
3843
+ // DRAWBRIDGE'S OWN CREDENTIALS for this vendor, as opposed to a merchant's —
3844
+ // what an admin types on the provider screen. The four names below are exactly
3845
+ // what `requires` gates on, which is the point of declaring them together: a
3846
+ // name required by the manifest and enterable nowhere is a vendor that can
3847
+ // never go live from the admin screen.
3848
+ provider: {
3849
+ fields: [
3850
+ { input: "text", key: "apiKey", credential: "SHOPIFY_API_KEY", label: "API key", required: true },
3851
+ { input: "password", key: "apiSecret", credential: "SHOPIFY_API_SECRET", label: "API secret", redact: true, required: true },
3852
+ { input: "text", key: "appHandle", credential: "SHOPIFY_APP_HANDLE", label: "App handle", required: true },
3853
+ { input: "text", key: "listingUrl", credential: "SHOPIFY_APP_LISTING_URL", label: "App listing URL", required: true }
3854
+ ]
3855
+ },
2491
3856
  // A pre-launch integration: it only surfaces once the App Store listing
2492
3857
  // exists and the app is fully configured. Requiring all four means it can
2493
3858
  // never render half-configured — and absence of any one excludes the
@@ -2521,9 +3886,6 @@ var shopify_default2 = {
2521
3886
  // workflow document, and those strings cannot be renamed without a backfill.
2522
3887
  //
2523
3888
  // 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
3889
  steps: {
2528
3890
  commerce: {
2529
3891
  code: {
@@ -2628,7 +3990,7 @@ var shopify_default2 = {
2628
3990
  title: "Shopify"
2629
3991
  };
2630
3992
 
2631
- // lib/connections/webhook.js
3993
+ // lib/connections/providers/webhook.js
2632
3994
  import crypto from "crypto";
2633
3995
 
2634
3996
  // lib/safe-http.js
@@ -2766,7 +4128,7 @@ var safeRequest = async ({
2766
4128
  }
2767
4129
  };
2768
4130
 
2769
- // lib/connections/webhook.js
4131
+ // lib/connections/providers/webhook.js
2770
4132
  var webhook_default = {
2771
4133
  // Connecting GENERATES the secret rather than storing one the merchant typed,
2772
4134
  // so the buttons say what actually happens.
@@ -2853,11 +4215,10 @@ var webhook_default = {
2853
4215
  // That is the rule the whole split runs on: a hook lives in sync only if it
2854
4216
  // needs Drawbridge's own database, sockets or queues. This one does not.
2855
4217
  webhook: {
2856
- send: async ({ context, controller, request: send2 = safeRequest, settings, step }) => {
4218
+ send: async ({ context, lead, settings, step }, { request: send2 = safeRequest } = {}) => {
2857
4219
  const { headers = {}, method = "POST", url } = step.settings || {};
2858
4220
  const request2 = { method, url: url || null };
2859
4221
  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
4222
  const body = lead || context;
2862
4223
  request2.body = body;
2863
4224
  const outgoing = { ...headers };
@@ -2933,7 +4294,7 @@ var leaves = (node, path = []) => Object.entries(node || {}).flatMap(
2933
4294
  ([key, value]) => typeof value === "function" ? [[[...path, key].join("."), value]] : value && typeof value === "object" ? leaves(value, [...path, key]) : []
2934
4295
  );
2935
4296
  var build = (manifest) => {
2936
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
4297
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
2937
4298
  if (!(manifest == null ? void 0 : manifest.slug)) throw new Error("A connection needs a slug");
2938
4299
  if (!(manifest == null ? void 0 : manifest.title)) throw new Error(manifest.slug + " needs a title");
2939
4300
  if (!(manifest == null ? void 0 : manifest.private) && !(manifest == null ? void 0 : manifest.feature)) throw new Error(manifest.slug + " needs a plan feature key");
@@ -2963,6 +4324,17 @@ var build = (manifest) => {
2963
4324
  }
2964
4325
  }
2965
4326
  }
4327
+ for (const field2 of ((_c = manifest.provider) == null ? void 0 : _c.fields) || []) {
4328
+ if (!(field2 == null ? void 0 : field2.key) || !(field2 == null ? void 0 : field2.label)) {
4329
+ throw new Error(manifest.slug + " declares a provider field with no key or label");
4330
+ }
4331
+ if (!INPUTS.includes(field2.input)) {
4332
+ throw new Error(manifest.slug + ".provider." + field2.key + " needs an input the admin form can render \u2014 one of " + INPUTS.join(", "));
4333
+ }
4334
+ if (field2.input === "password" && !field2.redact) {
4335
+ throw new Error(manifest.slug + ".provider." + field2.key + " is a password and must declare redact : true \u2014 the api would hand the value back");
4336
+ }
4337
+ }
2966
4338
  if (typeof (manifest == null ? void 0 : manifest.icon) !== "string" || !manifest.icon.includes("<svg")) {
2967
4339
  throw new Error(manifest.slug + " needs an icon \u2014 the svg markup itself, not a path to one");
2968
4340
  }
@@ -2975,23 +4347,23 @@ var build = (manifest) => {
2975
4347
  if (!GROUPS.includes(manifest == null ? void 0 : manifest.group)) {
2976
4348
  throw new Error(manifest.slug + " needs a group \u2014 one of " + GROUPS.join(", "));
2977
4349
  }
2978
- if ((_c = manifest == null ? void 0 : manifest.connect) == null ? void 0 : _c.type) {
4350
+ if ((_d = manifest == null ? void 0 : manifest.connect) == null ? void 0 : _d.type) {
2979
4351
  throw new Error(manifest.slug + " declares connect.type \u2014 that is auth.type now");
2980
4352
  }
2981
- if (!AUTH_TYPES.includes((_d = manifest == null ? void 0 : manifest.auth) == null ? void 0 : _d.type)) {
4353
+ if (!AUTH_TYPES.includes((_e = manifest == null ? void 0 : manifest.auth) == null ? void 0 : _e.type)) {
2982
4354
  throw new Error(manifest.slug + " needs auth.type \u2014 one of " + AUTH_TYPES.join(", "));
2983
4355
  }
2984
4356
  if (manifest.auth.type === "oauth") {
2985
4357
  for (const field2 of OAUTH_FIELDS) {
2986
- if (!((_e = manifest.auth.oauth) == null ? void 0 : _e[field2])) {
4358
+ if (!((_f = manifest.auth.oauth) == null ? void 0 : _f[field2])) {
2987
4359
  throw new Error(manifest.slug + " is oauth and must declare auth.oauth." + field2);
2988
4360
  }
2989
4361
  }
2990
- if (typeof ((_g = (_f = manifest.hooks) == null ? void 0 : _f.auth) == null ? void 0 : _g.token) !== "function") {
4362
+ if (typeof ((_h = (_g = manifest.hooks) == null ? void 0 : _g.auth) == null ? void 0 : _h.token) !== "function") {
2991
4363
  throw new Error(manifest.slug + " is oauth and must implement hooks.auth.token \u2014 point it at authToken() or wrap it");
2992
4364
  }
2993
4365
  for (const url of OAUTH_URLS) {
2994
- if (!((_i = (_h = manifest.auth.oauth) == null ? void 0 : _h.urls) == null ? void 0 : _i[url])) {
4366
+ if (!((_j = (_i = manifest.auth.oauth) == null ? void 0 : _i.urls) == null ? void 0 : _j[url])) {
2995
4367
  throw new Error(manifest.slug + " is oauth and must declare auth.oauth.urls." + url);
2996
4368
  }
2997
4369
  }
@@ -3001,16 +4373,16 @@ var build = (manifest) => {
3001
4373
  );
3002
4374
  }
3003
4375
  }
3004
- if (implemented(manifest.hooks, "inbound.event") && !((_k = (_j = manifest.inbound) == null ? void 0 : _j.headers) == null ? void 0 : _k.event)) {
4376
+ if (implemented(manifest.hooks, "inbound.event") && !((_l = (_k = manifest.inbound) == null ? void 0 : _k.headers) == null ? void 0 : _l.event)) {
3005
4377
  throw new Error(manifest.slug + " implements inbound.event but declares no inbound.headers.event");
3006
4378
  }
3007
- if (implemented(manifest.hooks, "inbound.verify") && !((_m = (_l = manifest.inbound) == null ? void 0 : _l.headers) == null ? void 0 : _m.signature)) {
4379
+ if (implemented(manifest.hooks, "inbound.verify") && !((_n = (_m = manifest.inbound) == null ? void 0 : _m.headers) == null ? void 0 : _n.signature)) {
3008
4380
  throw new Error(manifest.slug + " implements inbound.verify but declares no inbound.headers.signature");
3009
4381
  }
3010
4382
  if (typeof (manifest == null ? void 0 : manifest.status) !== "function") {
3011
4383
  throw new Error(manifest.slug + " must declare status( data ) \u2014 return null to accept the connection's own status, or { message, status } to override it");
3012
4384
  }
3013
- if (!Array.isArray((_n = manifest == null ? void 0 : manifest.content) == null ? void 0 : _n.guide) || !manifest.content.guide.length) {
4385
+ if (!Array.isArray((_o = manifest == null ? void 0 : manifest.content) == null ? void 0 : _o.guide) || !manifest.content.guide.length) {
3014
4386
  throw new Error(manifest.slug + " needs content.guide \u2014 an array of steps for its page");
3015
4387
  }
3016
4388
  if (typeof (manifest == null ? void 0 : manifest.status) !== "function") {
@@ -3022,8 +4394,8 @@ var build = (manifest) => {
3022
4394
  }
3023
4395
  for (const [domain, verbs] of Object.entries(HOOKS)) {
3024
4396
  for (const verb of verbs) {
3025
- const hook = (_p = (_o = manifest.hooks) == null ? void 0 : _o[domain]) == null ? void 0 : _p[verb];
3026
- if (((_q = manifest.hooks) == null ? void 0 : _q[domain]) === false) continue;
4397
+ const hook = (_q = (_p = manifest.hooks) == null ? void 0 : _p[domain]) == null ? void 0 : _q[verb];
4398
+ if (((_r = manifest.hooks) == null ? void 0 : _r[domain]) === false) continue;
3027
4399
  if (hook !== false && !implemented({ [domain]: { [verb]: hook } }, domain + "." + verb)) {
3028
4400
  throw new Error(manifest.slug + " must answer hooks." + domain + "." + verb + " \u2014 false, a function, or {} if another repo implements it");
3029
4401
  }
@@ -3069,14 +4441,18 @@ var connections = Object.freeze({
3069
4441
  webhook: build(webhook_default)
3070
4442
  });
3071
4443
  (() => {
3072
- const owners = {};
4444
+ var _a;
4445
+ const routes = {};
3073
4446
  for (const [slug, manifest] of Object.entries(connections)) {
3074
- for (const [name] of leaves(manifest.steps)) {
4447
+ for (const [name, step] of leaves(manifest.steps)) {
3075
4448
  const type = "step." + name;
3076
- if (owners[type]) {
3077
- throw new Error("Step " + type + " is declared by both " + owners[type] + " and " + slug);
4449
+ const queue = (_a = step({})) == null ? void 0 : _a.queue;
4450
+ if (routes[type] && routes[type].queue !== queue) {
4451
+ throw new Error(
4452
+ "Step " + type + " routes to " + routes[type].queue + " for " + routes[type].slug + " and " + queue + " for " + slug + " \u2014 one of them would be enqueued nowhere"
4453
+ );
3078
4454
  }
3079
- owners[type] = slug;
4455
+ routes[type] = { queue, slug };
3080
4456
  }
3081
4457
  }
3082
4458
  })();
@@ -3170,43 +4546,11 @@ var decrypt = (value) => {
3170
4546
  };
3171
4547
 
3172
4548
  // lib/providers.js
3173
- var FIELDS = {
3174
- attentive: [
3175
- { input: "text", key: "clientId", env: "ATTENTIVE_OAUTH_CLIENT_ID", label: "Client ID", required: true },
3176
- { input: "password", key: "clientSecret", env: "ATTENTIVE_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
3177
- ],
3178
- drawbridge: [
3179
- { input: "email", key: "accountSender", env: "SENDGRID_FROM_ADDRESS", label: "Account sender", message: "Verification codes and security alerts send from here.", required: true },
3180
- { input: "password", key: "apiKey", env: "SENDGRID_API_KEY", label: "SendGrid API key", redact: true, required: true },
3181
- // NOT required. The CRM sync is best-effort internal tooling and no-ops
3182
- // without a token — requiring it would make the whole drawbridge provider
3183
- // read not-live over something no merchant ever sees.
3184
- { input: "password", key: "hubspotToken", env: "HUBSPOT_ACCESS_TOKEN", label: "HubSpot access token", message: "Drawbridge's own CRM portal. Internal \u2014 no merchant sees this.", redact: true },
3185
- // Optional: SENDGRID_SEND_FROM_ADDRESS is not boot-required in sync
3186
- // either. Unset, it degrades to the account sender rather than
3187
- // refusing to start.
3188
- { input: "email", key: "leadSender", env: "SENDGRID_SEND_FROM_ADDRESS", label: "Lead sender", message: "The default for lead-facing mail when a merchant has not verified their own domain." },
3189
- { input: "text", key: "smsFrom", env: "TWILIO_ACCOUNT_FROM", label: "SMS number", required: true },
3190
- { input: "password", key: "smsSid", env: "TWILIO_ACCOUNT_SID", label: "Twilio account SID", redact: true, required: true },
3191
- { input: "password", key: "smsToken", env: "TWILIO_AUTH_TOKEN", label: "Twilio auth token", redact: true, required: true }
3192
- ],
3193
- klaviyo: [
3194
- { input: "text", key: "clientId", env: "KLAVIYO_OAUTH_CLIENT_ID", label: "Client ID", required: true },
3195
- { input: "password", key: "clientSecret", env: "KLAVIYO_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
3196
- ],
3197
- mailchimp: [
3198
- { input: "text", key: "clientId", env: "MAILCHIMP_OAUTH_CLIENT_ID", label: "Client ID", required: true },
3199
- { input: "password", key: "clientSecret", env: "MAILCHIMP_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
3200
- ],
3201
- shopify: [
3202
- { input: "text", key: "apiKey", env: "SHOPIFY_API_KEY", label: "API key", required: true },
3203
- { input: "password", key: "apiSecret", env: "SHOPIFY_API_SECRET", label: "API secret", redact: true, required: true },
3204
- { input: "text", key: "appHandle", env: "SHOPIFY_APP_HANDLE", label: "App handle", required: true },
3205
- { input: "text", key: "listingUrl", env: "SHOPIFY_APP_LISTING_URL", label: "App listing URL", required: true }
3206
- ]
3207
- };
3208
- var providerFields = (slug) => Object.hasOwn(FIELDS, slug) ? FIELDS[slug] : [];
3209
- var providerSlugs = () => Object.keys(FIELDS).sort();
4549
+ var providerFields = (slug) => {
4550
+ var _a;
4551
+ return Object.hasOwn(connections, slug) ? ((_a = connections[slug].provider) == null ? void 0 : _a.fields) || [] : [];
4552
+ };
4553
+ var providerSlugs = () => Object.keys(connections).filter((slug) => connections[slug].provider).sort();
3210
4554
  var isLive = (slug, settings) => {
3211
4555
  const fields2 = providerFields(slug);
3212
4556
  if (!fields2.length) return false;
@@ -3214,19 +4558,24 @@ var isLive = (slug, settings) => {
3214
4558
  };
3215
4559
  var mask = (value) => {
3216
4560
  if (!value) return null;
3217
- if (String(value).length < 12) return "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";
4561
+ if (String(value).length < 16) return "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";
3218
4562
  return String(value).slice(0, 3) + "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022" + String(value).slice(-4);
3219
4563
  };
3220
- var cacheKey = (slug) => ["provider", slug];
3221
- var providerSettings = async ({ cache, controller, slug }) => {
3222
- const read = async () => controller.get({
4564
+ var providerMemo = /* @__PURE__ */ new Map();
4565
+ var MEMO_TTL_MS = 60 * 1e3;
4566
+ var clearProviderMemo = () => providerMemo.clear();
4567
+ var providerSettings = async ({ controller, slug }) => {
4568
+ const memoized = providerMemo.get(slug);
4569
+ if (memoized && Date.now() - memoized.at < MEMO_TTL_MS) return memoized.value;
4570
+ const row = await controller.get({
3223
4571
  collection: "provider",
3224
4572
  query: { slug }
3225
4573
  });
3226
- const row = cache ? await cache.use(cacheKey(slug), read, 30) : await read();
3227
- return (row == null ? void 0 : row.settings) ? decrypt(row.settings) : {};
4574
+ const value = (row == null ? void 0 : row.settings) ? decrypt(row.settings) : {};
4575
+ providerMemo.set(slug, { at: Date.now(), value });
4576
+ return value;
3228
4577
  };
3229
- var saveProviderSettings = async ({ authenticated, cache, clear, controller, settings, slug }) => {
4578
+ var saveProviderSettings = async ({ authenticated, clear, controller, settings, slug }) => {
3230
4579
  const fields2 = providerFields(slug);
3231
4580
  if (!fields2.length) return null;
3232
4581
  const existing = await controller.get({
@@ -3254,37 +4603,35 @@ var saveProviderSettings = async ({ authenticated, cache, clear, controller, set
3254
4603
  },
3255
4604
  query: { slug }
3256
4605
  });
3257
- await cache.delete(cacheKey(slug));
4606
+ providerMemo.delete(slug);
3258
4607
  return result;
3259
4608
  };
3260
4609
  var providerEnvNames = () => new Set(
3261
- providerSlugs().flatMap((slug) => providerFields(slug)).map((field2) => field2.env).filter(Boolean)
4610
+ providerSlugs().flatMap((slug) => providerFields(slug)).map((field2) => field2.credential).filter(Boolean)
3262
4611
  );
3263
- var providerCredentials = async ({ cache, controller }) => {
4612
+ var providerCredentials = async ({ controller }) => {
3264
4613
  const credentials2 = {};
3265
4614
  for (const slug of providerSlugs()) {
3266
- const settings = await providerSettings({ cache, controller, slug });
3267
- for (const field2 of providerFields(slug)) {
3268
- const value = settings == null ? void 0 : settings[field2.key];
3269
- if (field2.env && value) credentials2[field2.env] = value;
4615
+ try {
4616
+ const settings = await providerSettings({ controller, slug });
4617
+ for (const field2 of providerFields(slug)) {
4618
+ const value = settings == null ? void 0 : settings[field2.key];
4619
+ if (field2.credential && value) credentials2[field2.credential] = value;
4620
+ }
4621
+ } catch {
4622
+ continue;
3270
4623
  }
3271
4624
  }
3272
4625
  return credentials2;
3273
4626
  };
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
4627
  export {
3281
- cacheKey,
3282
- hydrateEnvironment,
4628
+ clearProviderMemo,
3283
4629
  isLive,
3284
4630
  mask,
3285
4631
  providerCredentials,
3286
4632
  providerEnvNames,
3287
4633
  providerFields,
4634
+ providerMemo,
3288
4635
  providerSettings,
3289
4636
  providerSlugs,
3290
4637
  saveProviderSettings