@drawbridge/drawbridge-utils 0.0.176 → 0.0.177

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/admin-B9ZaLvan.d.cts +697 -0
  2. package/dist/admin-C3HtEM6h.d.ts +697 -0
  3. package/dist/billing-Bc4yo9XG.d.cts +175 -0
  4. package/dist/billing-mNsKflmQ.d.ts +175 -0
  5. package/dist/billing.d.cts +1 -1
  6. package/dist/billing.d.ts +1 -1
  7. package/dist/connections/index.cjs +3077 -228
  8. package/dist/connections/index.d.cts +13 -4
  9. package/dist/connections/index.d.ts +13 -4
  10. package/dist/connections/index.js +3107 -255
  11. package/dist/features.cjs +2940 -226
  12. package/dist/features.d.cts +13 -4
  13. package/dist/features.d.ts +13 -4
  14. package/dist/features.js +2980 -260
  15. package/dist/http.cjs +10 -1
  16. package/dist/http.d.cts +10 -1
  17. package/dist/http.d.ts +10 -1
  18. package/dist/http.js +10 -1
  19. package/dist/{index-B8JhYfvU.d.ts → index-B546oDNo.d.ts} +2837 -956
  20. package/dist/{index-qY18QITf.d.cts → index-C59xHago.d.cts} +2837 -956
  21. package/dist/oauth/index.d.cts +1 -1
  22. package/dist/oauth/index.d.ts +1 -1
  23. package/dist/oauth-BJDh0sdM.d.cts +527 -0
  24. package/dist/oauth-DveZMLHx.d.ts +527 -0
  25. package/dist/partner-BOZltuh2.d.ts +94 -0
  26. package/dist/partner-ed2OfW1J.d.cts +94 -0
  27. package/dist/plans.cjs +2939 -225
  28. package/dist/plans.d.cts +13 -4
  29. package/dist/plans.d.ts +13 -4
  30. package/dist/plans.js +2980 -260
  31. package/dist/pricing.cjs +2972 -258
  32. package/dist/pricing.d.cts +13 -4
  33. package/dist/pricing.d.ts +13 -4
  34. package/dist/pricing.js +2977 -257
  35. package/dist/providers.cjs +2942 -247
  36. package/dist/providers.d.cts +12 -3
  37. package/dist/providers.d.ts +12 -3
  38. package/dist/providers.js +2946 -245
  39. package/dist/sendgrid.cjs +10 -1
  40. package/dist/sendgrid.js +10 -1
  41. package/dist/shopify/admin.cjs +562 -0
  42. package/dist/shopify/admin.d.cts +3 -0
  43. package/dist/shopify/admin.d.ts +3 -0
  44. package/dist/shopify/admin.js +528 -0
  45. package/dist/shopify/billing.cjs +166 -0
  46. package/dist/shopify/billing.d.cts +3 -0
  47. package/dist/shopify/billing.d.ts +3 -0
  48. package/dist/shopify/billing.js +140 -0
  49. package/dist/shopify/constants.cjs +63 -0
  50. package/dist/shopify/constants.d.cts +58 -0
  51. package/dist/shopify/constants.d.ts +58 -0
  52. package/dist/shopify/constants.js +32 -0
  53. package/dist/shopify/oauth.cjs +509 -0
  54. package/dist/shopify/oauth.d.cts +7 -0
  55. package/dist/shopify/oauth.d.ts +7 -0
  56. package/dist/shopify/oauth.js +466 -0
  57. package/dist/shopify/partner.cjs +156 -0
  58. package/dist/shopify/partner.d.cts +3 -0
  59. package/dist/shopify/partner.d.ts +3 -0
  60. package/dist/shopify/partner.js +130 -0
  61. package/dist/shopify/storefront.cjs +611 -0
  62. package/dist/shopify/storefront.d.cts +3 -0
  63. package/dist/shopify/storefront.d.ts +3 -0
  64. package/dist/shopify/storefront.js +576 -0
  65. package/dist/storefront-C8FKOGeD.d.cts +659 -0
  66. package/dist/storefront-DJFGLqPl.d.ts +659 -0
  67. package/dist/twilio.cjs +10 -1
  68. package/dist/twilio.js +10 -1
  69. package/package.json +98 -68
package/dist/pricing.cjs CHANGED
@@ -469,6 +469,10 @@ var HOOKS = Object.freeze({
469
469
  "code",
470
470
  // Create the buyer at the vendor, so an order can be attributed to them.
471
471
  "customer",
472
+ // HOW MANY OF THIS PRODUCT ARE LEFT, at the vendor. Read at the moment a
473
+ // campaign's product list is rendered rather than stored, because stock is
474
+ // the one product fact that is stale the instant it is written down.
475
+ "inventory",
472
476
  // An order arrived at the vendor: attribute it, record it, update totals.
473
477
  "order",
474
478
  // Pull product data across on a vendor update.
@@ -536,7 +540,19 @@ var HOOKS = Object.freeze({
536
540
  organizations: Object.freeze(["add", "list", "remove"]),
537
541
  // What the merchant pays the VENDOR. Pairs with auth.install.billing, which
538
542
  // declares the plan they are being charged on.
539
- plan: Object.freeze(["cancel", "reselect"]),
543
+ //
544
+ // `verify` is the odd one of the three: not something a merchant does, but
545
+ // the question "is this store's billing actually metered right now". It is
546
+ // here because it is the same subject — and because the answer was being
547
+ // derived in TWO places, the vendor's health check and drawbridge-sync's
548
+ // approval webhook, whose copy said in its own comment that it matched the
549
+ // other and did not.
550
+ // `charge` and `verify` are the two that are not merchant actions: one
551
+ // sends a usage charge to the vendor's meter, the other asks whether that
552
+ // meter is actually working. Both are here because both are the same
553
+ // subject — what the merchant pays the vendor — and both were being done
554
+ // from drawbridge-sync with a direct import of the vendor's client.
555
+ plan: Object.freeze(["cancel", "charge", "reselect", "verify"]),
540
556
  // The embedded app's own session, stored by us on the vendor's behalf.
541
557
  session: Object.freeze(["clear", "read", "save"]),
542
558
  // The one-time code that hands a merchant from the embedded app into
@@ -621,7 +637,7 @@ var ANSWER_KEYS = Object.freeze([
621
637
  "usage"
622
638
  ].sort());
623
639
  var WRITE_OPERATIONS = Object.freeze(["create", "delete", "update"]);
624
- var INSTALL_SIGNATURE = Object.freeze({ options: ["read", "request"], props: ["context"] });
640
+ var INSTALL_SIGNATURE = Object.freeze({ options: ["read"], props: ["context"] });
625
641
  var LIFECYCLE_SIGNATURE = Object.freeze({ options: ["dispatch"], props: ["context"] });
626
642
  var RESOURCE_SIGNATURE = Object.freeze({
627
643
  options: ["fetcher", "shopify"],
@@ -638,15 +654,30 @@ var HOOK_SLOT_PROPS = Object.freeze({
638
654
  // the second bag would be silently discarded, which is exactly the
639
655
  // stubbed-fetcher-reaches-production failure the split exists to prevent.
640
656
  "auth.token": false,
641
- // COMMERCE. `cart` is declared and unimplemented the Checkout Kit path in
642
- // api/route/subdomain.js writes nothing, which is why it never became a hook
643
- // so its signature mirrors `code`, its nearest sibling, and moving the
644
- // route here is a deliberate widening of this line rather than a silent one.
645
- "commerce.cart": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context", "step"] }),
657
+ // COMMERCE. `cart` is the odd one: it runs for a SHOPPER on a public page,
658
+ // not for an organization inside a workflow, so it takes no `connection` and
659
+ // no `step`. It reads the storefront with the store's own storefront token
660
+ // and mints a checkout token from DRAWBRIDGE'S app credentials, which is why
661
+ // `clientId`/`clientSecret` are here as props, the way auth.disconnect
662
+ // already carries them, because a credential is a fact of the run rather
663
+ // than a service.
664
+ "commerce.cart": Object.freeze({
665
+ options: ["fetcher", "shopify"],
666
+ props: ["clientId", "clientSecret", "context", "settings"]
667
+ }),
646
668
  "commerce.code": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context", "step"] }),
647
669
  "commerce.customer": Object.freeze({ options: ["adminToken", "read", "shopify"], props: ["connection", "context"] }),
670
+ "commerce.inventory": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context"] }),
648
671
  "commerce.order": Object.freeze({ options: ["conversionRate", "logger", "mintId", "read"], props: ["connection", "context"] }),
649
- "commerce.product": Object.freeze({ options: ["mintId", "read"], props: ["connection", "context", "workflow"] }),
672
+ // THREE OPERATIONS, one slot — record, sync, variants. `settings` and
673
+ // `adminToken` arrived with the pull half: the storefront read needs the
674
+ // store's storefront token and the product-feedback send needs its admin one,
675
+ // and both are resolved by the caller because minting either needs a
676
+ // controller.
677
+ "commerce.product": Object.freeze({
678
+ options: ["adminToken", "mintId", "read", "shopify"],
679
+ props: ["connection", "context", "settings", "workflow"]
680
+ }),
650
681
  // THE ADDRESS IS `contact` IN BOTH, and the shell already says why: it is the
651
682
  // person, not the lead document. `remove` called it `email` and `sync` called
652
683
  // it `doc` on one vendor and `lead` on three — three names for two facts.
@@ -659,19 +690,58 @@ var HOOK_SLOT_PROPS = Object.freeze({
659
690
  "inbound.process": Object.freeze({ options: ["dispatch"], props: ["context"] }),
660
691
  "inbound.receive": Object.freeze({ options: [], props: ["channel", "event", "headers", "payload"] }),
661
692
  "inbound.verify": Object.freeze({ options: [], props: ["body", "channel", "headers", "secret", "url"] }),
662
- // INSTALL — thirteen slots, none implemented yet. They are what the thirteen
663
- // routes in api/route/shopify-embedded.js become, and the signature is
664
- // deliberately narrow: `context` is the request's own body, `read` and
665
- // `request` are the only services an install surface has been shown to need.
666
- // A route that cannot be expressed inside this line is a finding to bring
667
- // back here, not a name to add at the call site.
693
+ // INSTALL — thirteen slots, and they are the thirteen routes that used to be
694
+ // api/route/shopify-embedded.js. `context` is the request's own body in all
695
+ // of them; the options are where they differ, and every difference below was
696
+ // forced by a line in those routes rather than chosen.
697
+ //
698
+ // SEVEN NEED NOTHING BUT `read`. The two session slots that write, the two
699
+ // token slots that write, the two clears, and both account slots answer from
700
+ // the shared install record alone.
701
+ //
702
+ // SIX TAKE MORE, and the widenings are worth naming because each is a fact
703
+ // Drawbridge owns that the manifest must not:
704
+ //
705
+ // conversionRate, planTitle what Drawbridge charges this organization.
706
+ // The org list renders both, and importing the
707
+ // plan catalogue here is the cycle
708
+ // features -> connections -> shopify -> plans
709
+ // -> features that was just broken.
710
+ // currencies which settlement currencies Drawbridge can
711
+ // bill. A store outside them fails the
712
+ // connection validator INSIDE the transaction,
713
+ // which surfaces as an opaque 500, so `add`
714
+ // checks first and says so.
715
+ // mintId the connection's id, known before the write
716
+ // that creates it, because the organization's
717
+ // own refs have to name it in the same
718
+ // transaction.
719
+ // shopify the vendor. Four slots call the store: two
720
+ // read the live plan, two release it.
721
+ // mark THE ONE WRITE A DESCRIPTION CANNOT CARRY, and
722
+ // `reselect` is the only slot with one. See its
723
+ // implementation for why the order is the point.
668
724
  "install.account.link": INSTALL_SIGNATURE,
669
725
  "install.account.unlink": INSTALL_SIGNATURE,
670
- "install.organizations.add": INSTALL_SIGNATURE,
671
- "install.organizations.list": INSTALL_SIGNATURE,
726
+ "install.organizations.add": Object.freeze({
727
+ options: ["currencies", "mintId", "read", "shopify"],
728
+ props: ["context"]
729
+ }),
730
+ "install.organizations.list": Object.freeze({
731
+ options: ["conversionRate", "planTitle", "read", "shopify"],
732
+ props: ["context"]
733
+ }),
672
734
  "install.organizations.remove": INSTALL_SIGNATURE,
673
- "install.plan.cancel": INSTALL_SIGNATURE,
674
- "install.plan.reselect": INSTALL_SIGNATURE,
735
+ "install.plan.cancel": Object.freeze({ options: ["read", "shopify"], props: ["context"] }),
736
+ // `manifest` because the handle this charge bills under is the vendor's own
737
+ // declaration (auth.install.billing.handle), and checking the job against the
738
+ // declaration is what the enqueuer-checks-itself version could not do.
739
+ "install.plan.charge": Object.freeze({
740
+ options: ["shopify"],
741
+ props: ["clientId", "clientSecret", "context", "manifest"]
742
+ }),
743
+ "install.plan.reselect": Object.freeze({ options: ["mark", "read", "shopify"], props: ["context"] }),
744
+ "install.plan.verify": Object.freeze({ options: ["adminToken", "read", "shopify"], props: ["context"] }),
675
745
  "install.session.clear": INSTALL_SIGNATURE,
676
746
  "install.session.read": INSTALL_SIGNATURE,
677
747
  "install.session.save": INSTALL_SIGNATURE,
@@ -830,6 +900,52 @@ var ERROR_SOURCES = Object.freeze({
830
900
  "shopify.register.webhooks": true
831
901
  });
832
902
 
903
+ // lib/encrypt.js
904
+ var import_crypto2 = __toESM(require("crypto"), 1);
905
+
906
+ // lib/token.js
907
+ var import_crypto = __toESM(require("crypto"), 1);
908
+ var generate = (bytes = 32, encoding = "base64url") => {
909
+ const buf = import_crypto.default.randomBytes(bytes);
910
+ return encoding ? buf.toString(encoding) : buf;
911
+ };
912
+ var hash = (value, key) => {
913
+ if (!value) return null;
914
+ if (key) {
915
+ return import_crypto.default.createHmac("sha256", key).update(String(value)).digest("base64url");
916
+ }
917
+ return import_crypto.default.createHash("sha256").update(String(value)).digest("base64url");
918
+ };
919
+
920
+ // lib/encrypt.js
921
+ var ALGORITHM = "aes-256-gcm";
922
+ var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
923
+ var encrypt = (value) => {
924
+ const iv = generate(12, null);
925
+ const cipher = import_crypto2.default.createCipheriv(ALGORITHM, getKey(), iv);
926
+ const data2 = Buffer.concat([
927
+ cipher.update(JSON.stringify(value), "utf8"),
928
+ cipher.final()
929
+ ]);
930
+ const tag = cipher.getAuthTag();
931
+ return [iv, tag, data2].map((b) => b.toString("hex")).join(":");
932
+ };
933
+ var decrypt = (value) => {
934
+ if (typeof value !== "string") return value;
935
+ const [ivHex, tagHex, dataHex] = value.split(":");
936
+ const decipher = import_crypto2.default.createDecipheriv(
937
+ ALGORITHM,
938
+ getKey(),
939
+ Buffer.from(ivHex, "hex")
940
+ );
941
+ decipher.setAuthTag(Buffer.from(tagHex, "hex"));
942
+ const result = Buffer.concat([
943
+ decipher.update(Buffer.from(dataHex, "hex")),
944
+ decipher.final()
945
+ ]);
946
+ return JSON.parse(result.toString("utf8"));
947
+ };
948
+
833
949
  // lib/connections/oauth.js
834
950
  var import_node_crypto = require("crypto");
835
951
  var credentials = ({ basic, clientId, clientSecret }) => basic ? {
@@ -856,10 +972,10 @@ var authToken = async ({
856
972
  const renewing = !code2;
857
973
  if (renewing && !refreshToken) throw new Error("Nothing has been consented to yet, so there is no refresh token to spend");
858
974
  if (!renewing && descriptor.pkce && !verifier) throw new Error("This connection requires PKCE, so the code verifier is not optional");
859
- const client = credentials({ basic, clientId, clientSecret });
975
+ const client2 = credentials({ basic, clientId, clientSecret });
860
976
  const response = await fetcher(descriptor.endpoints.token, {
861
977
  body: new URLSearchParams({
862
- ...client.body,
978
+ ...client2.body,
863
979
  ...renewing ? { grant_type: "refresh_token", refresh_token: refreshToken } : {
864
980
  code: decodeURIComponent(String(code2 || "").trim()),
865
981
  grant_type: "authorization_code",
@@ -867,7 +983,7 @@ var authToken = async ({
867
983
  ...descriptor.pkce && { code_verifier: verifier }
868
984
  }
869
985
  }),
870
- headers: { "content-type": "application/x-www-form-urlencoded", ...client.headers },
986
+ headers: { "content-type": "application/x-www-form-urlencoded", ...client2.headers },
871
987
  method: "POST",
872
988
  signal: AbortSignal.timeout(15e3)
873
989
  });
@@ -1262,9 +1378,18 @@ var scaffold_default = {
1262
1378
  commerce: {
1263
1379
  // NEW in phase 1 — the Checkout Kit cart path, which writes nothing and is
1264
1380
  // the last api surface Shopify owns outside a hook.
1265
- cart: async ({ connection: connection2, context }, { read } = {}) => ANSWER,
1381
+ // NO `connection` AND NO `step`: this one runs for a SHOPPER on a public
1382
+ // page, not for an organization inside a workflow. It reads the storefront
1383
+ // with the store's storefront token and mints a checkout token from
1384
+ // DRAWBRIDGE'S app credentials, which is why the credential pair rides in
1385
+ // as props — the way auth.disconnect already carries it.
1386
+ cart: async ({ clientId, clientSecret, context, settings }, { fetcher, shopify } = {}) => ANSWER,
1266
1387
  code: async ({ connection: connection2, context, step }, { adminToken, shopify } = {}) => ANSWER,
1267
1388
  customer: async ({ connection: connection2, context }, { adminToken, read, shopify } = {}) => ANSWER,
1389
+ // STOCK, READ AT RENDER TIME rather than stored. It is the one product
1390
+ // fact that is stale the instant it is written down, so the campaign
1391
+ // product list asks the vendor and caches the answer for a minute.
1392
+ inventory: async ({ connection: connection2, context }, { adminToken, shopify } = {}) => ANSWER,
1268
1393
  order: async ({ connection: connection2, context }, { logger: logger2, mintId, read } = {}) => ANSWER,
1269
1394
  // THIS IS WHERE `product.insert` LANDS.
1270
1395
  //
@@ -1286,7 +1411,7 @@ var scaffold_default = {
1286
1411
  // nothing and shows up only as `workflow.dispatch.candidates matched : 0` in
1287
1412
  // a log. Phase 1 closes it and build() checks every trigger against it.
1288
1413
  product: {
1289
- hook: async ({ connection: connection2, context, workflow }, { mintId, read } = {}) => ANSWER,
1414
+ hook: async ({ connection: connection2, context, settings, workflow }, { adminToken, mintId, read, shopify } = {}) => ANSWER,
1290
1415
  step: () => ({
1291
1416
  description: "Syncs product data from the vendor when a product changes.",
1292
1417
  key: "Vendor Product Sync",
@@ -1434,8 +1559,19 @@ var scaffold_default = {
1434
1559
  // Vendor billing, the only group that is not generic. Pairs with
1435
1560
  // auth.install.billing, which declares what the merchant is being charged.
1436
1561
  plan: {
1437
- cancel: async ({ context }, { dispatch, read } = {}) => ANSWER,
1438
- reselect: async ({ context }, { dispatch, read } = {}) => ANSWER
1562
+ cancel: async ({ context }, { read, shopify } = {}) => ANSWER,
1563
+ // NOT A MERCHANT ACTION EITHER one attributed order's usage charge,
1564
+ // sent to the vendor's meter. The credential pair rides in as props
1565
+ // because the charge authenticates as the APP, not as the store.
1566
+ charge: async ({ clientId, clientSecret, context, manifest }, { shopify } = {}) => ANSWER,
1567
+ // `mark` is the one write a description cannot carry: the marker must
1568
+ // be persisted BEFORE the approval is released, and a described write
1569
+ // lands after the hook returns.
1570
+ reselect: async ({ context }, { mark, read, shopify } = {}) => ANSWER,
1571
+ // NOT A MERCHANT ACTION — the question "is this store's billing
1572
+ // actually metered right now", asked by the daily health check and by
1573
+ // the vendor's own approval webhook, which used to hand-copy it.
1574
+ verify: async ({ context }, { adminToken, read, shopify } = {}) => ANSWER
1439
1575
  },
1440
1576
  // The embedded app's own session, stored by us on the vendor's behalf.
1441
1577
  session: {
@@ -1921,16 +2057,19 @@ var attentive_default2 = {
1921
2057
  "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.",
1922
2058
  "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."
1923
2059
  ],
1924
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
1925
- // The dashboard already carries generic reasons for every way an
1926
- // authorization can fail — declined, expired state, a vendor we are not set
1927
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
1928
- // failures need saying differently. This one's do not.
2060
+ // WHAT THE MERCHANT READS WHEN A CONNECT FAILS. Two states, because the
2061
+ // consent screen has two ways to end: they said no, or something between
2062
+ // here and the vendor went wrong.
1929
2063
  //
1930
- // Answered rather than omitted, because `errors` existed on two of six
1931
- // manifests and there was no way to tell "nothing to add" from "nobody
1932
- // wrote it".
1933
- errors: false,
2064
+ // THE VENDOR IS NAMED IN BOTH. The dashboard's generic copy says "the
2065
+ // authorization"; a merchant connecting two accounts in one sitting needs
2066
+ // to know which one this was.
2067
+ errors: {
2068
+ connect: {
2069
+ denied: "The Attentive authorization was declined, so nothing was connected.",
2070
+ invalid: "We couldn't complete the Attentive connection. Try connecting again."
2071
+ }
2072
+ },
1934
2073
  excerpt: "Sync your Drawbridge contacts into an Attentive segment.",
1935
2074
  // NAMES THE SEGMENT STEP, because `status` below gates on it: a grant with
1936
2075
  // no segment chosen sits at Pending, and a guide that stops at the consent
@@ -2458,6 +2597,15 @@ var readEventHeader = ({ descriptor, headers }) => ({ result: { event: headers[d
2458
2597
  var DEFAULT_TIMEOUT_MS = 15e3;
2459
2598
  var request = async ({
2460
2599
  body,
2600
+ // THE TRANSPORT, injectable and defaulted to the real one.
2601
+ //
2602
+ // Every other vendor client in this package takes a `fetcher` — it is how
2603
+ // klaviyo, mailchimp and attentive are tested without a network, and it is a
2604
+ // declared HOOK_OPTION. The Shopify client had no seam at all, so the only way
2605
+ // to test a hook that used it was to inject the whole SDK namespace; that
2606
+ // injection existed to work around an import cycle, and when the cycle went
2607
+ // the tests lost their only hold. This is the seam they should have had.
2608
+ fetcher = fetch,
2461
2609
  headers = {},
2462
2610
  method = "GET",
2463
2611
  query,
@@ -2471,7 +2619,7 @@ var request = async ({
2471
2619
  }
2472
2620
  ;
2473
2621
  const isForm = type === "form";
2474
- const response = await fetch(fullUrl.toString(), {
2622
+ const response = await fetcher(fullUrl.toString(), {
2475
2623
  method,
2476
2624
  headers: {
2477
2625
  "Content-Type": isForm ? "application/x-www-form-urlencoded" : "application/json",
@@ -2913,15 +3061,12 @@ var drawbridge_default2 = {
2913
3061
  description: [
2914
3062
  "Drawbridge sends your notification emails and your entrants' emails, and recalculates segment membership on a schedule. It is always on and needs nothing connected."
2915
3063
  ],
2916
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
2917
- // The dashboard already carries generic reasons for every way an
2918
- // authorization can fail declined, expired state, a vendor we are not set
2919
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
2920
- // failures need saying differently. This one's do not.
3064
+ // NOTHING IS EVER CONNECTED, so no connect can fail. This is the platform's
3065
+ // own manifest always on, private, never in the catalogue — and it exists
3066
+ // to give Drawbridge's own steps a hook to point at. `denied` and `invalid`
3067
+ // describe a consent screen this connection does not have.
2921
3068
  //
2922
- // Answered rather than omitted, because `errors` existed on two of six
2923
- // manifests and there was no way to tell "nothing to add" from "nobody
2924
- // wrote it".
3069
+ // `false` is the recorded decision, not silence.
2925
3070
  errors: false,
2926
3071
  excerpt: "The steps Drawbridge runs itself.",
2927
3072
  guide: [
@@ -3681,10 +3826,10 @@ var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
3681
3826
 
3682
3827
  // lib/connections/scopes.js
3683
3828
  var list = (value) => (Array.isArray(value) ? value.flatMap((entry) => String(entry).split(/\s+/)) : String(value ?? "").split(/\s+/)).map((entry) => entry.trim()).filter(Boolean);
3684
- var missingScopes = ({ granted, required }) => {
3829
+ var missingScopes = ({ granted, required: required2 }) => {
3685
3830
  if (granted === null || granted === void 0 || granted === "") return null;
3686
3831
  const held = new Set(list(granted));
3687
- return list(required).filter((scope) => !held.has(scope));
3832
+ return list(required2).filter((scope) => !held.has(scope));
3688
3833
  };
3689
3834
 
3690
3835
  // lib/connections/manifests/klaviyo.js
@@ -4583,16 +4728,19 @@ var mailchimp_default2 = {
4583
4728
  "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.",
4584
4729
  "Someone who unsubscribed inside Mailchimp keeps that choice: a resync only sets the status of a subscriber Mailchimp has never seen before."
4585
4730
  ],
4586
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
4587
- // The dashboard already carries generic reasons for every way an
4588
- // authorization can fail — declined, expired state, a vendor we are not set
4589
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
4590
- // failures need saying differently. This one's do not.
4731
+ // WHAT THE MERCHANT READS WHEN A CONNECT FAILS. Two states, because the
4732
+ // consent screen has two ways to end: they said no, or something between
4733
+ // here and the vendor went wrong.
4591
4734
  //
4592
- // Answered rather than omitted, because `errors` existed on two of six
4593
- // manifests and there was no way to tell "nothing to add" from "nobody
4594
- // wrote it".
4595
- errors: false,
4735
+ // THE VENDOR IS NAMED IN BOTH. The dashboard's generic copy says "the
4736
+ // authorization"; a merchant connecting two accounts in one sitting needs
4737
+ // to know which one this was.
4738
+ errors: {
4739
+ connect: {
4740
+ denied: "The Mailchimp authorization was declined, so nothing was connected.",
4741
+ invalid: "We couldn't complete the Mailchimp connection. Try connecting again."
4742
+ }
4743
+ },
4596
4744
  excerpt: "Sync your Drawbridge contacts into a Mailchimp audience.",
4597
4745
  // NAMES THE AUDIENCE STEP, because `status` below gates on it: a grant with
4598
4746
  // no audience chosen sits at Pending, and a guide that stops at the consent
@@ -4691,7 +4839,7 @@ var mailchimp_default2 = {
4691
4839
  if (!audience) return { message: "No Mailchimp audience is chosen for this connection.", request: request2, skipped: true };
4692
4840
  const email = ((_d = (_c = lead == null ? void 0 : lead.canonical) == null ? void 0 : _c.email) == null ? void 0 : _d.value) || (lead == null ? void 0 : lead.email);
4693
4841
  if (!email) return { message: "That lead has no email address to sync.", request: request2, skipped: true };
4694
- const hash = subscriberHash(email);
4842
+ const hash2 = subscriberHash(email);
4695
4843
  const [firstName, ...restOfName] = String((lead == null ? void 0 : lead.name) || "").trim().split(/\s+/).filter(Boolean);
4696
4844
  const lastName = restOfName.join(" ");
4697
4845
  const phone = ((_e = lead == null ? void 0 : lead.phone) == null ? void 0 : _e.number) || null;
@@ -4700,7 +4848,7 @@ var mailchimp_default2 = {
4700
4848
  ...lastName && { LNAME: lastName },
4701
4849
  ...phone && { PHONE: phone }
4702
4850
  };
4703
- const member = await api3("/lists/" + audience + "/members/" + hash, {
4851
+ const member = await api3("/lists/" + audience + "/members/" + hash2, {
4704
4852
  dc: settings == null ? void 0 : settings.dc,
4705
4853
  fetcher,
4706
4854
  method: "PUT",
@@ -4741,7 +4889,7 @@ var mailchimp_default2 = {
4741
4889
  status: joined.has(entry.id) ? "active" : "inactive"
4742
4890
  }));
4743
4891
  if (tags.length > 0) {
4744
- await api3("/lists/" + audience + "/members/" + hash + "/tags", {
4892
+ await api3("/lists/" + audience + "/members/" + hash2 + "/tags", {
4745
4893
  dc: settings == null ? void 0 : settings.dc,
4746
4894
  fetcher,
4747
4895
  method: "POST",
@@ -4752,12 +4900,12 @@ var mailchimp_default2 = {
4752
4900
  }
4753
4901
  return {
4754
4902
  // Merged into `context` for later steps in this run.
4755
- context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash },
4903
+ context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash2 },
4756
4904
  message: suppressed ? "Synced to Mailchimp as unsubscribed \u2014 this contact has opted out." : "Synced to the Mailchimp audience.",
4757
4905
  request: request2,
4758
4906
  // Recorded on the run for support to read back, not a write
4759
4907
  // instruction — the hook has already written what it needed to.
4760
- response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash }
4908
+ response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash2 }
4761
4909
  };
4762
4910
  }
4763
4911
  },
@@ -5127,167 +5275,2058 @@ var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
5127
5275
  <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"/>
5128
5276
  </svg>`;
5129
5277
 
5130
- // lib/email.js
5131
- var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
5132
- var toCanonicalEmail = (value) => {
5133
- if (!value || typeof value !== "string") return null;
5134
- const email = value.trim().toLowerCase();
5135
- const at = email.lastIndexOf("@");
5136
- if (at < 1 || at === email.length - 1) return null;
5137
- let local = email.slice(0, at);
5138
- const domain = email.slice(at + 1);
5139
- const plus = local.indexOf("+");
5140
- if (plus > 0) local = local.slice(0, plus);
5141
- if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
5142
- if (!local) return null;
5143
- return local + "@" + domain;
5144
- };
5278
+ // lib/shopify/admin.js
5279
+ var admin_exports = {};
5280
+ __export(admin_exports, {
5281
+ adminFetch: () => adminFetch,
5282
+ createDiscountCode: () => createDiscountCode,
5283
+ createUsageRecord: () => createUsageRecord,
5284
+ createUsageSubscription: () => createUsageSubscription,
5285
+ getActiveAppSubscriptions: () => getActiveAppSubscriptions,
5286
+ getDiscounts: () => getDiscounts,
5287
+ getOrCreateCustomer: () => getOrCreateCustomer,
5288
+ getProductInventory: () => getProductInventory,
5289
+ sendProductResourceFeedback: () => sendProductResourceFeedback
5290
+ });
5145
5291
 
5146
- // lib/encrypt.js
5147
- var import_crypto = __toESM(require("crypto"), 1);
5148
- var ALGORITHM = "aes-256-gcm";
5149
- var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
5150
- var decrypt = (value) => {
5151
- if (typeof value !== "string") return value;
5152
- const [ivHex, tagHex, dataHex] = value.split(":");
5153
- const decipher = import_crypto.default.createDecipheriv(
5154
- ALGORITHM,
5155
- getKey(),
5156
- Buffer.from(ivHex, "hex")
5157
- );
5158
- decipher.setAuthTag(Buffer.from(tagHex, "hex"));
5159
- const result = Buffer.concat([
5160
- decipher.update(Buffer.from(dataHex, "hex")),
5161
- decipher.final()
5162
- ]);
5163
- return JSON.parse(result.toString("utf8"));
5164
- };
5292
+ // lib/shopify/constants.js
5293
+ var SHOPIFY_STOREFRONT_API_VERSION = "2025-01";
5294
+ var SHOPIFY_ADMIN_API_VERSION = "2026-04";
5295
+ var SHOPIFY_APP_API_VERSION = "unstable";
5296
+ var SHOPIFY_REQUIRED_SCOPES = [
5297
+ "read_customers",
5298
+ "write_customers",
5299
+ "read_discounts",
5300
+ "write_discounts",
5301
+ "read_orders",
5302
+ "read_products",
5303
+ "read_publications",
5304
+ "write_resource_feedbacks",
5305
+ "unauthenticated_read_checkouts",
5306
+ "unauthenticated_read_product_inventory",
5307
+ "unauthenticated_read_product_listings",
5308
+ "unauthenticated_write_checkouts"
5309
+ ];
5310
+ var REFRESH_TOKEN_LIFETIME_MS = 90 * 24 * 60 * 60 * 1e3;
5311
+ var ACCESS_TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1e3;
5312
+ var PARTNER_API_VERSION = process.env.SHOPIFY_PARTNER_API_VERSION || "2026-07";
5165
5313
 
5166
- // lib/slugify.js
5167
- var import_slugify = __toESM(require("slugify"), 1);
5168
- var slugify = (value, nochars = false) => {
5169
- const remove = nochars ? /[-?*+~.()'"!:@#^_{}\[\];,/\\]/g : /[?*+~.()'"!:@#^_{}\[\];,/\\]/g;
5170
- const replacement = nochars ? "" : "-";
5171
- return (0, import_slugify.default)(
5172
- value,
5173
- {
5174
- remove,
5175
- replacement,
5176
- lower: true,
5177
- trim: true
5314
+ // lib/shopify/admin.js
5315
+ var adminUrl = (domain) => `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}`;
5316
+ var adminFetch = async ({ adminAccessToken, domain, fetcher, query, variables }) => {
5317
+ var _a;
5318
+ const { data: data2, errors } = await request({
5319
+ fetcher,
5320
+ method: "POST",
5321
+ url: adminUrl(domain) + "/graphql.json",
5322
+ headers: {
5323
+ "X-Shopify-Access-Token": adminAccessToken
5324
+ },
5325
+ body: {
5326
+ query,
5327
+ ...variables && { variables }
5178
5328
  }
5179
- );
5329
+ });
5330
+ if (errors) {
5331
+ throw new Error("Shopify GraphQL error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
5332
+ }
5333
+ ;
5334
+ return data2;
5180
5335
  };
5181
-
5182
- // lib/connections/manifests/shopify.js
5183
- var toLine = ({
5184
- price,
5185
- product_id: productId,
5186
- quantity,
5187
- title,
5188
- variant_id: variantId,
5189
- variant_title: variantTitle
5190
- }) => ({
5191
- price: parseFloat(price) || 0,
5192
- productId: productId ? "gid://shopify/Product/" + productId : null,
5193
- quantity: quantity || 1,
5194
- title: title || null,
5195
- variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
5196
- variantTitle: variantTitle || null
5197
- });
5198
- var attributeLineItems = (lineItems = []) => lineItems.reduce(
5199
- (acc, item) => {
5200
- const attrs = (item.properties || []).reduce(
5201
- (map, { name, value }) => {
5202
- map[name] = value;
5203
- return map;
5204
- },
5205
- {}
5206
- );
5207
- if (!attrs["_drwbrdg_ca"]) return acc;
5208
- if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
5209
- const line = toLine(item);
5210
- acc.attributedGross += line.price * line.quantity;
5211
- acc.attributedLines.push(line);
5212
- return acc;
5213
- },
5214
- { attrMap: {}, attributedGross: 0, attributedLines: [] }
5215
- );
5216
- var generateDiscountCode = (0, import_nanoid.customAlphabet)("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
5217
- var blockedReason = (discount) => {
5218
- var _a;
5219
- if ((discount == null ? void 0 : discount.status) === "EXPIRED") return "This discount has expired.";
5220
- const buyers = (_a = discount == null ? void 0 : discount.context) == null ? void 0 : _a.__typename;
5221
- if (buyers && buyers !== "DiscountBuyerSelectionAll") {
5222
- return "This discount is limited to specific buyers in Shopify, so a code issued to an entrant won't work. Set it to all customers to use it here.";
5336
+ var DISCOUNT_FIELDS = `
5337
+ title
5338
+ status
5339
+ startsAt
5340
+ endsAt
5341
+ usageLimit
5342
+ asyncUsageCount
5343
+ appliesOncePerCustomer
5344
+ context { __typename }
5345
+ `;
5346
+ var discountsQuery = (search, cursor, limit) => `{
5347
+ codeDiscountNodes(first: ${limit}${search ? `, query: "title:*${search}*"` : ""}${cursor ? `, after: "${cursor}"` : ""}) {
5348
+ edges {
5349
+ node {
5350
+ id
5351
+ codeDiscount {
5352
+ ... on DiscountCodeBasic { ${DISCOUNT_FIELDS} }
5353
+ ... on DiscountCodeBxgy { ${DISCOUNT_FIELDS} }
5354
+ ... on DiscountCodeFreeShipping { ${DISCOUNT_FIELDS} }
5355
+ ... on DiscountCodeApp { ${DISCOUNT_FIELDS} }
5356
+ }
5357
+ }
5358
+ }
5359
+ pageInfo {
5360
+ endCursor
5361
+ hasNextPage
5362
+ hasPreviousPage
5363
+ startCursor
5364
+ }
5365
+ }
5366
+ }`;
5367
+ var getDiscounts = async ({ fetcher, adminAccessToken, domain, search, cursor, limit }) => {
5368
+ const data2 = await adminFetch({
5369
+ fetcher,
5370
+ adminAccessToken,
5371
+ domain,
5372
+ query: discountsQuery(search, cursor, limit)
5373
+ });
5374
+ return data2 == null ? void 0 : data2.codeDiscountNodes;
5375
+ };
5376
+ var discountGid = (id) => String(id).startsWith("gid://") ? String(id) : "gid://shopify/DiscountCodeNode/" + id;
5377
+ var createDiscountCode = async ({ fetcher, adminAccessToken, domain, discountId, code: code2 }) => {
5378
+ var _a, _b, _c, _d, _e, _f, _g, _h;
5379
+ const added = await adminFetch({
5380
+ fetcher,
5381
+ adminAccessToken,
5382
+ domain,
5383
+ query: `
5384
+ mutation DiscountRedeemCodeBulkAdd($discountId: ID!, $codes: [DiscountRedeemCodeInput!]!) {
5385
+ discountRedeemCodeBulkAdd(discountId: $discountId, codes: $codes) {
5386
+ bulkCreation {
5387
+ id
5388
+ }
5389
+ userErrors {
5390
+ field
5391
+ message
5392
+ }
5393
+ }
5394
+ }
5395
+ `,
5396
+ variables: {
5397
+ codes: [{ code: code2 }],
5398
+ discountId: discountGid(discountId)
5399
+ }
5400
+ });
5401
+ const addErrors = (_a = added == null ? void 0 : added.discountRedeemCodeBulkAdd) == null ? void 0 : _a.userErrors;
5402
+ if (addErrors == null ? void 0 : addErrors.length) {
5403
+ throw new Error("Shopify discount code create failed: " + addErrors[0].message);
5223
5404
  }
5224
5405
  ;
5225
- if (typeof (discount == null ? void 0 : discount.usageLimit) === "number" && discount.usageLimit > 0 && ((discount == null ? void 0 : discount.asyncUsageCount) || 0) >= discount.usageLimit) {
5226
- return "This discount has reached its total usage limit.";
5406
+ const bulkCreationId = (_c = (_b = added == null ? void 0 : added.discountRedeemCodeBulkAdd) == null ? void 0 : _b.bulkCreation) == null ? void 0 : _c.id;
5407
+ if (!bulkCreationId) {
5408
+ throw new Error("Shopify discount code create failed: no bulk creation id returned");
5227
5409
  }
5228
5410
  ;
5229
- return null;
5411
+ for (let attempt = 0; attempt < 15; attempt++) {
5412
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
5413
+ const polled = await adminFetch({
5414
+ fetcher,
5415
+ adminAccessToken,
5416
+ domain,
5417
+ query: `
5418
+ query DiscountRedeemCodeBulkCreationPoll($id: ID!) {
5419
+ discountRedeemCodeBulkCreation(id: $id) {
5420
+ done
5421
+ codes(first: 1) {
5422
+ nodes {
5423
+ code
5424
+ discountRedeemCode {
5425
+ id
5426
+ }
5427
+ errors {
5428
+ message
5429
+ }
5430
+ }
5431
+ }
5432
+ }
5433
+ }
5434
+ `,
5435
+ variables: {
5436
+ id: bulkCreationId
5437
+ }
5438
+ });
5439
+ const creation = polled == null ? void 0 : polled.discountRedeemCodeBulkCreation;
5440
+ if (!(creation == null ? void 0 : creation.done)) continue;
5441
+ const node = (_e = (_d = creation.codes) == null ? void 0 : _d.nodes) == null ? void 0 : _e[0];
5442
+ if (!((_f = node == null ? void 0 : node.discountRedeemCode) == null ? void 0 : _f.id)) {
5443
+ throw new Error("Shopify discount code create failed: " + (((_h = (_g = node == null ? void 0 : node.errors) == null ? void 0 : _g[0]) == null ? void 0 : _h.message) || "code was not created"));
5444
+ }
5445
+ ;
5446
+ return {
5447
+ code: node.code,
5448
+ // Numeric tail keeps the stored shopifyDiscountId in the shape the
5449
+ // legacy REST endpoint returned — it feeds a merchant-visible
5450
+ // workflow template variable, so no gid:// leakage.
5451
+ id: node.discountRedeemCode.id.split("/").pop()
5452
+ };
5453
+ }
5454
+ ;
5455
+ throw new Error("Shopify discount code create timed out waiting for bulk creation " + bulkCreationId);
5230
5456
  };
5231
- var discountWarning = (discount) => {
5232
- if ((discount == null ? void 0 : discount.status) === "SCHEDULED") {
5233
- return "This discount hasn't started yet, so codes issued before it does won't work until then.";
5457
+ var getOrCreateCustomer = async ({ fetcher, adminAccessToken, domain, email, firstName, lastName, source }) => {
5458
+ var _a, _b, _c, _d, _e, _f, _g, _h;
5459
+ const lookupQuery = `
5460
+ query customerByEmail( $query : String! ) {
5461
+ customers( first : 1, query : $query ) {
5462
+ edges {
5463
+ node {
5464
+ id
5465
+ }
5466
+ }
5467
+ }
5468
+ }
5469
+ `;
5470
+ const data2 = await adminFetch({
5471
+ fetcher,
5472
+ adminAccessToken,
5473
+ domain,
5474
+ query: lookupQuery,
5475
+ variables: { query: "email:" + email }
5476
+ });
5477
+ const existing = (_c = (_b = (_a = data2 == null ? void 0 : data2.customers) == null ? void 0 : _a.edges) == null ? void 0 : _b[0]) == null ? void 0 : _c.node;
5478
+ if (existing) return existing;
5479
+ const input = { email };
5480
+ if (firstName) input.firstName = firstName;
5481
+ if (lastName) input.lastName = lastName;
5482
+ if (source) {
5483
+ input.metafields = [{
5484
+ namespace: "drwbrdg",
5485
+ key: "source",
5486
+ type: "single_line_text_field",
5487
+ value: source
5488
+ }];
5234
5489
  }
5235
5490
  ;
5236
- if (discount == null ? void 0 : discount.appliesOncePerCustomer) return "Each customer can use this discount only once.";
5237
- return null;
5491
+ const result = await adminFetch({
5492
+ fetcher,
5493
+ adminAccessToken,
5494
+ domain,
5495
+ query: `
5496
+ mutation customerCreate( $input : CustomerInput! ) {
5497
+ customerCreate( input : $input ) {
5498
+ customer {
5499
+ id
5500
+ }
5501
+ userErrors {
5502
+ field
5503
+ message
5504
+ }
5505
+ }
5506
+ }
5507
+ `,
5508
+ variables: { input }
5509
+ });
5510
+ const userErrors = (_d = result == null ? void 0 : result.customerCreate) == null ? void 0 : _d.userErrors;
5511
+ if (userErrors == null ? void 0 : userErrors.length) {
5512
+ const emailTaken = userErrors.some((e) => {
5513
+ var _a2;
5514
+ return (_a2 = e.message) == null ? void 0 : _a2.includes("Email has already been taken");
5515
+ });
5516
+ if (emailTaken) {
5517
+ const retry = await adminFetch({
5518
+ fetcher,
5519
+ adminAccessToken,
5520
+ domain,
5521
+ query: lookupQuery,
5522
+ variables: { query: "email:" + email }
5523
+ });
5524
+ const found = (_g = (_f = (_e = retry == null ? void 0 : retry.customers) == null ? void 0 : _e.edges) == null ? void 0 : _f[0]) == null ? void 0 : _g.node;
5525
+ if (found) return found;
5526
+ }
5527
+ ;
5528
+ throw new Error("Shopify customer create failed: " + userErrors[0].message);
5529
+ }
5530
+ ;
5531
+ return (_h = result == null ? void 0 : result.customerCreate) == null ? void 0 : _h.customer;
5238
5532
  };
5239
- var ORDER_EVENT_HANDLE = slugify("drawbridge-orders");
5240
- var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
5241
- var OAUTH_ERROR_SOURCE = "oauth";
5242
- var BILLING_ERROR_SOURCE = "billing";
5243
- var BILLING_ERROR_MESSAGE = "Order billing isn't set up for this store \u2014 reselect and approve the plan from the Shopify connection page.";
5244
- var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
5245
- var inbound = {
5246
- headers: {
5247
- event: "x-shopify-topic",
5248
- id: "x-shopify-webhook-id",
5249
- shop: "x-shopify-shop-domain",
5250
- signature: "x-shopify-hmac-sha256"
5251
- },
5252
- signature: {
5253
- algorithm: "sha256",
5254
- encoding: "base64",
5255
- secret: "SHOPIFY_API_SECRET"
5533
+ var getActiveAppSubscriptions = async ({ fetcher, adminAccessToken, domain }) => {
5534
+ var _a, _b;
5535
+ const data2 = await adminFetch({
5536
+ fetcher,
5537
+ adminAccessToken,
5538
+ domain,
5539
+ query: `{
5540
+ currentAppInstallation {
5541
+ activeSubscriptions {
5542
+ id
5543
+ name
5544
+ status
5545
+ test
5546
+ lineItems {
5547
+ id
5548
+ plan {
5549
+ pricingDetails {
5550
+ __typename
5551
+ }
5552
+ }
5553
+ }
5554
+ }
5555
+ }
5556
+ shop {
5557
+ myshopifyDomain
5558
+ }
5559
+ }`
5560
+ });
5561
+ return {
5562
+ shopDomain: ((_a = data2 == null ? void 0 : data2.shop) == null ? void 0 : _a.myshopifyDomain) || null,
5563
+ subscriptions: (((_b = data2 == null ? void 0 : data2.currentAppInstallation) == null ? void 0 : _b.activeSubscriptions) || []).map((subscription) => {
5564
+ var _a2;
5565
+ return {
5566
+ ...subscription,
5567
+ metered: ((subscription == null ? void 0 : subscription.lineItems) || []).some(
5568
+ (item) => {
5569
+ var _a3, _b2;
5570
+ return ((_b2 = (_a3 = item == null ? void 0 : item.plan) == null ? void 0 : _a3.pricingDetails) == null ? void 0 : _b2.__typename) === "AppUsagePricing";
5571
+ }
5572
+ ),
5573
+ // The usage line's own id — the address appUsageRecordCreate charges
5574
+ // against. Null when the approval carries no usage component.
5575
+ usageLineItemId: ((_a2 = ((subscription == null ? void 0 : subscription.lineItems) || []).find(
5576
+ (item) => {
5577
+ var _a3, _b2;
5578
+ return ((_b2 = (_a3 = item == null ? void 0 : item.plan) == null ? void 0 : _a3.pricingDetails) == null ? void 0 : _b2.__typename) === "AppUsagePricing";
5579
+ }
5580
+ )) == null ? void 0 : _a2.id) || null
5581
+ };
5582
+ })
5583
+ };
5584
+ };
5585
+ var createUsageSubscription = async ({ fetcher, adminAccessToken, cappedAmount, currencyCode = "USD", domain, name, recurringPrice = 0, returnUrl, terms, test = false }) => {
5586
+ if (!name || !returnUrl || !terms || !(Number(cappedAmount) > 0)) {
5587
+ throw new Error("createUsageSubscription requires name, returnUrl, terms, and a positive cappedAmount");
5588
+ }
5589
+ ;
5590
+ const data2 = await adminFetch({
5591
+ fetcher,
5592
+ adminAccessToken,
5593
+ domain,
5594
+ query: `mutation createUsageSubscription( $lineItems : [AppSubscriptionLineItemInput!]!, $name : String!, $returnUrl : URL!, $test : Boolean ) {
5595
+ appSubscriptionCreate( lineItems : $lineItems, name : $name, returnUrl : $returnUrl, test : $test ) {
5596
+ appSubscription { id name status test lineItems { id plan { pricingDetails { __typename } } } }
5597
+ confirmationUrl
5598
+ userErrors { field message }
5599
+ }
5600
+ }`,
5601
+ variables: {
5602
+ lineItems: [
5603
+ {
5604
+ plan: {
5605
+ appRecurringPricingDetails: {
5606
+ interval: "EVERY_30_DAYS",
5607
+ price: { amount: Number(recurringPrice), currencyCode }
5608
+ }
5609
+ }
5610
+ },
5611
+ {
5612
+ plan: {
5613
+ appUsagePricingDetails: {
5614
+ cappedAmount: { amount: Number(cappedAmount), currencyCode },
5615
+ terms
5616
+ }
5617
+ }
5618
+ }
5619
+ ],
5620
+ name,
5621
+ returnUrl,
5622
+ test
5623
+ }
5624
+ });
5625
+ const payload = data2 == null ? void 0 : data2.appSubscriptionCreate;
5626
+ const userErrors = (payload == null ? void 0 : payload.userErrors) || [];
5627
+ if (userErrors.length) {
5628
+ throw new Error("Shopify subscription create failed: " + userErrors.map((entry) => entry.message).join("; "));
5629
+ }
5630
+ ;
5631
+ if (!(payload == null ? void 0 : payload.confirmationUrl)) {
5632
+ throw new Error("Shopify subscription create failed: no confirmation url returned");
5256
5633
  }
5634
+ ;
5635
+ return {
5636
+ confirmationUrl: payload.confirmationUrl,
5637
+ subscription: payload.appSubscription
5638
+ };
5257
5639
  };
5258
- var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
5259
- "customers/data_request",
5260
- "customers/redact",
5261
- "shop/redact"
5262
- ]);
5263
- var shopify_default2 = {
5264
- // THE WORDS ON THE BUTTONS. `listing` was `content.redirect.title`, which put
5265
- // a BUTTON LABEL inside the copy object next to a url — the title and the
5266
- // address it belongs to sat at different levels and could drift apart.
5267
- //
5268
- // It names where the link GOES rather than what it does: installing happens on
5269
- // the App Store listing, and the dashboard must never imply a store can be
5270
- // linked from inside it.
5271
- actions: {
5272
- create: null,
5273
- listing: "View on the Shopify App Store",
5274
- manage: null,
5275
- update: null
5276
- },
5277
- // INSTALL, not oauth. The grant is an OAuth grant, but the merchant never
5278
- // sees a consent screen we sent them to -- they start at the App Store, and
5279
- // the install completes inside Shopify admin without redirecting back. A
5280
- // Connect button here would be lying about where connecting happens.
5281
- auth: {
5282
- // ONE STORE PER ORGANIZATION. A Shopify install IS a store, and a second
5283
- // one would give an organization two catalogues, two order streams and two
5284
- // usage meters with nothing to say which is authoritative.
5285
- //
5286
- // DECLARED AND ENFORCED BY NOTHING, measured 2026-09-13: no repo reads this
5287
- // key, and the connection collection's { organization, slug } index is not
5288
- // unique. So a second Shopify connection would be accepted today. The gate
5289
- // belongs at the connect route with a unique partial index behind it, and
5290
- // that is api work — this is the declaration it will read.
5640
+ var createUsageRecord = async ({ fetcher, adminAccessToken, amount, currencyCode = "USD", description, domain, idempotencyKey, subscriptionLineItemId }) => {
5641
+ var _a;
5642
+ if (!subscriptionLineItemId || !description || !(Number(amount) > 0)) {
5643
+ throw new Error("createUsageRecord requires subscriptionLineItemId, description, and a positive amount");
5644
+ }
5645
+ ;
5646
+ const data2 = await adminFetch({
5647
+ fetcher,
5648
+ adminAccessToken,
5649
+ domain,
5650
+ query: `mutation createUsageRecord( $description : String!, $idempotencyKey : String, $price : MoneyInput!, $subscriptionLineItemId : ID! ) {
5651
+ appUsageRecordCreate( description : $description, idempotencyKey : $idempotencyKey, price : $price, subscriptionLineItemId : $subscriptionLineItemId ) {
5652
+ appUsageRecord { id }
5653
+ userErrors { field message }
5654
+ }
5655
+ }`,
5656
+ variables: {
5657
+ description,
5658
+ idempotencyKey: idempotencyKey ? String(idempotencyKey) : null,
5659
+ price: { amount: Number(amount), currencyCode },
5660
+ subscriptionLineItemId
5661
+ }
5662
+ });
5663
+ const payload = data2 == null ? void 0 : data2.appUsageRecordCreate;
5664
+ const userErrors = (payload == null ? void 0 : payload.userErrors) || [];
5665
+ if (userErrors.length || !((_a = payload == null ? void 0 : payload.appUsageRecord) == null ? void 0 : _a.id)) {
5666
+ throw new Error("Shopify usage record failed: " + (userErrors.map((entry) => entry.message).join("; ") || "no record returned"));
5667
+ }
5668
+ ;
5669
+ return { id: payload.appUsageRecord.id };
5670
+ };
5671
+ var getProductInventory = async ({ fetcher, adminAccessToken, domain, productId }) => {
5672
+ var _a, _b;
5673
+ const data2 = await adminFetch({
5674
+ fetcher,
5675
+ adminAccessToken,
5676
+ domain,
5677
+ query: `{
5678
+ product( id : "${productId}" ) {
5679
+ variants( first : 100 ) {
5680
+ edges {
5681
+ node {
5682
+ id
5683
+ inventoryQuantity
5684
+ }
5685
+ }
5686
+ }
5687
+ }
5688
+ }`
5689
+ });
5690
+ const edges = ((_b = (_a = data2 == null ? void 0 : data2.product) == null ? void 0 : _a.variants) == null ? void 0 : _b.edges) || [];
5691
+ return edges.reduce((accumulator, edge) => {
5692
+ var _a2, _b2;
5693
+ const id = (_a2 = edge == null ? void 0 : edge.node) == null ? void 0 : _a2.id;
5694
+ const quantity = (_b2 = edge == null ? void 0 : edge.node) == null ? void 0 : _b2.inventoryQuantity;
5695
+ if (id) {
5696
+ accumulator[id] = Number.isFinite(quantity) ? quantity : 0;
5697
+ }
5698
+ ;
5699
+ return accumulator;
5700
+ }, {});
5701
+ };
5702
+ var getProductUpdatedAt = async ({ adminAccessToken, domain, fetcher, productId }) => {
5703
+ var _a;
5704
+ const data2 = await adminFetch({
5705
+ fetcher,
5706
+ adminAccessToken,
5707
+ domain,
5708
+ query: `
5709
+ query ProductUpdatedAt($id: ID!) {
5710
+ product(id: $id) {
5711
+ updatedAt
5712
+ }
5713
+ }
5714
+ `,
5715
+ variables: { id: productId }
5716
+ });
5717
+ return ((_a = data2 == null ? void 0 : data2.product) == null ? void 0 : _a.updatedAt) || null;
5718
+ };
5719
+ var NOT_ON_CHANNEL = "not available to the channel";
5720
+ var OUTDATED_FEEDBACK = "later version";
5721
+ var sendProductResourceFeedback = async ({ fetcher, adminAccessToken, domain, productId, state, messages = [] }) => {
5722
+ var _a, _b, _c;
5723
+ const productUpdatedAt = await getProductUpdatedAt({ adminAccessToken, domain, fetcher, productId });
5724
+ if (!productUpdatedAt) return null;
5725
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5726
+ const submit = async (version) => {
5727
+ const data2 = await adminFetch({
5728
+ fetcher,
5729
+ adminAccessToken,
5730
+ domain,
5731
+ query: `
5732
+ mutation ProductFeedback($feedbackInput: [ProductResourceFeedbackInput!]!) {
5733
+ bulkProductResourceFeedbackCreate(feedbackInput: $feedbackInput) {
5734
+ feedback {
5735
+ productId
5736
+ state
5737
+ }
5738
+ userErrors {
5739
+ field
5740
+ message
5741
+ }
5742
+ }
5743
+ }
5744
+ `,
5745
+ variables: {
5746
+ feedbackInput: [
5747
+ {
5748
+ productId,
5749
+ state,
5750
+ feedbackGeneratedAt: now,
5751
+ productUpdatedAt: version,
5752
+ messages
5753
+ }
5754
+ ]
5755
+ }
5756
+ });
5757
+ return data2 == null ? void 0 : data2.bulkProductResourceFeedbackCreate;
5758
+ };
5759
+ let result = await submit(productUpdatedAt);
5760
+ if ((((_b = (_a = result == null ? void 0 : result.userErrors) == null ? void 0 : _a[0]) == null ? void 0 : _b.message) || "").toLowerCase().includes(OUTDATED_FEEDBACK)) {
5761
+ result = await submit(now);
5762
+ }
5763
+ ;
5764
+ const feedbackErrors = result == null ? void 0 : result.userErrors;
5765
+ if (feedbackErrors == null ? void 0 : feedbackErrors.length) {
5766
+ const message = feedbackErrors[0].message || "";
5767
+ if (message.toLowerCase().includes(NOT_ON_CHANNEL)) return null;
5768
+ throw new Error("Shopify product feedback failed: " + message);
5769
+ }
5770
+ ;
5771
+ return ((_c = result == null ? void 0 : result.feedback) == null ? void 0 : _c[0]) || null;
5772
+ };
5773
+
5774
+ // lib/shopify/billing.js
5775
+ var billing_exports = {};
5776
+ __export(billing_exports, {
5777
+ sendAppEvent: () => sendAppEvent
5778
+ });
5779
+ var APP_API = "https://api.shopify.com";
5780
+ var APP_API_VERSION = process.env.SHOPIFY_APP_API_VERSION || SHOPIFY_APP_API_VERSION;
5781
+ var cachedTokens = {};
5782
+ var fetchAppToken = async ({ clientId, clientSecret, fetcher }) => {
5783
+ const data2 = await request({
5784
+ fetcher,
5785
+ method: "POST",
5786
+ url: APP_API + "/auth/access_token",
5787
+ body: {
5788
+ client_id: clientId,
5789
+ client_secret: clientSecret,
5790
+ grant_type: "client_credentials"
5791
+ }
5792
+ });
5793
+ if (!(data2 == null ? void 0 : data2.access_token)) {
5794
+ throw new Error("Shopify app token request failed: no access token returned");
5795
+ }
5796
+ ;
5797
+ const ttl = data2.expires_in ? data2.expires_in * 1e3 : 60 * 60 * 1e3;
5798
+ cachedTokens[clientId] = {
5799
+ expiresAt: Date.now() + ttl - 60 * 1e3,
5800
+ token: data2.access_token
5801
+ };
5802
+ return data2.access_token;
5803
+ };
5804
+ var getAppToken = async ({ clientId, clientSecret, fetcher }) => {
5805
+ const cached = cachedTokens[clientId];
5806
+ if (cached && cached.expiresAt > Date.now()) {
5807
+ return cached.token;
5808
+ }
5809
+ ;
5810
+ return fetchAppToken({ clientId, clientSecret, fetcher });
5811
+ };
5812
+ var toShopGid = (shopId) => String(shopId).startsWith("gid://") ? String(shopId) : "gid://shopify/Shop/" + shopId;
5813
+ var sendAppEvent = async ({ fetcher, clientId, clientSecret, eventHandle, idempotencyKey, reference, revision, shopId, timestamp, value }) => {
5814
+ if (!shopId || !eventHandle || !(Number(value) > 0)) {
5815
+ throw new Error("sendAppEvent requires shopId, eventHandle, and a positive value");
5816
+ }
5817
+ ;
5818
+ if (!clientId || !clientSecret) {
5819
+ throw new Error("sendAppEvent requires clientId and clientSecret");
5820
+ }
5821
+ ;
5822
+ const suffix = revision ? ".r" + revision : "";
5823
+ const key = idempotencyKey && String(idempotencyKey).slice(0, Math.max(0, 64 - suffix.length)) + suffix;
5824
+ const body = {
5825
+ attributes: {
5826
+ value: Number(value),
5827
+ ...reference && {
5828
+ reference: String(reference).slice(0, 128)
5829
+ }
5830
+ },
5831
+ event_handle: eventHandle,
5832
+ shop_id: toShopGid(shopId),
5833
+ timestamp: timestamp || (/* @__PURE__ */ new Date()).toISOString(),
5834
+ ...key && {
5835
+ idempotency_key: key
5836
+ }
5837
+ };
5838
+ const send2 = async (token) => request({
5839
+ method: "POST",
5840
+ url: APP_API + "/app/" + APP_API_VERSION + "/events",
5841
+ headers: {
5842
+ "Authorization": "Bearer " + token
5843
+ },
5844
+ body
5845
+ });
5846
+ try {
5847
+ return await send2(await getAppToken({ clientId, clientSecret, fetcher }));
5848
+ } catch (error) {
5849
+ if ((error == null ? void 0 : error.status) === 401) {
5850
+ delete cachedTokens[clientId];
5851
+ return send2(await fetchAppToken({ clientId, clientSecret, fetcher }));
5852
+ }
5853
+ ;
5854
+ throw error;
5855
+ }
5856
+ };
5857
+
5858
+ // lib/shopify/oauth.js
5859
+ var oauth_exports = {};
5860
+ __export(oauth_exports, {
5861
+ SHOPIFY_REQUIRED_SCOPES: () => SHOPIFY_REQUIRED_SCOPES,
5862
+ createStorefrontToken: () => createStorefrontToken,
5863
+ getAdminToken: () => getAdminToken,
5864
+ getShop: () => getShop,
5865
+ missingScopes: () => missingScopes2,
5866
+ ping: () => ping,
5867
+ refreshAdminToken: () => refreshAdminToken,
5868
+ resolveConnectionSettings: () => resolveConnectionSettings
5869
+ });
5870
+ var required = (name, value) => {
5871
+ if (!value) {
5872
+ throw new Error("Shopify " + name + " is required");
5873
+ }
5874
+ ;
5875
+ return value;
5876
+ };
5877
+ var missingScopes2 = (granted) => {
5878
+ const grantedSet = new Set(
5879
+ (Array.isArray(granted) ? granted : String(granted || "").split(",")).map((scope) => scope.trim()).filter(Boolean)
5880
+ );
5881
+ const satisfied = (scope) => grantedSet.has(scope) || grantedSet.has(scope.replace(/(^|_)read_/, "$1write_"));
5882
+ return SHOPIFY_REQUIRED_SCOPES.filter((scope) => !satisfied(scope));
5883
+ };
5884
+ var ping = async ({ fetcher, adminAccessToken, domain }) => {
5885
+ var _a;
5886
+ const response = await fetch(
5887
+ `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}/graphql.json`,
5888
+ {
5889
+ body: JSON.stringify({ query: "{ shop { name } }" }),
5890
+ headers: {
5891
+ "Content-Type": "application/json",
5892
+ "X-Shopify-Access-Token": adminAccessToken
5893
+ },
5894
+ method: "POST"
5895
+ }
5896
+ );
5897
+ if (!response.ok) {
5898
+ const text = await response.text().catch(() => "");
5899
+ const error = new Error(response.status + ": " + text);
5900
+ error.status = response.status;
5901
+ throw error;
5902
+ }
5903
+ ;
5904
+ const { errors } = await response.json().catch(() => ({}));
5905
+ if (errors == null ? void 0 : errors.length) {
5906
+ throw new Error("GraphQL: " + (((_a = errors[0]) == null ? void 0 : _a.message) || "unknown error"));
5907
+ }
5908
+ ;
5909
+ };
5910
+ var OAUTH_ERROR_TITLE_PATTERN = /Oauth error (\w+)/i;
5911
+ var parseOAuthErrorCode = (text) => {
5912
+ var _a;
5913
+ try {
5914
+ const parsed = JSON.parse(text);
5915
+ if (parsed == null ? void 0 : parsed.error) return parsed.error;
5916
+ } catch {
5917
+ }
5918
+ ;
5919
+ return ((_a = text.match(OAUTH_ERROR_TITLE_PATTERN)) == null ? void 0 : _a[1]) || null;
5920
+ };
5921
+ var shopifyOAuthFetch = async (url, body) => {
5922
+ const response = await fetch(url, {
5923
+ method: "POST",
5924
+ headers: {
5925
+ "Content-Type": "application/json"
5926
+ },
5927
+ body: JSON.stringify(body)
5928
+ });
5929
+ if (!response.ok) {
5930
+ const text = await response.text().catch(() => "");
5931
+ const error = new Error(response.status + ": " + text);
5932
+ error.status = response.status;
5933
+ error.code = parseOAuthErrorCode(text);
5934
+ throw error;
5935
+ }
5936
+ ;
5937
+ return response.json();
5938
+ };
5939
+ var getShop = async ({ fetcher, adminAccessToken, shop }) => {
5940
+ const data2 = await adminFetch({
5941
+ fetcher,
5942
+ adminAccessToken,
5943
+ domain: shop,
5944
+ query: `{
5945
+ shop {
5946
+ currencyCode
5947
+ id
5948
+ myshopifyDomain
5949
+ name
5950
+ }
5951
+ }`
5952
+ });
5953
+ const shopData = data2 == null ? void 0 : data2.shop;
5954
+ if (!(shopData == null ? void 0 : shopData.id)) {
5955
+ throw new Error("Shopify shop lookup failed: no shop returned");
5956
+ }
5957
+ ;
5958
+ return {
5959
+ currency: shopData.currencyCode || null,
5960
+ id: shopData.id.split("/").pop(),
5961
+ myshopifyDomain: shopData.myshopifyDomain,
5962
+ name: shopData.name
5963
+ };
5964
+ };
5965
+ var createStorefrontToken = async ({ fetcher, adminAccessToken, shop }) => {
5966
+ var _a, _b, _c, _d, _e;
5967
+ try {
5968
+ const listed = await adminFetch({
5969
+ fetcher,
5970
+ adminAccessToken,
5971
+ domain: shop,
5972
+ query: `{
5973
+ shop {
5974
+ storefrontAccessTokens(first: 100) {
5975
+ edges {
5976
+ node {
5977
+ id
5978
+ title
5979
+ }
5980
+ }
5981
+ }
5982
+ }
5983
+ }`
5984
+ });
5985
+ const existing = (((_b = (_a = listed == null ? void 0 : listed.shop) == null ? void 0 : _a.storefrontAccessTokens) == null ? void 0 : _b.edges) || []).map((edge) => edge == null ? void 0 : edge.node);
5986
+ const orphaned = existing.filter((token) => (token == null ? void 0 : token.title) === "Drawbridge");
5987
+ await Promise.allSettled(
5988
+ orphaned.map((token) => adminFetch({
5989
+ adminAccessToken,
5990
+ domain: shop,
5991
+ query: `
5992
+ mutation StorefrontAccessTokenDelete($input: StorefrontAccessTokenDeleteInput!) {
5993
+ storefrontAccessTokenDelete(input: $input) {
5994
+ deletedStorefrontAccessTokenId
5995
+ userErrors {
5996
+ field
5997
+ message
5998
+ }
5999
+ }
6000
+ }
6001
+ `,
6002
+ variables: {
6003
+ input: {
6004
+ id: token.id
6005
+ }
6006
+ }
6007
+ }))
6008
+ );
6009
+ } catch {
6010
+ }
6011
+ const created = await adminFetch({
6012
+ fetcher,
6013
+ adminAccessToken,
6014
+ domain: shop,
6015
+ query: `
6016
+ mutation StorefrontAccessTokenCreate($input: StorefrontAccessTokenInput!) {
6017
+ storefrontAccessTokenCreate(input: $input) {
6018
+ storefrontAccessToken {
6019
+ accessToken
6020
+ }
6021
+ userErrors {
6022
+ field
6023
+ message
6024
+ }
6025
+ }
6026
+ }
6027
+ `,
6028
+ variables: {
6029
+ input: {
6030
+ title: "Drawbridge"
6031
+ }
6032
+ }
6033
+ });
6034
+ const createErrors = (_c = created == null ? void 0 : created.storefrontAccessTokenCreate) == null ? void 0 : _c.userErrors;
6035
+ if (createErrors == null ? void 0 : createErrors.length) {
6036
+ throw new Error("Shopify storefront token create failed: " + createErrors[0].message);
6037
+ }
6038
+ ;
6039
+ return ((_e = (_d = created == null ? void 0 : created.storefrontAccessTokenCreate) == null ? void 0 : _d.storefrontAccessToken) == null ? void 0 : _e.accessToken) || null;
6040
+ };
6041
+ var resolveTokenContext = async ({ connection: connection2, controller }) => {
6042
+ const decrypted = (connection2 == null ? void 0 : connection2.settings) ? decrypt(connection2.settings) : {};
6043
+ if ((decrypted == null ? void 0 : decrypted.ref) !== "shop") {
6044
+ return {
6045
+ raw: (connection2 == null ? void 0 : connection2.settings) || null,
6046
+ session: null,
6047
+ settings: decrypted,
6048
+ shop: null,
6049
+ target: "connection"
6050
+ };
6051
+ }
6052
+ ;
6053
+ const shop = decrypted.shop;
6054
+ if (!controller || !shop) {
6055
+ return { raw: null, session: {}, settings: {}, shop, target: "shop" };
6056
+ }
6057
+ ;
6058
+ const record = await controller.get({ collection: "shop", query: { shop } });
6059
+ const session = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : {};
6060
+ const storefront = (record == null ? void 0 : record.storefront) ? decrypt(record.storefront) : null;
6061
+ return {
6062
+ raw: (record == null ? void 0 : record.settings) || null,
6063
+ session,
6064
+ settings: {
6065
+ adminAccessToken: session.accessToken || null,
6066
+ refreshToken: session.refreshToken || null,
6067
+ refreshTokenExpiresAt: session.refreshTokenExpires || null,
6068
+ storefrontAccessToken: (storefront == null ? void 0 : storefront.token) || null,
6069
+ tokenExpiresAt: session.expires || null
6070
+ },
6071
+ shop,
6072
+ target: "shop"
6073
+ };
6074
+ };
6075
+ var resolveConnectionSettings = async ({ fetcher, connection: connection2, controller }) => {
6076
+ const { settings } = await resolveTokenContext({ connection: connection2, controller });
6077
+ return settings;
6078
+ };
6079
+ var refreshAdminToken = async ({ fetcher, clientId, clientSecret, connection: connection2, controller }) => {
6080
+ var _a;
6081
+ const { raw, session, settings, shop, target } = await resolveTokenContext({ connection: connection2, controller });
6082
+ const domain = (connection2 == null ? void 0 : connection2.shop) || ((_a = settings.source) == null ? void 0 : _a.domain) || settings.domain || shop;
6083
+ const { refreshToken } = settings;
6084
+ const data2 = await shopifyOAuthFetch(
6085
+ `https://${domain}/admin/oauth/access_token`,
6086
+ {
6087
+ grant_type: "refresh_token",
6088
+ // Throw before the grant: rotation RETIRES the old pair the moment it
6089
+ // returns, so a credential-less call that Shopify rejects opaquely is
6090
+ // the one failure mode worth being loud about.
6091
+ client_id: required("clientId", clientId),
6092
+ client_secret: required("clientSecret", clientSecret),
6093
+ refresh_token: refreshToken
6094
+ }
6095
+ );
6096
+ const adminAccessToken = data2.access_token;
6097
+ const newRefreshToken = data2.refresh_token;
6098
+ const expiresIn = data2.expires_in;
6099
+ const tokenExpiresAt = expiresIn ? new Date(Date.now() + expiresIn * 1e3) : null;
6100
+ const refreshTokenExpiresAt = new Date(Date.now() + REFRESH_TOKEN_LIFETIME_MS);
6101
+ let liveToken = adminAccessToken;
6102
+ if (target === "shop") {
6103
+ const written = await controller.update({
6104
+ collection: "shop",
6105
+ data: {
6106
+ $set: {
6107
+ settings: encrypt({
6108
+ ...session,
6109
+ accessToken: adminAccessToken,
6110
+ expires: tokenExpiresAt,
6111
+ refreshToken: newRefreshToken,
6112
+ refreshTokenExpires: refreshTokenExpiresAt
6113
+ })
6114
+ }
6115
+ },
6116
+ query: {
6117
+ shop,
6118
+ ...raw && { settings: raw }
6119
+ }
6120
+ });
6121
+ if (!written) {
6122
+ const current = await controller.get({ collection: "shop", query: { shop } });
6123
+ if (!(current == null ? void 0 : current.settings)) {
6124
+ throw new Error("Shopify token refresh write-back failed: shop record missing for " + shop);
6125
+ }
6126
+ ;
6127
+ const currentSession = decrypt(current.settings);
6128
+ if ((currentSession == null ? void 0 : currentSession.accessToken) && currentSession.accessToken !== settings.adminAccessToken) {
6129
+ liveToken = currentSession.accessToken;
6130
+ } else {
6131
+ throw new Error("Shopify token refresh write-back failed for " + shop);
6132
+ }
6133
+ ;
6134
+ }
6135
+ ;
6136
+ } else {
6137
+ const written = await controller.update({
6138
+ collection: "connection",
6139
+ data: {
6140
+ $set: {
6141
+ settings: encrypt({
6142
+ ...settings,
6143
+ adminAccessToken,
6144
+ refreshToken: newRefreshToken,
6145
+ refreshTokenExpiresAt,
6146
+ tokenExpiresAt
6147
+ })
6148
+ }
6149
+ },
6150
+ query: {
6151
+ id: connection2.id,
6152
+ ...raw && { settings: raw }
6153
+ }
6154
+ });
6155
+ if (!written) {
6156
+ const current = await controller.get({ collection: "connection", query: { id: connection2.id } });
6157
+ const currentSettings = (current == null ? void 0 : current.settings) ? decrypt(current.settings) : null;
6158
+ if ((currentSettings == null ? void 0 : currentSettings.adminAccessToken) && currentSettings.adminAccessToken !== settings.adminAccessToken) {
6159
+ liveToken = currentSettings.adminAccessToken;
6160
+ } else {
6161
+ throw new Error("Shopify token refresh write-back failed for connection " + (connection2 == null ? void 0 : connection2.id));
6162
+ }
6163
+ ;
6164
+ }
6165
+ ;
6166
+ }
6167
+ ;
6168
+ await ping({ adminAccessToken: liveToken, domain });
6169
+ return liveToken;
6170
+ };
6171
+ var getAdminToken = async ({ fetcher, clientId, clientSecret, connection: connection2, controller }) => {
6172
+ required("clientId", clientId);
6173
+ required("clientSecret", clientSecret);
6174
+ const settings = await resolveConnectionSettings({ connection: connection2, controller });
6175
+ const { adminAccessToken, refreshToken, tokenExpiresAt } = settings;
6176
+ if (!adminAccessToken) {
6177
+ return null;
6178
+ }
6179
+ ;
6180
+ if (!refreshToken) {
6181
+ return adminAccessToken;
6182
+ }
6183
+ ;
6184
+ const needsRefresh = !tokenExpiresAt || new Date(tokenExpiresAt) < new Date(Date.now() + ACCESS_TOKEN_REFRESH_BUFFER_MS);
6185
+ if (needsRefresh) {
6186
+ return refreshAdminToken({ clientId, clientSecret, connection: connection2, controller });
6187
+ }
6188
+ ;
6189
+ return adminAccessToken;
6190
+ };
6191
+
6192
+ // lib/shopify/partner.js
6193
+ var partner_exports = {};
6194
+ __export(partner_exports, {
6195
+ getUsageChargeEvents: () => getUsageChargeEvents
6196
+ });
6197
+ var PARTNER_API = "https://partners.shopify.com";
6198
+ var getUsageChargeEvents = async ({ fetcher, appId, first = 10, occurredAtMin, organizationId, partnerToken, shopId }) => {
6199
+ var _a, _b, _c;
6200
+ if (!partnerToken || !organizationId || !appId) {
6201
+ throw new Error("getUsageChargeEvents requires partnerToken, organizationId, and appId");
6202
+ }
6203
+ ;
6204
+ const data2 = await request({
6205
+ fetcher,
6206
+ method: "POST",
6207
+ url: PARTNER_API + "/" + organizationId + "/api/" + PARTNER_API_VERSION + "/graphql.json",
6208
+ headers: {
6209
+ "X-Shopify-Access-Token": partnerToken
6210
+ },
6211
+ body: {
6212
+ query: `query usageCharges( $filter : EventFilterInput!, $first : Int! ) {
6213
+ events( filter : $filter, orderBy : OCCURRED_AT_DESC, first : $first ) {
6214
+ edges {
6215
+ node {
6216
+ id
6217
+ occurredAt
6218
+ eventType
6219
+ shop { id myshopifyDomain }
6220
+ ... on Charge {
6221
+ chargeId
6222
+ chargeType
6223
+ amount { amount currencyCode }
6224
+ usageQuantity
6225
+ planHandle
6226
+ description
6227
+ }
6228
+ }
6229
+ }
6230
+ pageInfo { hasNextPage endCursor }
6231
+ }
6232
+ }`,
6233
+ variables: {
6234
+ filter: {
6235
+ eventTypes: ["CHARGE_USAGE"],
6236
+ subjectId: String(appId),
6237
+ ...occurredAtMin && { occurredAtMin },
6238
+ ...shopId && { shopId: String(shopId) }
6239
+ },
6240
+ first
6241
+ }
6242
+ }
6243
+ });
6244
+ if ((_a = data2 == null ? void 0 : data2.errors) == null ? void 0 : _a.length) {
6245
+ throw new Error("Shopify partner events query failed: " + data2.errors.map((entry) => entry.message).join("; "));
6246
+ }
6247
+ ;
6248
+ return (((_c = (_b = data2 == null ? void 0 : data2.data) == null ? void 0 : _b.events) == null ? void 0 : _c.edges) || []).map((edge) => {
6249
+ var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j;
6250
+ return {
6251
+ amount: ((_a2 = edge.node) == null ? void 0 : _a2.amount) || null,
6252
+ chargeId: ((_b2 = edge.node) == null ? void 0 : _b2.chargeId) || null,
6253
+ // USAGE vs the recurring plan charge an approval emits — the
6254
+ // disambiguator callers filter on.
6255
+ chargeType: ((_c2 = edge.node) == null ? void 0 : _c2.chargeType) || null,
6256
+ description: ((_d = edge.node) == null ? void 0 : _d.description) || null,
6257
+ eventType: ((_e = edge.node) == null ? void 0 : _e.eventType) || null,
6258
+ id: ((_f = edge.node) == null ? void 0 : _f.id) || null,
6259
+ occurredAt: ((_g = edge.node) == null ? void 0 : _g.occurredAt) || null,
6260
+ planHandle: ((_h = edge.node) == null ? void 0 : _h.planHandle) || null,
6261
+ shop: ((_i = edge.node) == null ? void 0 : _i.shop) || null,
6262
+ usageQuantity: ((_j = edge.node) == null ? void 0 : _j.usageQuantity) ?? null
6263
+ };
6264
+ });
6265
+ };
6266
+
6267
+ // lib/shopify/storefront.js
6268
+ var storefront_exports = {};
6269
+ __export(storefront_exports, {
6270
+ cartCreate: () => cartCreate,
6271
+ cartGet: () => cartGet,
6272
+ cartLinesAdd: () => cartLinesAdd,
6273
+ cartLinesRemove: () => cartLinesRemove,
6274
+ cartLinesUpdate: () => cartLinesUpdate,
6275
+ createCheckoutToken: () => createCheckoutToken,
6276
+ getProduct: () => getProduct,
6277
+ getProductVariantsPage: () => getProductVariantsPage,
6278
+ getProducts: () => getProducts,
6279
+ probeVariantsOutOfStock: () => probeVariantsOutOfStock
6280
+ });
6281
+ var SORT_KEY_MAP = {
6282
+ bestSelling: "BEST_SELLING",
6283
+ createdAt: "CREATED_AT",
6284
+ id: "ID",
6285
+ price: "PRICE",
6286
+ productType: "PRODUCT_TYPE",
6287
+ title: "TITLE",
6288
+ updatedAt: "UPDATED_AT",
6289
+ vendor: "VENDOR"
6290
+ };
6291
+ var resolveProductSort = (sort) => {
6292
+ const entry = sort && Object.entries(sort)[0];
6293
+ if (!entry) return null;
6294
+ const [field2, direction] = entry;
6295
+ const sortKey = SORT_KEY_MAP[field2];
6296
+ if (!sortKey) return null;
6297
+ return {
6298
+ sortKey,
6299
+ reverse: Number(direction) < 0
6300
+ };
6301
+ };
6302
+ var storefrontUrl = (domain) => `https://${domain}/api/${SHOPIFY_STOREFRONT_API_VERSION}/graphql.json`;
6303
+ var storefrontFetch = async ({ fetcher, domain, storefrontAccessToken, query, variables }) => {
6304
+ return request({
6305
+ method: "POST",
6306
+ url: storefrontUrl(domain),
6307
+ headers: {
6308
+ "X-Shopify-Storefront-Access-Token": storefrontAccessToken
6309
+ },
6310
+ body: {
6311
+ query,
6312
+ ...variables && { variables }
6313
+ }
6314
+ });
6315
+ };
6316
+ var shopCountryCache = {};
6317
+ var getShopCountry = async ({ domain, fetcher, storefrontAccessToken }) => {
6318
+ var _a, _b;
6319
+ if (shopCountryCache[domain]) return shopCountryCache[domain];
6320
+ const { data: data2 } = await storefrontFetch({
6321
+ fetcher,
6322
+ domain,
6323
+ storefrontAccessToken,
6324
+ query: `{
6325
+ shop {
6326
+ paymentSettings {
6327
+ countryCode
6328
+ }
6329
+ }
6330
+ }`
6331
+ });
6332
+ const countryCode = ((_b = (_a = data2 == null ? void 0 : data2.shop) == null ? void 0 : _a.paymentSettings) == null ? void 0 : _b.countryCode) || null;
6333
+ if (countryCode) shopCountryCache[domain] = countryCode;
6334
+ return countryCode;
6335
+ };
6336
+ var OUT_OF_STOCK_WARNING_CODES = [
6337
+ "MERCHANDISE_OUT_OF_STOCK",
6338
+ "MERCHANDISE_NOT_ENOUGH_STOCK"
6339
+ ];
6340
+ var probeVariantsOutOfStock = async ({ fetcher, domain, storefrontAccessToken, variantIds, countryCode }) => {
6341
+ var _a, _b;
6342
+ if (!(variantIds == null ? void 0 : variantIds.length)) return [];
6343
+ const resolvedCountry = countryCode || await getShopCountry({ domain, fetcher, storefrontAccessToken });
6344
+ const { data: data2, errors } = await storefrontFetch({
6345
+ fetcher,
6346
+ domain,
6347
+ storefrontAccessToken,
6348
+ query: `
6349
+ mutation probe( $input : CartInput! ){
6350
+ cartCreate( input : $input ){
6351
+ cart {
6352
+ lines( first : 250 ){
6353
+ edges {
6354
+ node {
6355
+ id
6356
+ merchandise {
6357
+ ... on ProductVariant {
6358
+ id
6359
+ }
6360
+ }
6361
+ }
6362
+ }
6363
+ }
6364
+ }
6365
+ warnings {
6366
+ code
6367
+ message
6368
+ target
6369
+ }
6370
+ }
6371
+ }
6372
+ `,
6373
+ variables: {
6374
+ input: {
6375
+ lines: variantIds.map((merchandiseId) => ({
6376
+ merchandiseId,
6377
+ quantity: 1
6378
+ })),
6379
+ ...resolvedCountry && {
6380
+ buyerIdentity: {
6381
+ countryCode: resolvedCountry
6382
+ }
6383
+ }
6384
+ }
6385
+ }
6386
+ });
6387
+ if (errors) return [];
6388
+ const payload = data2 == null ? void 0 : data2.cartCreate;
6389
+ const soldOut = new Set(
6390
+ ((payload == null ? void 0 : payload.warnings) || []).filter((warning) => OUT_OF_STOCK_WARNING_CODES.includes(warning == null ? void 0 : warning.code) && (warning == null ? void 0 : warning.target)).map((warning) => warning.target)
6391
+ );
6392
+ return (((_b = (_a = payload == null ? void 0 : payload.cart) == null ? void 0 : _a.lines) == null ? void 0 : _b.edges) || []).filter(({ node }) => soldOut.has(node.id)).map(({ node }) => {
6393
+ var _a2;
6394
+ return (_a2 = node == null ? void 0 : node.merchandise) == null ? void 0 : _a2.id;
6395
+ }).filter(Boolean);
6396
+ };
6397
+ var productsQuery = (search, cursor, limit, sort) => {
6398
+ const resolved = resolveProductSort(sort);
6399
+ const sortArgs = resolved ? `, sortKey: ${resolved.sortKey}, reverse: ${resolved.reverse}` : "";
6400
+ return `{
6401
+ products(first: ${limit}${search ? `, query: "title:*${search}*"` : ""}${cursor ? `, after: "${cursor}"` : ""}${sortArgs}) {
6402
+ edges {
6403
+ node {
6404
+ id
6405
+ title
6406
+ description
6407
+ handle
6408
+ productType
6409
+ featuredImage {
6410
+ url
6411
+ }
6412
+ variants(first: 10) {
6413
+ edges {
6414
+ node {
6415
+ id
6416
+ title
6417
+ image {
6418
+ url
6419
+ }
6420
+ price {
6421
+ amount
6422
+ currencyCode
6423
+ }
6424
+ compareAtPrice {
6425
+ amount
6426
+ currencyCode
6427
+ }
6428
+ availableForSale
6429
+ requiresShipping
6430
+ }
6431
+ }
6432
+ }
6433
+ }
6434
+ }
6435
+ pageInfo {
6436
+ endCursor
6437
+ hasNextPage
6438
+ hasPreviousPage
6439
+ startCursor
6440
+ }
6441
+ }
6442
+ }`;
6443
+ };
6444
+ var productQuery = (productId) => `{
6445
+ product(id: "${productId}") {
6446
+ id
6447
+ title
6448
+ description
6449
+ handle
6450
+ productType
6451
+ featuredImage {
6452
+ url
6453
+ }
6454
+ variants(first: 10) {
6455
+ edges {
6456
+ node {
6457
+ id
6458
+ title
6459
+ image {
6460
+ url
6461
+ }
6462
+ price {
6463
+ amount
6464
+ currencyCode
6465
+ }
6466
+ compareAtPrice {
6467
+ amount
6468
+ currencyCode
6469
+ }
6470
+ availableForSale
6471
+ requiresShipping
6472
+ }
6473
+ }
6474
+ }
6475
+ }
6476
+ }`;
6477
+ var variantsQuery = (productId, cursor) => `{
6478
+ product(id: "${productId}") {
6479
+ variants(first: 250${cursor ? `, after: "${cursor}"` : ""}) {
6480
+ edges {
6481
+ node {
6482
+ id
6483
+ title
6484
+ image {
6485
+ url
6486
+ }
6487
+ price {
6488
+ amount
6489
+ currencyCode
6490
+ }
6491
+ compareAtPrice {
6492
+ amount
6493
+ currencyCode
6494
+ }
6495
+ availableForSale
6496
+ requiresShipping
6497
+ }
6498
+ }
6499
+ pageInfo {
6500
+ hasNextPage
6501
+ endCursor
6502
+ }
6503
+ }
6504
+ }
6505
+ }`;
6506
+ var getProducts = async ({ fetcher, domain, storefrontAccessToken, search, cursor, limit, sort }) => {
6507
+ const { data: data2, errors } = await storefrontFetch({
6508
+ fetcher,
6509
+ domain,
6510
+ storefrontAccessToken,
6511
+ query: productsQuery(search, cursor, limit, sort)
6512
+ });
6513
+ if (errors) {
6514
+ throw new Error("Failed to fetch Shopify products");
6515
+ }
6516
+ ;
6517
+ return data2 == null ? void 0 : data2.products;
6518
+ };
6519
+ var getProduct = async ({ fetcher, domain, storefrontAccessToken, productId }) => {
6520
+ var _a;
6521
+ const { data: data2, errors } = await storefrontFetch({
6522
+ fetcher,
6523
+ domain,
6524
+ storefrontAccessToken,
6525
+ query: productQuery(productId)
6526
+ });
6527
+ if (errors) {
6528
+ throw new Error("Shopify storefront error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
6529
+ }
6530
+ ;
6531
+ if (!(data2 == null ? void 0 : data2.product)) {
6532
+ throw new Error("Shopify product not found");
6533
+ }
6534
+ ;
6535
+ return data2.product;
6536
+ };
6537
+ var getProductVariantsPage = async ({ fetcher, domain, storefrontAccessToken, productId, cursor }) => {
6538
+ var _a;
6539
+ const { data: data2, errors } = await storefrontFetch({
6540
+ fetcher,
6541
+ domain,
6542
+ storefrontAccessToken,
6543
+ query: variantsQuery(productId, cursor)
6544
+ });
6545
+ if (errors) {
6546
+ throw new Error("Shopify storefront error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
6547
+ }
6548
+ ;
6549
+ if (!(data2 == null ? void 0 : data2.product)) {
6550
+ throw new Error("Shopify product not found");
6551
+ }
6552
+ ;
6553
+ return data2.product.variants;
6554
+ };
6555
+ var CART_FIELDS = `
6556
+ id
6557
+ checkoutUrl
6558
+ lines(first: 100) {
6559
+ edges {
6560
+ node {
6561
+ id
6562
+ quantity
6563
+ merchandise {
6564
+ ... on ProductVariant {
6565
+ id
6566
+ title
6567
+ availableForSale
6568
+ image {
6569
+ url
6570
+ }
6571
+ price {
6572
+ amount
6573
+ currencyCode
6574
+ }
6575
+ product {
6576
+ title
6577
+ }
6578
+ }
6579
+ }
6580
+ }
6581
+ }
6582
+ }
6583
+ `;
6584
+ var mapCart = (cart) => {
6585
+ var _a;
6586
+ if (!cart) return null;
6587
+ return {
6588
+ checkoutUrl: cart.checkoutUrl,
6589
+ id: cart.id,
6590
+ lines: (((_a = cart.lines) == null ? void 0 : _a.edges) || []).map(({ node }) => {
6591
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
6592
+ return {
6593
+ availableForSale: ((_a2 = node == null ? void 0 : node.merchandise) == null ? void 0 : _a2.availableForSale) ?? true,
6594
+ currency: ((_c = (_b = node == null ? void 0 : node.merchandise) == null ? void 0 : _b.price) == null ? void 0 : _c.currencyCode) || null,
6595
+ id: node.id,
6596
+ image: ((_e = (_d = node == null ? void 0 : node.merchandise) == null ? void 0 : _d.image) == null ? void 0 : _e.url) || null,
6597
+ price: ((_g = (_f = node == null ? void 0 : node.merchandise) == null ? void 0 : _f.price) == null ? void 0 : _g.amount) || null,
6598
+ productTitle: ((_i = (_h = node == null ? void 0 : node.merchandise) == null ? void 0 : _h.product) == null ? void 0 : _i.title) || null,
6599
+ quantity: node.quantity,
6600
+ variantId: (_j = node == null ? void 0 : node.merchandise) == null ? void 0 : _j.id,
6601
+ variantTitle: ((_k = node == null ? void 0 : node.merchandise) == null ? void 0 : _k.title) || null
6602
+ };
6603
+ })
6604
+ };
6605
+ };
6606
+ var firstUserError = (userErrors) => {
6607
+ const error = userErrors == null ? void 0 : userErrors[0];
6608
+ if (!error) return null;
6609
+ const message = new Error(error.message || "Shopify cart error");
6610
+ message.userError = true;
6611
+ return message;
6612
+ };
6613
+ var createCheckoutToken = async ({ fetcher, clientId, clientSecret } = {}) => {
6614
+ if (!clientId || !clientSecret) {
6615
+ throw new Error("createCheckoutToken requires clientId and clientSecret");
6616
+ }
6617
+ ;
6618
+ const response = await request({
6619
+ fetcher,
6620
+ method: "POST",
6621
+ url: "https://api.shopify.com/auth/access_token",
6622
+ body: {
6623
+ client_id: clientId,
6624
+ client_secret: clientSecret,
6625
+ grant_type: "client_credentials"
6626
+ }
6627
+ });
6628
+ const token = response == null ? void 0 : response.access_token;
6629
+ if (!token) {
6630
+ throw new Error("Failed to create Shopify checkout token");
6631
+ }
6632
+ ;
6633
+ return token;
6634
+ };
6635
+ var cartCreate = async ({ fetcher, domain, storefrontAccessToken, lines }) => {
6636
+ var _a, _b;
6637
+ const { data: data2, errors } = await storefrontFetch({
6638
+ fetcher,
6639
+ domain,
6640
+ storefrontAccessToken,
6641
+ query: `
6642
+ mutation cartCreate($input: CartInput!) {
6643
+ cartCreate(input: $input) {
6644
+ cart {
6645
+ ${CART_FIELDS}
6646
+ }
6647
+ userErrors {
6648
+ field
6649
+ message
6650
+ }
6651
+ }
6652
+ }
6653
+ `,
6654
+ variables: {
6655
+ input: {
6656
+ lines
6657
+ }
6658
+ }
6659
+ });
6660
+ if (errors) {
6661
+ throw new Error("Failed to create Shopify cart");
6662
+ }
6663
+ ;
6664
+ const userError = firstUserError((_a = data2 == null ? void 0 : data2.cartCreate) == null ? void 0 : _a.userErrors);
6665
+ if (userError) throw userError;
6666
+ return mapCart((_b = data2 == null ? void 0 : data2.cartCreate) == null ? void 0 : _b.cart);
6667
+ };
6668
+ var cartGet = async ({ fetcher, domain, storefrontAccessToken, cartId }) => {
6669
+ const { data: data2, errors } = await storefrontFetch({
6670
+ fetcher,
6671
+ domain,
6672
+ storefrontAccessToken,
6673
+ query: `
6674
+ query cart($id: ID!) {
6675
+ cart(id: $id) {
6676
+ ${CART_FIELDS}
6677
+ }
6678
+ }
6679
+ `,
6680
+ variables: {
6681
+ id: cartId
6682
+ }
6683
+ });
6684
+ if (errors) {
6685
+ throw new Error("Failed to fetch Shopify cart");
6686
+ }
6687
+ ;
6688
+ return mapCart(data2 == null ? void 0 : data2.cart);
6689
+ };
6690
+ var cartLinesAdd = async ({ fetcher, domain, storefrontAccessToken, cartId, lines }) => {
6691
+ var _a, _b;
6692
+ const { data: data2, errors } = await storefrontFetch({
6693
+ fetcher,
6694
+ domain,
6695
+ storefrontAccessToken,
6696
+ query: `
6697
+ mutation cartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {
6698
+ cartLinesAdd(cartId: $cartId, lines: $lines) {
6699
+ cart {
6700
+ ${CART_FIELDS}
6701
+ }
6702
+ userErrors {
6703
+ field
6704
+ message
6705
+ }
6706
+ }
6707
+ }
6708
+ `,
6709
+ variables: {
6710
+ cartId,
6711
+ lines
6712
+ }
6713
+ });
6714
+ if (errors) {
6715
+ throw new Error("Failed to add Shopify cart lines");
6716
+ }
6717
+ ;
6718
+ const userError = firstUserError((_a = data2 == null ? void 0 : data2.cartLinesAdd) == null ? void 0 : _a.userErrors);
6719
+ if (userError) throw userError;
6720
+ return mapCart((_b = data2 == null ? void 0 : data2.cartLinesAdd) == null ? void 0 : _b.cart);
6721
+ };
6722
+ var cartLinesRemove = async ({ fetcher, domain, storefrontAccessToken, cartId, lineIds }) => {
6723
+ var _a, _b;
6724
+ const { data: data2, errors } = await storefrontFetch({
6725
+ fetcher,
6726
+ domain,
6727
+ storefrontAccessToken,
6728
+ query: `
6729
+ mutation cartLinesRemove($cartId: ID!, $lineIds: [ID!]!) {
6730
+ cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {
6731
+ cart {
6732
+ ${CART_FIELDS}
6733
+ }
6734
+ userErrors {
6735
+ field
6736
+ message
6737
+ }
6738
+ }
6739
+ }
6740
+ `,
6741
+ variables: {
6742
+ cartId,
6743
+ lineIds
6744
+ }
6745
+ });
6746
+ if (errors) {
6747
+ throw new Error("Failed to remove Shopify cart lines");
6748
+ }
6749
+ ;
6750
+ const userError = firstUserError((_a = data2 == null ? void 0 : data2.cartLinesRemove) == null ? void 0 : _a.userErrors);
6751
+ if (userError) throw userError;
6752
+ return mapCart((_b = data2 == null ? void 0 : data2.cartLinesRemove) == null ? void 0 : _b.cart);
6753
+ };
6754
+ var cartLinesUpdate = async ({ fetcher, domain, storefrontAccessToken, cartId, lines }) => {
6755
+ var _a, _b;
6756
+ const { data: data2, errors } = await storefrontFetch({
6757
+ fetcher,
6758
+ domain,
6759
+ storefrontAccessToken,
6760
+ query: `
6761
+ mutation cartLinesUpdate($cartId: ID!, $lines: [CartLineUpdateInput!]!) {
6762
+ cartLinesUpdate(cartId: $cartId, lines: $lines) {
6763
+ cart {
6764
+ ${CART_FIELDS}
6765
+ }
6766
+ userErrors {
6767
+ field
6768
+ message
6769
+ }
6770
+ }
6771
+ }
6772
+ `,
6773
+ variables: {
6774
+ cartId,
6775
+ lines
6776
+ }
6777
+ });
6778
+ if (errors) {
6779
+ throw new Error("Failed to update Shopify cart lines");
6780
+ }
6781
+ ;
6782
+ const userError = firstUserError((_a = data2 == null ? void 0 : data2.cartLinesUpdate) == null ? void 0 : _a.userErrors);
6783
+ if (userError) throw userError;
6784
+ return mapCart((_b = data2 == null ? void 0 : data2.cartLinesUpdate) == null ? void 0 : _b.cart);
6785
+ };
6786
+
6787
+ // lib/email.js
6788
+ var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
6789
+ var toCanonicalEmail = (value) => {
6790
+ if (!value || typeof value !== "string") return null;
6791
+ const email = value.trim().toLowerCase();
6792
+ const at = email.lastIndexOf("@");
6793
+ if (at < 1 || at === email.length - 1) return null;
6794
+ let local = email.slice(0, at);
6795
+ const domain = email.slice(at + 1);
6796
+ const plus = local.indexOf("+");
6797
+ if (plus > 0) local = local.slice(0, plus);
6798
+ if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
6799
+ if (!local) return null;
6800
+ return local + "@" + domain;
6801
+ };
6802
+
6803
+ // lib/oauth/index.js
6804
+ var lifetimes = {
6805
+ access: 60 * 60 * 8,
6806
+ // 8 hours
6807
+ authorizationCode: 10 * 60,
6808
+ // 10 minutes
6809
+ code: 15 * 60,
6810
+ // 15 minutes (email OTC)
6811
+ refresh: 30 * 24 * 60 * 60
6812
+ // 30 days
6813
+ };
6814
+ var tokenTypes = {
6815
+ access: "access",
6816
+ oauthState: "oauth.state",
6817
+ pat: "pat",
6818
+ refresh: "refresh"
6819
+ };
6820
+ var scopes = [
6821
+ "profile:read",
6822
+ "profile:write",
6823
+ "organization:read",
6824
+ "organization:write",
6825
+ "campaigns:read",
6826
+ "campaigns:write",
6827
+ "contacts:read",
6828
+ "contacts:write",
6829
+ "workflows:read",
6830
+ "workflows:write",
6831
+ "connections:read",
6832
+ "connections:write",
6833
+ "billing:read",
6834
+ "billing:write",
6835
+ "admin"
6836
+ ];
6837
+ var developer = [
6838
+ "profile:read",
6839
+ "organization:read",
6840
+ "campaigns:read",
6841
+ "campaigns:write",
6842
+ "contacts:read",
6843
+ "contacts:write",
6844
+ "workflows:read",
6845
+ "workflows:write",
6846
+ "connections:read",
6847
+ "connections:write"
6848
+ ];
6849
+ var scopeLabels = {
6850
+ "profile:read": "Read own profile",
6851
+ "profile:write": "Update own profile",
6852
+ "organization:read": "Read organization info",
6853
+ "organization:write": "Manage organization",
6854
+ "campaigns:read": "Read campaigns",
6855
+ "campaigns:write": "Manage campaigns",
6856
+ "contacts:read": "Read contacts",
6857
+ "contacts:write": "Manage contacts",
6858
+ "workflows:read": "Read workflows",
6859
+ "workflows:write": "Manage workflows",
6860
+ "connections:read": "Read integrations",
6861
+ "connections:write": "Manage integrations",
6862
+ "billing:read": "Read billing",
6863
+ "billing:write": "Manage billing",
6864
+ admin: "Admin access"
6865
+ };
6866
+ var toOption = (scope) => ({
6867
+ key: scopeLabels[scope] || scope,
6868
+ value: scope
6869
+ });
6870
+ var developerOptions = developer.map(toOption);
6871
+ var scopeOptions = scopes.map(toOption);
6872
+ var hashToken = (raw) => hash(raw, process.env.HMAC_OAUTH_TOKEN_KEY);
6873
+
6874
+ // lib/sanitize.js
6875
+ var import_disposable_email_domains = __toESM(require("disposable-email-domains/index.js"), 1);
6876
+ var disposableBlacklist = new Set(import_disposable_email_domains.default.map((d) => d.toLowerCase()));
6877
+ var sanitizeDomain = (value, pattern) => {
6878
+ if (!value) return value;
6879
+ const cleaned = value.trim().toLowerCase().replace(/^https?:\/\//i, "").replace(/\/+$/, "");
6880
+ if (pattern) {
6881
+ const match = cleaned.match(pattern);
6882
+ return match ? match[0] : cleaned;
6883
+ }
6884
+ return cleaned;
6885
+ };
6886
+
6887
+ // lib/slugify.js
6888
+ var import_slugify = __toESM(require("slugify"), 1);
6889
+ var slugify = (value, nochars = false) => {
6890
+ const remove = nochars ? /[-?*+~.()'"!:@#^_{}\[\];,/\\]/g : /[?*+~.()'"!:@#^_{}\[\];,/\\]/g;
6891
+ const replacement = nochars ? "" : "-";
6892
+ return (0, import_slugify.default)(
6893
+ value,
6894
+ {
6895
+ remove,
6896
+ replacement,
6897
+ lower: true,
6898
+ trim: true
6899
+ }
6900
+ );
6901
+ };
6902
+
6903
+ // lib/connections/manifests/shopify.js
6904
+ var client = Object.freeze({
6905
+ admin: admin_exports,
6906
+ billing: billing_exports,
6907
+ oauth: oauth_exports,
6908
+ partner: partner_exports,
6909
+ storefront: storefront_exports
6910
+ });
6911
+ var toLine = ({
6912
+ price,
6913
+ product_id: productId,
6914
+ quantity,
6915
+ title,
6916
+ variant_id: variantId,
6917
+ variant_title: variantTitle
6918
+ }) => ({
6919
+ price: parseFloat(price) || 0,
6920
+ productId: productId ? "gid://shopify/Product/" + productId : null,
6921
+ quantity: quantity || 1,
6922
+ title: title || null,
6923
+ variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
6924
+ variantTitle: variantTitle || null
6925
+ });
6926
+ var attributeLineItems = (lineItems = []) => lineItems.reduce(
6927
+ (acc, item) => {
6928
+ const attrs = (item.properties || []).reduce(
6929
+ (map, { name, value }) => {
6930
+ map[name] = value;
6931
+ return map;
6932
+ },
6933
+ {}
6934
+ );
6935
+ if (!attrs["_drwbrdg_ca"]) return acc;
6936
+ if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
6937
+ const line = toLine(item);
6938
+ acc.attributedGross += line.price * line.quantity;
6939
+ acc.attributedLines.push(line);
6940
+ return acc;
6941
+ },
6942
+ { attrMap: {}, attributedGross: 0, attributedLines: [] }
6943
+ );
6944
+ var generateDiscountCode = (0, import_nanoid.customAlphabet)("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
6945
+ var blockedReason = (discount) => {
6946
+ var _a;
6947
+ if ((discount == null ? void 0 : discount.status) === "EXPIRED") return "This discount has expired.";
6948
+ const buyers = (_a = discount == null ? void 0 : discount.context) == null ? void 0 : _a.__typename;
6949
+ if (buyers && buyers !== "DiscountBuyerSelectionAll") {
6950
+ return "This discount is limited to specific buyers in Shopify, so a code issued to an entrant won't work. Set it to all customers to use it here.";
6951
+ }
6952
+ ;
6953
+ if (typeof (discount == null ? void 0 : discount.usageLimit) === "number" && discount.usageLimit > 0 && ((discount == null ? void 0 : discount.asyncUsageCount) || 0) >= discount.usageLimit) {
6954
+ return "This discount has reached its total usage limit.";
6955
+ }
6956
+ ;
6957
+ return null;
6958
+ };
6959
+ var discountWarning = (discount) => {
6960
+ if ((discount == null ? void 0 : discount.status) === "SCHEDULED") {
6961
+ return "This discount hasn't started yet, so codes issued before it does won't work until then.";
6962
+ }
6963
+ ;
6964
+ if (discount == null ? void 0 : discount.appliesOncePerCustomer) return "Each customer can use this discount only once.";
6965
+ return null;
6966
+ };
6967
+ var ORDER_EVENT_HANDLE = slugify("drawbridge-orders");
6968
+ var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
6969
+ var OAUTH_ERROR_SOURCE = "oauth";
6970
+ var BILLING_ERROR_SOURCE = "billing";
6971
+ var BILLING_ERROR_MESSAGE = "Order billing isn't set up for this store \u2014 reselect and approve the plan from the Shopify connection page.";
6972
+ var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
6973
+ var inbound = {
6974
+ headers: {
6975
+ event: "x-shopify-topic",
6976
+ id: "x-shopify-webhook-id",
6977
+ shop: "x-shopify-shop-domain",
6978
+ signature: "x-shopify-hmac-sha256"
6979
+ },
6980
+ signature: {
6981
+ algorithm: "sha256",
6982
+ encoding: "base64",
6983
+ secret: "SHOPIFY_API_SECRET"
6984
+ }
6985
+ };
6986
+ var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
6987
+ "customers/data_request",
6988
+ "customers/redact",
6989
+ "shop/redact"
6990
+ ]);
6991
+ var refusal = (message, status) => Object.assign(new Error(message), { status });
6992
+ var LINK_TOKEN_TTL_MS = 30 * 60 * 1e3;
6993
+ var CONNECTABLE_STATUSES = ["active", "unsubscribed"];
6994
+ var merchantOrganizations = ({ read, user }) => read.aggregate({
6995
+ collection: "organization",
6996
+ pipeline: [
6997
+ // A member qualifies only at `manage`; an owner always qualifies.
6998
+ {
6999
+ $lookup: {
7000
+ as: "membership",
7001
+ from: "member",
7002
+ let: { organization: "$id" },
7003
+ pipeline: [
7004
+ {
7005
+ $match: {
7006
+ $expr: { $eq: ["$organization", "$$organization"] },
7007
+ "capabilities.connections": "manage",
7008
+ status: "accepted",
7009
+ user
7010
+ }
7011
+ },
7012
+ { $limit: 1 },
7013
+ { $project: { _id: 0, organization: 1 } }
7014
+ ]
7015
+ }
7016
+ },
7017
+ {
7018
+ $match: {
7019
+ status: { $ne: "canceled" },
7020
+ $or: [{ owner: user }, { "membership.0": { $exists: true } }]
7021
+ }
7022
+ },
7023
+ // `organization.subscription` is a subscription RECORD ID — resolved here so
7024
+ // the list can read the real plan and conversion rate. Without it every org
7025
+ // rendered as free tier.
7026
+ { $lookup: { as: "subscription", foreignField: "id", from: "subscription", localField: "subscription" } },
7027
+ { $unwind: { path: "$subscription", preserveNullAndEmptyArrays: true } },
7028
+ {
7029
+ $lookup: {
7030
+ as: "connection",
7031
+ foreignField: "organization",
7032
+ from: "connection",
7033
+ localField: "id",
7034
+ pipeline: [
7035
+ { $match: { slug: "shopify" } },
7036
+ { $limit: 1 },
7037
+ { $project: { _id: 0, id: 1, shop: 1, status: 1 } }
7038
+ ]
7039
+ }
7040
+ },
7041
+ { $unwind: { path: "$connection", preserveNullAndEmptyArrays: true } },
7042
+ { $project: { _id: 0, billingStatus: "$status", connection: 1, id: 1, name: "$title", subscription: 1 } },
7043
+ { $sort: { name: 1 } }
7044
+ ]
7045
+ });
7046
+ var storePlan = async ({ record, shopify }) => {
7047
+ var _a;
7048
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
7049
+ if (!(settings == null ? void 0 : settings.accessToken)) return { active: false, name: null };
7050
+ try {
7051
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
7052
+ adminAccessToken: settings.accessToken,
7053
+ domain: record.shop
7054
+ });
7055
+ const active = (subscriptions || []).length > 0;
7056
+ const metered = active && subscriptions.some((subscription) => subscription.metered === true) ? true : null;
7057
+ return { active, metered, name: active ? ((_a = subscriptions[0]) == null ? void 0 : _a.name) || null : null };
7058
+ } catch (_) {
7059
+ return { active: false, name: null, unavailable: true };
7060
+ }
7061
+ };
7062
+ var releaseApprovals = async ({ context, read, shopify }) => {
7063
+ var _a;
7064
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
7065
+ if (!shop) throw refusal("shop is required", 400);
7066
+ const record = await read.get({ collection: "shop", query: { shop } });
7067
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
7068
+ if (!(settings == null ? void 0 : settings.accessToken)) throw refusal("Store is not installed", 409);
7069
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
7070
+ adminAccessToken: settings.accessToken,
7071
+ domain: shop
7072
+ });
7073
+ for (const subscription of subscriptions || []) {
7074
+ const data2 = await shopify.admin.adminFetch({
7075
+ adminAccessToken: settings.accessToken,
7076
+ domain: shop,
7077
+ query: "mutation appSubscriptionCancel( $id : ID! ) { appSubscriptionCancel( id : $id ) { appSubscription { id status } userErrors { field message } } }",
7078
+ variables: { id: subscription.id }
7079
+ });
7080
+ const [userError] = ((_a = data2 == null ? void 0 : data2.appSubscriptionCancel) == null ? void 0 : _a.userErrors) || [];
7081
+ if (userError) throw refusal(userError.message, 422);
7082
+ }
7083
+ return {
7084
+ message: "Released " + (subscriptions || []).length + " approval(s).",
7085
+ request: { shop },
7086
+ result: { ok: true }
7087
+ };
7088
+ };
7089
+ var LEDGER_WINDOW_MS = 30 * 24 * 60 * 60 * 1e3;
7090
+ var meterVerdict = async ({ adminAccessToken, ledgerFloor, partner, shop, shopId, shopify }) => {
7091
+ var _a;
7092
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({ adminAccessToken, domain: shop });
7093
+ let metered = (_a = subscriptions.find((subscription) => subscription.usageLineItemId)) == null ? void 0 : _a.usageLineItemId;
7094
+ if (!((partner == null ? void 0 : partner.partnerToken) && (partner == null ? void 0 : partner.partnerOrgId) && (partner == null ? void 0 : partner.partnerAppId) && shopId)) {
7095
+ return { boundaries: [], ledger: false, metered };
7096
+ }
7097
+ const accruals = await shopify.partner.getUsageChargeEvents({
7098
+ appId: "gid://shopify/App/" + partner.partnerAppId,
7099
+ first: 10,
7100
+ occurredAtMin: ledgerFloor.toISOString(),
7101
+ organizationId: partner.partnerOrgId,
7102
+ partnerToken: partner.partnerToken,
7103
+ shopId: "gid://shopify/Shop/" + shopId
7104
+ });
7105
+ const boundaries = (accruals || []).filter((event) => event.occurredAt).sort((a, b) => new Date(a.occurredAt) - new Date(b.occurredAt));
7106
+ const accrued = [...boundaries].reverse().find((event) => Number(event.usageQuantity) > 0);
7107
+ if (accrued) metered = String(accrued.chargeId || accrued.id);
7108
+ return { boundaries, ledger: true, metered };
7109
+ };
7110
+ var toVariant = (edge) => {
7111
+ var _a, _b, _c, _d;
7112
+ return {
7113
+ availableForSale: edge.node.availableForSale || false,
7114
+ currency: ((_a = edge.node.price) == null ? void 0 : _a.currencyCode) || null,
7115
+ id: edge.node.id,
7116
+ image: ((_b = edge.node.image) == null ? void 0 : _b.url) || null,
7117
+ price: parseFloat((_c = edge.node.price) == null ? void 0 : _c.amount) || null,
7118
+ requiresShipping: edge.node.requiresShipping || false,
7119
+ sale: parseFloat((_d = edge.node.compareAtPrice) == null ? void 0 : _d.amount) || null,
7120
+ title: edge.node.title !== "Default Title" ? edge.node.title : null
7121
+ };
7122
+ };
7123
+ var applyOutOfStock = async ({ domain, shopify, storefrontAccessToken, variants }) => {
7124
+ try {
7125
+ const outOfStock = new Set(await shopify.storefront.probeVariantsOutOfStock({
7126
+ domain,
7127
+ storefrontAccessToken,
7128
+ variantIds: variants.map((variant) => variant.id)
7129
+ }));
7130
+ return variants.map((variant) => ({
7131
+ ...variant,
7132
+ availableForSale: variant.availableForSale && !outOfStock.has(variant.id)
7133
+ }));
7134
+ } catch (_) {
7135
+ return variants;
7136
+ }
7137
+ };
7138
+ var sendFeedback = async ({ adminToken, connection: connection2, messages, productId, shopify, state }) => {
7139
+ try {
7140
+ await shopify.admin.sendProductResourceFeedback({
7141
+ adminAccessToken: await adminToken(),
7142
+ domain: connection2.shop,
7143
+ messages,
7144
+ productId,
7145
+ state
7146
+ });
7147
+ return null;
7148
+ } catch (error) {
7149
+ return error;
7150
+ }
7151
+ };
7152
+ var resolveProduct = async ({ connection: connection2, context, read }) => {
7153
+ const byId = (context == null ? void 0 : context.product) ? await read.get({ collection: "product", query: { id: context.product } }) : null;
7154
+ const row2 = byId || ((context == null ? void 0 : context.providerId) && ((context == null ? void 0 : context.shop) || (connection2 == null ? void 0 : connection2.shop)) ? await read.get({
7155
+ collection: "product",
7156
+ query: {
7157
+ "provider.id": context.providerId,
7158
+ "provider.slug": "shopify",
7159
+ "source.domain": context.shop || connection2.shop
7160
+ }
7161
+ }) : null);
7162
+ return row2;
7163
+ };
7164
+ var UNAVAILABLE_FEEDBACK = "Drawbridge can't display this product. Check it is active and available in the United States.";
7165
+ var NOT_FOUND = "Shopify product not found";
7166
+ var syncProduct = async ({ adminToken, connection: connection2, context, read, settings, shopify }) => {
7167
+ var _a, _b, _c;
7168
+ const row2 = await resolveProduct({ connection: connection2, context, read });
7169
+ if (!row2) return { message: "No product row to sync.", request: { product: (context == null ? void 0 : context.product) || null }, skipped: true };
7170
+ const domain = connection2.shop;
7171
+ const providerId = (_a = row2.provider) == null ? void 0 : _a.id;
7172
+ const request2 = { product: row2.id, providerId: providerId || null, shop: domain };
7173
+ let product;
7174
+ try {
7175
+ product = await shopify.storefront.getProduct({
7176
+ domain,
7177
+ productId: providerId,
7178
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
7179
+ });
7180
+ } catch (error) {
7181
+ if (error.message !== NOT_FOUND) throw error;
7182
+ const failed2 = await sendFeedback({
7183
+ adminToken,
7184
+ connection: connection2,
7185
+ messages: [UNAVAILABLE_FEEDBACK],
7186
+ productId: providerId,
7187
+ shopify,
7188
+ state: "REQUIRES_ACTION"
7189
+ });
7190
+ return {
7191
+ failed: failed2 ? [failed2.message] : void 0,
7192
+ message: "Storefront cannot see this product \u2014 deactivated.",
7193
+ request: request2,
7194
+ result: { status: "inactive" },
7195
+ writes: [
7196
+ {
7197
+ collection: "product",
7198
+ data: { $set: { status: "inactive" } },
7199
+ operation: "update",
7200
+ query: { id: row2.id }
7201
+ },
7202
+ {
7203
+ collection: "advertisement",
7204
+ data: { $set: { status: "drafted" } },
7205
+ multiple: true,
7206
+ operation: "update",
7207
+ query: { product: row2.id }
7208
+ }
7209
+ ]
7210
+ };
7211
+ }
7212
+ const variants = await applyOutOfStock({
7213
+ domain,
7214
+ shopify,
7215
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken,
7216
+ variants: (((_b = product == null ? void 0 : product.variants) == null ? void 0 : _b.edges) || []).map(toVariant)
7217
+ });
7218
+ const failed = await sendFeedback({
7219
+ adminToken,
7220
+ connection: connection2,
7221
+ messages: [],
7222
+ productId: providerId,
7223
+ shopify,
7224
+ state: "ACCEPTED"
7225
+ });
7226
+ return {
7227
+ // EVERYTHING PAST THE FIRST PAGE, filled in silently. The first page is
7228
+ // written above; a product with thousands of variants becomes N short
7229
+ // sequential jobs rather than one long loop that risks a BullMQ stall.
7230
+ enqueues: [{
7231
+ data: { operation: "variants", product: row2.id },
7232
+ name: "sync",
7233
+ options: { jobId: "product.shopify.variants." + row2.id + "." + Date.now() },
7234
+ queue: "product.shopify.variants"
7235
+ }],
7236
+ failed: failed ? [failed.message] : void 0,
7237
+ message: "Synced " + (product.title || "product") + ".",
7238
+ request: request2,
7239
+ result: { status: "active", variants: variants.length },
7240
+ writes: [{
7241
+ collection: "product",
7242
+ data: {
7243
+ $set: {
7244
+ description: product.description || null,
7245
+ image: ((_c = product.featuredImage) == null ? void 0 : _c.url) || null,
7246
+ // A successful sync PROVES channel visibility, which reverses the
7247
+ // deactivation above. Ads stay drafted.
7248
+ status: "active",
7249
+ title: product.title || null,
7250
+ type: product.productType || null,
7251
+ url: domain && product.handle ? "https://" + domain + "/products/" + product.handle : null,
7252
+ variants
7253
+ }
7254
+ },
7255
+ operation: "update",
7256
+ query: { id: row2.id }
7257
+ }]
7258
+ };
7259
+ };
7260
+ var syncVariants = async ({ connection: connection2, context, read, settings, shopify }) => {
7261
+ var _a, _b, _c;
7262
+ const row2 = await resolveProduct({ connection: connection2, context, read });
7263
+ if (!row2) return { message: "No product row to paginate.", request: { product: (context == null ? void 0 : context.product) || null }, skipped: true };
7264
+ const cursor = (context == null ? void 0 : context.cursor) || null;
7265
+ const request2 = { cursor, product: row2.id };
7266
+ let page2;
7267
+ try {
7268
+ page2 = await shopify.storefront.getProductVariantsPage({
7269
+ cursor,
7270
+ domain: connection2.shop,
7271
+ productId: (_a = row2.provider) == null ? void 0 : _a.id,
7272
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
7273
+ });
7274
+ } catch (error) {
7275
+ if (error.message !== NOT_FOUND) throw error;
7276
+ return { message: "Storefront lost this product mid-pagination \u2014 stopping.", request: request2, skipped: true };
7277
+ }
7278
+ const variants = await applyOutOfStock({
7279
+ domain: connection2.shop,
7280
+ shopify,
7281
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken,
7282
+ variants: (page2.edges || []).map(toVariant)
7283
+ });
7284
+ return {
7285
+ ...((_b = page2.pageInfo) == null ? void 0 : _b.hasNextPage) && { enqueues: [{
7286
+ data: { cursor: page2.pageInfo.endCursor, operation: "variants", product: row2.id },
7287
+ name: "page",
7288
+ options: { jobId: "product.shopify.variants." + row2.id + "." + Date.now() },
7289
+ queue: "product.shopify.variants"
7290
+ }] },
7291
+ message: variants.length + " variant(s) on this page.",
7292
+ request: request2,
7293
+ result: { hasNextPage: Boolean((_c = page2.pageInfo) == null ? void 0 : _c.hasNextPage), variants: variants.length },
7294
+ writes: [{
7295
+ collection: "product",
7296
+ data: cursor ? { $push: { variants: { $each: variants } } } : { $set: { variants } },
7297
+ operation: "update",
7298
+ query: { id: row2.id }
7299
+ }]
7300
+ };
7301
+ };
7302
+ var shopify_default2 = {
7303
+ // THE WORDS ON THE BUTTONS. `listing` was `content.redirect.title`, which put
7304
+ // a BUTTON LABEL inside the copy object next to a url — the title and the
7305
+ // address it belongs to sat at different levels and could drift apart.
7306
+ //
7307
+ // It names where the link GOES rather than what it does: installing happens on
7308
+ // the App Store listing, and the dashboard must never imply a store can be
7309
+ // linked from inside it.
7310
+ actions: {
7311
+ create: null,
7312
+ listing: "View on the Shopify App Store",
7313
+ manage: null,
7314
+ update: null
7315
+ },
7316
+ // INSTALL, not oauth. The grant is an OAuth grant, but the merchant never
7317
+ // sees a consent screen we sent them to -- they start at the App Store, and
7318
+ // the install completes inside Shopify admin without redirecting back. A
7319
+ // Connect button here would be lying about where connecting happens.
7320
+ auth: {
7321
+ // ONE STORE PER ORGANIZATION. A Shopify install IS a store, and a second
7322
+ // one would give an organization two catalogues, two order streams and two
7323
+ // usage meters with nothing to say which is authoritative.
7324
+ //
7325
+ // DECLARED AND ENFORCED BY NOTHING, measured 2026-09-13: no repo reads this
7326
+ // key, and the connection collection's { organization, slug } index is not
7327
+ // unique. So a second Shopify connection would be accepted today. The gate
7328
+ // belongs at the connect route with a unique partial index behind it, and
7329
+ // that is api work — this is the declaration it will read.
5291
7330
  exclusive: true,
5292
7331
  generated: false,
5293
7332
  // THE MERCHANT STARTS AT SHOPIFY, not here. They install the app from
@@ -5446,8 +7485,8 @@ var shopify_default2 = {
5446
7485
  // string; this answers what is missing from it.
5447
7486
  //
5448
7487
  // `shopify` is injected for the same reason it is everywhere else — this
5449
- // package cannot import @drawbridge/shopify, which depends on it.
5450
- scopes: ({ scope }, { shopify } = {}) => ({ result: { missing: scope ? shopify.oauth.missingScopes(scope) : null } }),
7488
+ // client is imported here and defaulted, never wired in by a caller.
7489
+ scopes: ({ scope }, { shopify = client } = {}) => ({ result: { missing: scope ? shopify.oauth.missingScopes(scope) : null } }),
5451
7490
  // Shopify's install grant is exchanged inside its own app flow, not
5452
7491
  // through the shared OAuth runner.
5453
7492
  token: false
@@ -5461,17 +7500,53 @@ var shopify_default2 = {
5461
7500
  // can reference another), `dispatch` (the caller's own coordinator table,
5462
7501
  // for the hooks that are dispatches).
5463
7502
  commerce: {
5464
- // NOT YET. The Checkout Kit cart path is `api/route/subdomain.js`, six direct
5465
- // calls into `@drawbridge/shopify/storefront` that write nothing — which is
5466
- // exactly why it never became a hook: a hook is reached to have its effects
5467
- // performed, and this one has none to perform. It moves here when the vendor
5468
- // client moves into the manifest and `subdomain.js` stops importing the
5469
- // package directly.
5470
- cart: false,
7503
+ // THE CHECKOUT KIT CART. Six operations that were six direct calls into
7504
+ // the storefront client from api/route/subdomain.js.
7505
+ //
7506
+ // IT WRITES NOTHING, which is exactly why it was the last surface to
7507
+ // become a hook a hook is usually reached to have its effects performed
7508
+ // and this one has none. That reasoning was wrong: a hook is also the one
7509
+ // place a vendor's client is allowed to be called from, and leaving the
7510
+ // cart out meant a public route importing a vendor SDK directly.
7511
+ //
7512
+ // ONE HOOK, OPERATION IN THE CONTEXT, the same shape `inbound.process`
7513
+ // uses for its topic table. Six slots would be six names in the closed
7514
+ // vocabulary for one question — what does this shopper's cart look like
7515
+ // now — asked six ways.
7516
+ //
7517
+ // A USER ERROR IS A 400 AND THE SHOPPER'S OWN WORDS. Shopify's cart
7518
+ // mutations answer "that variant is sold out" as a userError rather than a
7519
+ // transport failure, and the route it replaced already told the two apart.
7520
+ // runHook carries `status` off a thrown error, so it survives to the
7521
+ // caller; the rest of a thrown error's shape does not.
7522
+ cart: async ({ clientId, clientSecret, context, settings }, { fetcher, shopify = client } = {}) => {
7523
+ const { cartId, lineIds, lines, operation } = context || {};
7524
+ const { domain, storefrontAccessToken } = settings || {};
7525
+ if (operation === "checkout") {
7526
+ const token = await shopify.storefront.createCheckoutToken({ clientId, clientSecret, fetcher });
7527
+ return { message: "Checkout token minted.", result: { token } };
7528
+ }
7529
+ const storefront = { domain, fetcher, storefrontAccessToken };
7530
+ try {
7531
+ const cart = await ({
7532
+ create: () => shopify.storefront.cartCreate({ ...storefront, lines }),
7533
+ get: () => shopify.storefront.cartGet({ ...storefront, cartId }),
7534
+ linesAdd: () => shopify.storefront.cartLinesAdd({ ...storefront, cartId, lines }),
7535
+ linesRemove: () => shopify.storefront.cartLinesRemove({ ...storefront, cartId, lineIds }),
7536
+ linesUpdate: () => shopify.storefront.cartLinesUpdate({ ...storefront, cartId, lines })
7537
+ }[operation] || (() => {
7538
+ throw Object.assign(new Error("Unknown cart operation: " + operation), { status: 400 });
7539
+ }))();
7540
+ return { message: "Cart " + operation + ".", request: { cartId: cartId || null, operation }, result: cart };
7541
+ } catch (error) {
7542
+ if (error == null ? void 0 : error.userError) throw Object.assign(error, { status: 400 });
7543
+ throw error;
7544
+ }
7545
+ },
5471
7546
  // MINT A DISCOUNT CODE against the merchant's chosen discount, mapped to
5472
7547
  // one lead — which is what lets an order that redeems it be attributed
5473
7548
  // back.
5474
- code: async ({ connection: connection2, context, step }, { adminToken, shopify } = {}) => {
7549
+ code: async ({ connection: connection2, context, step }, { adminToken, shopify = client } = {}) => {
5475
7550
  var _a;
5476
7551
  const discount = (_a = step.settings) == null ? void 0 : _a.discount;
5477
7552
  const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
@@ -5517,7 +7592,7 @@ var shopify_default2 = {
5517
7592
  // customer at the store is a support ticket: the context may already
5518
7593
  // carry the id from an earlier step, the lead may already be linked from
5519
7594
  // an earlier run, and Shopify's own get-or-create settles the rest.
5520
- customer: async ({ connection: connection2, context }, { adminToken, read, shopify } = {}) => {
7595
+ customer: async ({ connection: connection2, context }, { adminToken, read, shopify = client } = {}) => {
5521
7596
  const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
5522
7597
  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 };
5523
7598
  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 };
@@ -5567,6 +7642,30 @@ var shopify_default2 = {
5567
7642
  }]
5568
7643
  };
5569
7644
  },
7645
+ // HOW MANY ARE LEFT. Read at the moment a campaign's product list is
7646
+ // rendered rather than stored on the product, because stock is the one
7647
+ // product fact that is stale the instant it is written down.
7648
+ //
7649
+ // SUMMED HERE, not by the caller. Shopify answers per variant and every
7650
+ // caller wanted the total; the one that existed summed it inline, and
7651
+ // summing `Object.values()` over the raw map is how a cache wrapper's own
7652
+ // bookkeeping key got counted as a quantity.
7653
+ inventory: async ({ connection: connection2, context }, { adminToken, shopify = client } = {}) => {
7654
+ const productId = context == null ? void 0 : context.product;
7655
+ const request2 = { product: productId || null, shop: connection2.shop };
7656
+ if (!productId) return { message: "No product id \u2014 nothing to count.", request: request2, result: { total: null }, skipped: true };
7657
+ const adminAccessToken = await adminToken();
7658
+ const byVariant = await shopify.admin.getProductInventory({
7659
+ adminAccessToken,
7660
+ domain: connection2.shop,
7661
+ productId
7662
+ });
7663
+ return {
7664
+ message: "Inventory read.",
7665
+ request: request2,
7666
+ result: { total: Object.values(byVariant || {}).reduce((sum, quantity) => sum + quantity, 0) }
7667
+ };
7668
+ },
5570
7669
  // AN ORDER ARRIVED AT THE STORE. The largest hook in the family, because
5571
7670
  // attribution genuinely is: an order can reach Drawbridge two ways and
5572
7671
  // they bill differently.
@@ -5926,10 +8025,28 @@ var shopify_default2 = {
5926
8025
  //
5927
8026
  // The shell has already refused a missing or inactive Shopify connection,
5928
8027
  // so what is left is the two things only this hook can know are wrong.
5929
- product: async ({ connection: connection2, context, workflow }, { mintId, read } = {}) => {
8028
+ // A PRODUCT, IN THREE MOVES. Nested by operation rather than by three
8029
+ // slots in the closed vocabulary, the same shape inbound.process uses
8030
+ // for its topic table — they are one subject, and a vendor that syncs
8031
+ // products has to answer all three or none.
8032
+ //
8033
+ // record a webhook said a product changed: upsert the row and
8034
+ // queue the pull
8035
+ // sync pull the product from the storefront and write what it
8036
+ // says, including what it says by NOT answering
8037
+ // variants one page of variants, self-chaining
8038
+ //
8039
+ // `sync` and `variants` were 443 lines of drawbridge-sync's
8040
+ // queue/product.js — a shadow implementation of the step this manifest
8041
+ // already declared, importing three of the vendor's client modules from
8042
+ // a worker file.
8043
+ product: async ({ connection: connection2, context, settings, workflow }, { adminToken, mintId, read, shopify = client } = {}) => {
8044
+ const operation = (context == null ? void 0 : context.operation) || "record";
8045
+ if (operation === "sync") return syncProduct({ adminToken, connection: connection2, context, read, settings, shopify });
8046
+ if (operation === "variants") return syncVariants({ connection: connection2, context, read, settings, shopify });
5930
8047
  const request2 = {
5931
8048
  numericId: (context == null ? void 0 : context.id) || null,
5932
- organizationId: workflow.organization,
8049
+ organizationId: (workflow == null ? void 0 : workflow.organization) || null,
5933
8050
  title: (context == null ? void 0 : context.title) || null
5934
8051
  };
5935
8052
  if (!(context == null ? void 0 : context.id)) return { message: "Skipped \u2014 product webhook payload had no id.", request: request2, response: { skipped: true }, skipped: true };
@@ -5979,9 +8096,612 @@ var shopify_default2 = {
5979
8096
  }
5980
8097
  },
5981
8098
  contacts: { remove: false, sync: false },
5982
- // The embedded-app surface. Only a vendor whose merchants arrive from its
5983
- // own app store has one.
5984
- install: false,
8099
+ // THE EMBEDDED-APP SURFACE. Only a vendor whose merchants arrive from its
8100
+ // own app store has one, and these thirteen slots are the thirteen routes
8101
+ // that used to live in api/route/shopify-embedded.js.
8102
+ //
8103
+ // A HOOK DESCRIBES ITS WRITES and the shell performs them, so none of these
8104
+ // holds a controller — `read` is the controller's read methods and nothing
8105
+ // else. Where one REFUSES it throws with a status, and the route answers
8106
+ // what it said. The helpers they share are above the manifest.
8107
+ install: {
8108
+ account: {
8109
+ // ESTABLISH THE DURABLE MERCHANT-TO-STORE LINK. The breakout
8110
+ // authenticates the merchant once, top-level, and stashes their user
8111
+ // token in `install.token.save`; App Bridge has already proven shop
8112
+ // control by the time this runs.
8113
+ //
8114
+ // THE STASHED TOKEN IS THE TRUST ANCHOR, not merely any valid user
8115
+ // token: the presented one must BE this shop's one-shot handoff token,
8116
+ // unexpired, and an access or pat record — a refresh or oauth-state
8117
+ // token that happens to resolve to a user must not qualify, which is
8118
+ // the rule a session is held to in drawbridge-api's middleware.
8119
+ link: async ({ context }, { read } = {}) => {
8120
+ var _a;
8121
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8122
+ const token = context == null ? void 0 : context.token;
8123
+ if (!shop || !token) throw refusal("shop and token are required", 400);
8124
+ const now = /* @__PURE__ */ new Date();
8125
+ const record = await read.get({ collection: "shop", query: { shop } });
8126
+ const stashed = (record == null ? void 0 : record.linkToken) ? (_a = decrypt(record.linkToken)) == null ? void 0 : _a.token : null;
8127
+ const expired = !(record == null ? void 0 : record.linkTokenExpiresAt) || new Date(record.linkTokenExpiresAt) <= now;
8128
+ if (!stashed || expired || stashed !== token) throw refusal("Invalid or expired link token", 401);
8129
+ const granted = await read.get({
8130
+ collection: "token",
8131
+ query: {
8132
+ revoked: false,
8133
+ tokenHash: hashToken(token),
8134
+ type: { $in: [tokenTypes.access, tokenTypes.pat] }
8135
+ }
8136
+ });
8137
+ if (!(granted == null ? void 0 : granted.user) || granted.expiresAt && new Date(granted.expiresAt) <= now) {
8138
+ throw refusal("Invalid or expired link token", 401);
8139
+ }
8140
+ const switching = Boolean(record == null ? void 0 : record.user) && record.user !== granted.user;
8141
+ const connections2 = switching ? await read.aggregate({
8142
+ collection: "connection",
8143
+ pipeline: [
8144
+ { $match: { shop, slug: "shopify" } },
8145
+ { $project: { _id: 0, id: 1 } }
8146
+ ]
8147
+ }) : [];
8148
+ return {
8149
+ message: switching ? "Linked to a different Drawbridge account." : "Linked.",
8150
+ request: { shop },
8151
+ result: { connected: true, switched: switching },
8152
+ // ALL OR NONE. A half-done switch is a store linked to the new
8153
+ // account while the old account's connections still serve from it.
8154
+ transaction: true,
8155
+ writes: [
8156
+ ...(connections2 || []).map((connection2) => ({
8157
+ collection: "connection",
8158
+ operation: "delete",
8159
+ query: { id: connection2.id }
8160
+ })),
8161
+ {
8162
+ collection: "shop",
8163
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null, user: granted.user } },
8164
+ operation: "update",
8165
+ query: { shop }
8166
+ }
8167
+ ]
8168
+ };
8169
+ },
8170
+ // DISCONNECT THE ACCOUNT FROM THE STORE. Every org connection goes and
8171
+ // the durable link clears; the offline token and the shop record stay,
8172
+ // because the app is still installed and the merchant may link a
8173
+ // different account next.
8174
+ unlink: async ({ context }, { read } = {}) => {
8175
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8176
+ if (!shop) throw refusal("shop is required", 400);
8177
+ const connections2 = await read.aggregate({
8178
+ collection: "connection",
8179
+ pipeline: [
8180
+ { $match: { shop, slug: "shopify" } },
8181
+ { $project: { _id: 0, id: 1 } }
8182
+ ]
8183
+ });
8184
+ return {
8185
+ message: "Unlinked " + (connections2 || []).length + " connection(s).",
8186
+ request: { shop },
8187
+ result: { ok: true },
8188
+ transaction: true,
8189
+ writes: [
8190
+ ...(connections2 || []).map((connection2) => ({
8191
+ collection: "connection",
8192
+ operation: "delete",
8193
+ query: { id: connection2.id }
8194
+ })),
8195
+ {
8196
+ collection: "shop",
8197
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null, user: null } },
8198
+ operation: "update",
8199
+ query: { shop }
8200
+ }
8201
+ ]
8202
+ };
8203
+ }
8204
+ },
8205
+ organizations: {
8206
+ // BIND ONE ORGANIZATION TO THIS STORE. The longest slot here, and every
8207
+ // gate in it came from a line in the route it replaces.
8208
+ add: async ({ context }, { currencies: currencies2, mintId, read, shopify = client } = {}) => {
8209
+ var _a, _b;
8210
+ const organization2 = context == null ? void 0 : context.organization;
8211
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8212
+ if (!shop) throw refusal("shop is required", 400);
8213
+ if (!organization2) throw refusal("organization is required", 400);
8214
+ const record = await read.get({ collection: "shop", query: { shop } });
8215
+ if (!(record == null ? void 0 : record.user)) throw refusal("Account is not connected for this store", 409);
8216
+ const owned = await merchantOrganizations({ read, user: record.user });
8217
+ const org = (owned || []).find((entry) => entry.id === organization2);
8218
+ if (!org) throw refusal("No access to this organization", 403);
8219
+ if (!CONNECTABLE_STATUSES.includes(org.billingStatus)) {
8220
+ throw refusal("This organization can't accept connections right now \u2014 check its billing status in the dashboard", 403);
8221
+ }
8222
+ if (org.connection && org.connection.shop !== shop) {
8223
+ throw refusal("This organization is already connected to another Shopify store", 409);
8224
+ }
8225
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
8226
+ if (!(settings == null ? void 0 : settings.accessToken)) {
8227
+ throw refusal("Store is not installed \u2014 open the app in the Shopify admin first", 409);
8228
+ }
8229
+ const plan = await storePlan({ record, shopify });
8230
+ if (plan.unavailable) throw refusal("Couldn't verify the store's plan \u2014 try again shortly", 502);
8231
+ if (!plan.active) throw refusal("Approve a plan before connecting organizations", 402);
8232
+ let storefront = null;
8233
+ if (!record.storefront) {
8234
+ try {
8235
+ const minted2 = await shopify.oauth.createStorefrontToken({
8236
+ adminAccessToken: settings.accessToken,
8237
+ shop
8238
+ });
8239
+ if (minted2) storefront = encrypt({ token: minted2 });
8240
+ } catch (_) {
8241
+ }
8242
+ }
8243
+ let currency = (record == null ? void 0 : record.currency) || null;
8244
+ let source = (record == null ? void 0 : record.source) || null;
8245
+ try {
8246
+ const shopData = await shopify.oauth.getShop({ adminAccessToken: settings.accessToken, shop });
8247
+ if (shopData) {
8248
+ currency = String(shopData.currency || "").toLowerCase() || null;
8249
+ source = { domain: shopData.myshopifyDomain, id: String(shopData.id), label: shopData.name };
8250
+ }
8251
+ } catch (_) {
8252
+ }
8253
+ if (currency && currencies2 && !currencies2.includes(currency)) {
8254
+ throw refusal("This store settles in a currency we can't bill yet. Connect a store with a supported settlement currency.", 422);
8255
+ }
8256
+ const minted = ((_a = org.connection) == null ? void 0 : _a.id) ? null : mintId();
8257
+ const connectionId = ((_b = org.connection) == null ? void 0 : _b.id) || minted.id;
8258
+ return {
8259
+ message: "Connected " + org.name + " to " + shop + ".",
8260
+ request: { organization: organization2, shop },
8261
+ result: { ok: true },
8262
+ transaction: true,
8263
+ writes: [
8264
+ ...storefront ? [{
8265
+ collection: "shop",
8266
+ data: { $set: { storefront } },
8267
+ operation: "update",
8268
+ query: { shop }
8269
+ }] : [],
8270
+ {
8271
+ collection: "connection",
8272
+ data: {
8273
+ $set: {
8274
+ currency,
8275
+ errors: [],
8276
+ // The token of record lives on the shared `shop` row; this
8277
+ // is the pointer that satisfies the required `settings`
8278
+ // string, and `auth.install.shared` declares how to read it.
8279
+ settings: encrypt({ ref: "shop", shop }),
8280
+ shop,
8281
+ status: "pending",
8282
+ ...source && { source }
8283
+ },
8284
+ $setOnInsert: {
8285
+ ...minted && { _id: minted._id, id: minted.id },
8286
+ feature: "organization:connection:shopify",
8287
+ organization: organization2,
8288
+ slug: "shopify"
8289
+ }
8290
+ },
8291
+ operation: "update",
8292
+ options: { upsert: true },
8293
+ query: { organization: organization2, slug: "shopify" }
8294
+ },
8295
+ {
8296
+ collection: "organization",
8297
+ data: {
8298
+ // $addToSet UNCONDITIONALLY. The route this replaces only
8299
+ // registered the refs when the upsert INSERTED, which meant an
8300
+ // org whose refs had drifted stayed drifted through every
8301
+ // re-link. Adding a member that is already there is a no-op,
8302
+ // so doing it every time costs nothing and repairs the drift.
8303
+ $addToSet: {
8304
+ "connections.groups": "ecommerce",
8305
+ "connections.ids": connectionId,
8306
+ "connections.keys": "shopify"
8307
+ },
8308
+ $set: { billingProvider: "shopify" }
8309
+ },
8310
+ operation: "update",
8311
+ query: { id: organization2 }
8312
+ }
8313
+ ]
8314
+ };
8315
+ },
8316
+ // WHAT THIS STORE CAN SEE: the linked merchant's organizations, the
8317
+ // store's live plan, and the products the merchant has to act on.
8318
+ //
8319
+ // AN ORG CONNECTED TO A DIFFERENT STORE IS OMITTED ENTIRELY, because
8320
+ // `add` would refuse it — a list that offers what the next call rejects
8321
+ // is worse than a shorter one.
8322
+ list: async ({ context }, { conversionRate: conversionRate2, planTitle, read, shopify = client } = {}) => {
8323
+ var _a;
8324
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8325
+ if (!shop) throw refusal("shop is required", 400);
8326
+ const record = await read.get({ collection: "shop", query: { shop } });
8327
+ if (!(record == null ? void 0 : record.user)) {
8328
+ return {
8329
+ message: "No account linked to this store.",
8330
+ request: { shop },
8331
+ result: {
8332
+ account: null,
8333
+ connected: false,
8334
+ organizations: [],
8335
+ plan: { active: false, name: null },
8336
+ unavailableProducts: [],
8337
+ unavailableProductsTotal: 0
8338
+ }
8339
+ };
8340
+ }
8341
+ const owned = await merchantOrganizations({ read, user: record.user });
8342
+ const organizations = (owned || []).filter((org) => !org.connection || org.connection.shop === shop).map((org) => {
8343
+ var _a2;
8344
+ return {
8345
+ // The org's OWN billing status decides whether `add` accepts it.
8346
+ // Sent up so the app can disable Connect and name the reason
8347
+ // rather than letting the merchant click into a 403 —
8348
+ // listed-but-blocked beats hidden, because an org vanishing from
8349
+ // the list is indistinguishable from a bug.
8350
+ billingStatus: org.billingStatus || null,
8351
+ connectable: CONNECTABLE_STATUSES.includes(org.billingStatus),
8352
+ connected: Boolean(org.connection),
8353
+ conversion: conversionRate2(org.subscription),
8354
+ id: org.id,
8355
+ name: org.name,
8356
+ plan: planTitle(org.subscription),
8357
+ status: ((_a2 = org.connection) == null ? void 0 : _a2.status) || null
8358
+ };
8359
+ });
8360
+ const connections2 = (owned || []).filter((org) => {
8361
+ var _a2;
8362
+ return ((_a2 = org.connection) == null ? void 0 : _a2.shop) === shop && org.connection.id;
8363
+ }).map((org) => org.connection.id);
8364
+ const [account, plan, unavailable] = await Promise.all([
8365
+ read.get({ collection: "user", query: { id: record.user } }),
8366
+ storePlan({ record, shopify }),
8367
+ connections2.length ? read.aggregate({
8368
+ collection: "product",
8369
+ pipeline: [
8370
+ { $match: { connections: { $in: connections2 }, "source.domain": shop, status: "inactive" } },
8371
+ // $facet so the app can name the first 25 AND report a
8372
+ // truthful total: listing 25 of 40 under "25 products need
8373
+ // attention" would understate the problem.
8374
+ {
8375
+ $facet: {
8376
+ items: [{ $sort: { title: 1 } }, { $limit: 25 }, { $project: { _id: 0, id: 1, title: 1 } }],
8377
+ total: [{ $count: "count" }]
8378
+ }
8379
+ }
8380
+ ]
8381
+ }) : []
8382
+ ]);
8383
+ const facet = (unavailable || [])[0] || {};
8384
+ if (plan.active && plan.metered !== true) {
8385
+ const stamped = await read.aggregate({
8386
+ collection: "connection",
8387
+ pipeline: [
8388
+ { $match: { shop, slug: "shopify" } },
8389
+ { $project: { _id: 0, "source.metered": 1 } }
8390
+ ]
8391
+ });
8392
+ const verdicts = (stamped || []).map((row2) => {
8393
+ var _a2;
8394
+ return (_a2 = row2 == null ? void 0 : row2.source) == null ? void 0 : _a2.metered;
8395
+ });
8396
+ if (verdicts.some((verdict) => typeof verdict === "string")) plan.metered = true;
8397
+ else if (verdicts.some((verdict) => verdict === null)) plan.metered = false;
8398
+ }
8399
+ return {
8400
+ message: organizations.length + " organization(s) for this store.",
8401
+ request: { shop },
8402
+ result: {
8403
+ account: { email: (account == null ? void 0 : account.email) || null },
8404
+ connected: true,
8405
+ organizations,
8406
+ plan,
8407
+ unavailableProducts: (facet.items || []).map((product) => ({
8408
+ id: product.id,
8409
+ title: product.title || "Untitled product"
8410
+ })),
8411
+ // The total can exceed the 25 listed above, and has to.
8412
+ unavailableProductsTotal: ((_a = (facet.total || [])[0]) == null ? void 0 : _a.count) || 0
8413
+ }
8414
+ };
8415
+ },
8416
+ // DISCONNECT ONE ORGANIZATION. The connection is deleted and nothing
8417
+ // else: every dependent — products, ads, steps, workflows, and the org's
8418
+ // own connection refs — is torn down by drawbridge-sync's connection
8419
+ // change stream. The shared token and the other orgs are untouched.
8420
+ remove: async ({ context }, { read } = {}) => {
8421
+ const organization2 = context == null ? void 0 : context.organization;
8422
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8423
+ if (!shop) throw refusal("shop is required", 400);
8424
+ if (!organization2) throw refusal("organization is required", 400);
8425
+ const record = await read.get({ collection: "shop", query: { shop } });
8426
+ if (!(record == null ? void 0 : record.user)) throw refusal("Account is not connected for this store", 409);
8427
+ const owned = await merchantOrganizations({ read, user: record.user });
8428
+ if (!(owned || []).some((entry) => entry.id === organization2)) {
8429
+ throw refusal("No access to this organization", 403);
8430
+ }
8431
+ const connection2 = await read.get({
8432
+ collection: "connection",
8433
+ query: { organization: organization2, shop, slug: "shopify" }
8434
+ });
8435
+ if (!connection2) throw refusal("No connection to remove", 404);
8436
+ return {
8437
+ message: "Disconnected.",
8438
+ request: { organization: organization2, shop },
8439
+ result: { ok: true },
8440
+ writes: [{ collection: "connection", operation: "delete", query: { id: connection2.id } }]
8441
+ };
8442
+ }
8443
+ },
8444
+ plan: {
8445
+ // RELEASE EVERY ACTIVE APPROVAL. The App Home then re-checks the plan
8446
+ // and falls back to "Choose a plan".
8447
+ cancel: ({ context }, { read, shopify = client } = {}) => releaseApprovals({ context, read, shopify }),
8448
+ // ONE ATTRIBUTED ORDER'S USAGE CHARGE. Enqueued per conversion by the
8449
+ // order step and run on a retrying queue, so this may be called
8450
+ // several times for one order — which is safe because the idempotency
8451
+ // key is PERMANENT for billing events and Shopify settles the repeat.
8452
+ //
8453
+ // THE HANDLE IS CHECKED AGAINST THE MANIFEST'S OWN DECLARATION, which
8454
+ // is a real strengthening of what it replaced: drawbridge-sync compared
8455
+ // the job's `handle` against the job's `transaction` — two fields from
8456
+ // the same enqueuer, so a drifted enqueuer agreed with itself. The
8457
+ // handle is the one string that decides whether the event bills at all,
8458
+ // and this is the file that publishes it.
8459
+ //
8460
+ // REFUSE BEFORE SENDING, because sending burns the order's PERMANENT
8461
+ // idempotency key on an event that misclassifies or mistraces. The
8462
+ // throw rides the queue's normal retry path and the abandoned-job alert
8463
+ // pages on exhaustion.
8464
+ //
8465
+ // DELIBERATELY NO TIMESTAMP. sendAppEvent defaults to the SEND time,
8466
+ // which is always inside the merchant's current billing cycle at the
8467
+ // moment of sending and so can never hit PERIOD_CLOSED. Pinning the
8468
+ // purchase time reads more correct and is strictly worse: a retry
8469
+ // backoff crossing a cycle boundary would carry a closed-cycle
8470
+ // timestamp, Shopify would 202-accept, silently drop it, and the
8471
+ // commission would be lost. Send-time's worst case is benign — the
8472
+ // charge lands in the next cycle, but it lands.
8473
+ charge: async ({ clientId, clientSecret, context, manifest }, { shopify = client } = {}) => {
8474
+ const { idempotencyKey, order, orderId, rate, revision, shopId, timestamp, transaction, value } = context || {};
8475
+ const handle = (context == null ? void 0 : context.handle) || manifest.auth.install.billing.handle;
8476
+ if (!transaction || !String(transaction).startsWith(handle + ".")) {
8477
+ throw new Error("shopify.usage.billing.handle.mismatch on order " + orderId + ": transaction " + (transaction || "null") + " does not carry handle " + handle + " \u2014 refusing to send");
8478
+ }
8479
+ await shopify.billing.sendAppEvent({
8480
+ clientId,
8481
+ clientSecret,
8482
+ eventHandle: handle,
8483
+ idempotencyKey,
8484
+ // The Shopify-side event record names the order that produced it.
8485
+ reference: transaction,
8486
+ // OPERATOR-ONLY, BOTH OF THEM, and absent on every automatic
8487
+ // send. `revision` suffixes the idempotency key, which is what
8488
+ // makes a second attempt possible once a key has been consumed;
8489
+ // the encoding is owned by sendAppEvent so no caller builds keys
8490
+ // itself. `timestamp` pins the PURCHASE time, which the automatic
8491
+ // path must never do — see the note above — and the recovery
8492
+ // migration must, because it is resending orders from a closed
8493
+ // window and bounds its own run to the merchant's current cycle.
8494
+ ...revision && { revision },
8495
+ ...timestamp && { timestamp },
8496
+ shopId,
8497
+ value
8498
+ });
8499
+ return {
8500
+ message: "Usage charge sent for order " + orderId + ".",
8501
+ request: { order: order || null, orderId: orderId || null, shopId: shopId || null, value },
8502
+ result: { transaction: String(transaction) },
8503
+ // TRACEABILITY. The App Events API returns no event id, so the
8504
+ // trace key into Shopify's event logs is the transaction id the
8505
+ // commerce.order hook minted and this sent as `reference`.
8506
+ // `amount` is the per-order usage value in cents, mirroring the
8507
+ // Stripe path's marker.
8508
+ ...order && { writes: [{
8509
+ collection: "order",
8510
+ data: {
8511
+ $set: {
8512
+ billed: {
8513
+ amount: value,
8514
+ date: /* @__PURE__ */ new Date(),
8515
+ rate: rate || 0,
8516
+ transaction: String(transaction)
8517
+ }
8518
+ }
8519
+ },
8520
+ operation: "update",
8521
+ query: { id: order }
8522
+ }] }
8523
+ };
8524
+ },
8525
+ // RESELECT, NOT CANCEL. The same mechanics — the current approval has to
8526
+ // be released before the pricing page will offer the plan again — but
8527
+ // the intent is a thirty-second round trip rather than a departure.
8528
+ //
8529
+ // `mark` IS A DECLARED CAPABILITY, and this is the only slot here that
8530
+ // needs one. The marker has to be persisted BEFORE the approval is
8531
+ // released: it is what tells sync's CANCELLED handler to hold the pause
8532
+ // — no connection error, no owner email — and start a timed recheck that
8533
+ // pauses honestly if the merchant abandons. A described write lands
8534
+ // after the hook returns, which is after the cancel, and a marker
8535
+ // written then can race the very webhook it exists to soften. Same
8536
+ // precedent as `resolveContact`: the one write a description cannot
8537
+ // carry.
8538
+ reselect: async ({ context }, { mark, read, shopify = client } = {}) => {
8539
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8540
+ if (!shop) throw refusal("shop is required", 400);
8541
+ await mark({ shop });
8542
+ return releaseApprovals({ context, read, shopify });
8543
+ },
8544
+ // IS THIS STORE'S ORDER BILLING ACTUALLY METERED? Not a merchant
8545
+ // action — the other two slots here are — but the same subject, and
8546
+ // the reason it is a declared hook rather than a helper is that the
8547
+ // answer was being derived in two places: `lifecycle.health` below,
8548
+ // and drawbridge-sync's app_subscriptions/update handler, whose copy
8549
+ // stated in its own comment that it matched this one and did not.
8550
+ //
8551
+ // THREE ANSWERS, and the caller must keep them apart:
8552
+ //
8553
+ // a string PROVEN. The charge id or usage line id, stamped on
8554
+ // the connection as the evidence.
8555
+ // null PROBED, and nothing is accruing.
8556
+ // undefined NO VERDICT — the probe could not run. `probed` says
8557
+ // which, because undefined does not survive JSON.
8558
+ verify: async ({ context }, { adminToken, read, shopify = client } = {}) => {
8559
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8560
+ if (!shop) throw refusal("shop is required", 400);
8561
+ const adminAccessToken = await adminToken();
8562
+ if (!adminAccessToken) {
8563
+ return { message: "No admin token for this store \u2014 no verdict.", request: { shop }, result: { metered: null, probed: false }, skipped: true };
8564
+ }
8565
+ const partnerRow = (read == null ? void 0 : read.get) ? await read.get({ collection: "provider", query: { slug: "shopify" } }) : null;
8566
+ const partner = (partnerRow == null ? void 0 : partnerRow.settings) ? decrypt(partnerRow.settings) : {};
8567
+ const { ledger, metered } = await meterVerdict({
8568
+ adminAccessToken,
8569
+ ledgerFloor: new Date(Date.now() - LEDGER_WINDOW_MS),
8570
+ partner,
8571
+ shop,
8572
+ shopId: (context == null ? void 0 : context.shopId) || null,
8573
+ shopify
8574
+ });
8575
+ return {
8576
+ message: typeof metered === "string" ? "Billing is metered." : "No meter evidence for this store.",
8577
+ request: { shop },
8578
+ // `probed` is the LEDGER, not the call: a store whose Partner
8579
+ // credentials are absent was not asked, and reporting that as
8580
+ // "probed, nothing accruing" would stamp an unmetered verdict on
8581
+ // a store nobody looked at.
8582
+ result: { metered: metered ?? null, probed: ledger || typeof metered === "string" }
8583
+ };
8584
+ }
8585
+ },
8586
+ // THE EMBEDDED APP'S SESSION STORE. The @shopify/shopify-app library
8587
+ // persists the offline session on token exchange and refresh; it lives
8588
+ // encrypted on the shared `shop` record, which is the same row every
8589
+ // organization's connection to this store points at.
8590
+ session: {
8591
+ // SOFT-CLEAR, NEVER A DELETE. The library calls this on session
8592
+ // invalidation and not only on uninstall, so hard-deleting the record
8593
+ // would orphan every org connection pointing at it — token resolution
8594
+ // silently nulls — and destroy the durable account link and the
8595
+ // storefront token with it. The next embedded load re-runs token
8596
+ // exchange. The full record delete belongs to the uninstall webhook.
8597
+ clear: async ({ context }) => {
8598
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8599
+ if (!shop) throw refusal("shop is required", 400);
8600
+ return {
8601
+ message: "Session cleared.",
8602
+ request: { shop },
8603
+ result: { ok: true },
8604
+ writes: [{
8605
+ collection: "shop",
8606
+ data: { $set: { settings: null } },
8607
+ operation: "update",
8608
+ query: { shop }
8609
+ }]
8610
+ };
8611
+ },
8612
+ read: async ({ context }, { read } = {}) => {
8613
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8614
+ if (!shop) throw refusal("shop is required", 400);
8615
+ const record = await read.get({ collection: "shop", query: { shop } });
8616
+ if (!(record == null ? void 0 : record.settings)) throw refusal("No session for this store", 404);
8617
+ return {
8618
+ message: "Session read.",
8619
+ request: { shop },
8620
+ result: { session: decrypt(record.settings) }
8621
+ };
8622
+ },
8623
+ save: async ({ context }) => {
8624
+ const session = context == null ? void 0 : context.session;
8625
+ const shop = sanitizeDomain(session == null ? void 0 : session.shop);
8626
+ if (!shop || !(session == null ? void 0 : session.accessToken)) throw refusal("session.shop and session.accessToken are required", 400);
8627
+ return {
8628
+ message: "Session saved.",
8629
+ request: { shop },
8630
+ result: { ok: true },
8631
+ writes: [{
8632
+ collection: "shop",
8633
+ data: {
8634
+ $set: { settings: encrypt(session), shop },
8635
+ $setOnInsert: { status: "pending" }
8636
+ },
8637
+ operation: "update",
8638
+ options: { upsert: true },
8639
+ query: { shop }
8640
+ }]
8641
+ };
8642
+ }
8643
+ },
8644
+ // THE LINK-TOKEN HANDOFF. The breakout callback runs top-level and can set
8645
+ // a first-party cookie; the embedded App Home cannot read that cookie from
8646
+ // inside the Shopify admin iframe. So the callback stashes the merchant's
8647
+ // user token here keyed by shop, and App Home reads it once and clears it.
8648
+ //
8649
+ // DURABLE RATHER THAN IN REDIS: a restart must not strand a merchant
8650
+ // mid-handoff. Short-lived and encrypted.
8651
+ token: {
8652
+ clear: async ({ context }) => {
8653
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8654
+ if (!shop) throw refusal("shop is required", 400);
8655
+ return {
8656
+ message: "Link token cleared.",
8657
+ request: { shop },
8658
+ result: { ok: true },
8659
+ writes: [{
8660
+ collection: "shop",
8661
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null } },
8662
+ operation: "update",
8663
+ query: { shop }
8664
+ }]
8665
+ };
8666
+ },
8667
+ read: async ({ context }, { read } = {}) => {
8668
+ var _a;
8669
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8670
+ if (!shop) throw refusal("shop is required", 400);
8671
+ const record = await read.get({ collection: "shop", query: { shop } });
8672
+ const expiresAt = (record == null ? void 0 : record.linkTokenExpiresAt) ? new Date(record.linkTokenExpiresAt) : null;
8673
+ if (!(record == null ? void 0 : record.linkToken) || !expiresAt || expiresAt <= /* @__PURE__ */ new Date()) {
8674
+ throw refusal("No link token for this store", 404);
8675
+ }
8676
+ return {
8677
+ message: "Link token read.",
8678
+ request: { shop },
8679
+ result: { token: ((_a = decrypt(record.linkToken)) == null ? void 0 : _a.token) ?? null }
8680
+ };
8681
+ },
8682
+ save: async ({ context }) => {
8683
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8684
+ const token = context == null ? void 0 : context.token;
8685
+ if (!shop || !token) throw refusal("shop and token are required", 400);
8686
+ return {
8687
+ message: "Link token saved.",
8688
+ request: { shop },
8689
+ result: { ok: true },
8690
+ writes: [{
8691
+ collection: "shop",
8692
+ data: {
8693
+ $set: {
8694
+ linkToken: encrypt({ token }),
8695
+ linkTokenExpiresAt: new Date(Date.now() + LINK_TOKEN_TTL_MS)
8696
+ }
8697
+ },
8698
+ operation: "update",
8699
+ query: { shop }
8700
+ }]
8701
+ };
8702
+ }
8703
+ }
8704
+ },
5985
8705
  // Drawbridge sends its own notification email and SMS — see the private
5986
8706
  // `drawbridge` manifest. A vendor answering these would be a second sender,
5987
8707
  // which is the arrangement the platform sender replaced.
@@ -6043,8 +8763,8 @@ var shopify_default2 = {
6043
8763
  // access token still works, reconciles the scopes the store granted
6044
8764
  // against the ones the app now needs, and queues a webhook
6045
8765
  // reconciliation.
6046
- health: async ({ connection: connection2, workflow }, { adminToken, logger: logger2, read, reconcileScopes, resolveSettings, rotateToken, shopify } = {}) => {
6047
- var _a, _b, _c, _d, _e, _f;
8766
+ health: async ({ connection: connection2, workflow }, { adminToken, logger: logger2, read, reconcileScopes, resolveSettings, rotateToken, shopify = client } = {}) => {
8767
+ var _a, _b, _c, _d;
6048
8768
  const request2 = {
6049
8769
  connectionId: workflow.connection,
6050
8770
  organizationId: workflow.organization,
@@ -6081,33 +8801,26 @@ var shopify_default2 = {
6081
8801
  shopCurrency = String(shopData.currency || "").toLowerCase() || null;
6082
8802
  sourceRepaired = true;
6083
8803
  }
6084
- const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
6085
- adminAccessToken,
6086
- domain: connection2.shop
6087
- });
6088
- const usageLine = (_a = subscriptions.find((subscription) => subscription.usageLineItemId)) == null ? void 0 : _a.usageLineItemId;
6089
- if (usageLine) metered = usageLine;
6090
8804
  const partnerRow = (read == null ? void 0 : read.get) ? await read.get({ collection: "provider", query: { slug: "shopify" } }) : null;
6091
8805
  const partner = (partnerRow == null ? void 0 : partnerRow.settings) ? decrypt(partnerRow.settings) : {};
6092
- if (partner.partnerToken && partner.partnerOrgId && partner.partnerAppId && (source == null ? void 0 : source.id) && ((_b = shopify.partner) == null ? void 0 : _b.getUsageChargeEvents)) {
6093
- const ledgerFloor = new Date(Date.now() - 30 * 24 * 60 * 60 * 1e3);
6094
- const accruals = await shopify.partner.getUsageChargeEvents({
6095
- appId: "gid://shopify/App/" + partner.partnerAppId,
6096
- first: 10,
6097
- occurredAtMin: ledgerFloor.toISOString(),
6098
- organizationId: partner.partnerOrgId,
6099
- partnerToken: partner.partnerToken,
6100
- shopId: "gid://shopify/Shop/" + source.id
6101
- });
6102
- const boundaries = accruals.filter((event) => event.occurredAt).sort((a, b) => new Date(a.occurredAt) - new Date(b.occurredAt));
6103
- const accrued = [...boundaries].reverse().find((event) => Number(event.usageQuantity) > 0);
6104
- if (accrued) metered = String(accrued.chargeId || accrued.id);
6105
- const stampedAt = (_c = boundaries.find(
8806
+ const ledgerFloor = new Date(Date.now() - LEDGER_WINDOW_MS);
8807
+ const verdict = await meterVerdict({
8808
+ adminAccessToken,
8809
+ ledgerFloor,
8810
+ partner,
8811
+ shop: connection2.shop,
8812
+ shopId: source == null ? void 0 : source.id,
8813
+ shopify
8814
+ });
8815
+ if (verdict.metered !== void 0) metered = verdict.metered;
8816
+ const { boundaries } = verdict;
8817
+ if (boundaries.length) {
8818
+ const stampedAt = (_a = boundaries.find(
6106
8819
  (event) => {
6107
8820
  var _a2;
6108
8821
  return String(event.chargeId || event.id) === String(((_a2 = connection2.source) == null ? void 0 : _a2.metered) || "");
6109
8822
  }
6110
- )) == null ? void 0 : _c.occurredAt;
8823
+ )) == null ? void 0 : _a.occurredAt;
6111
8824
  reconciliation = [];
6112
8825
  let windowStart = ledgerFloor;
6113
8826
  for (const boundary of boundaries) {
@@ -6157,7 +8870,7 @@ var shopify_default2 = {
6157
8870
  }
6158
8871
  });
6159
8872
  } else {
6160
- (_d = logger2 == null ? void 0 : logger2.error) == null ? void 0 : _d.call(logger2, new Error(
8873
+ (_b = logger2 == null ? void 0 : logger2.error) == null ? void 0 : _b.call(logger2, new Error(
6161
8874
  "shopify.usage.reconciliation.mismatch on shop " + connection2.shop + ": charge " + charge + " charged " + charged + " cents but its window holds " + billed + " cents across " + orders.length + " billed orders \u2014 each cent of difference is commission that never charged"
6162
8875
  ), {
6163
8876
  extra: {
@@ -6176,13 +8889,13 @@ var shopify_default2 = {
6176
8889
  }
6177
8890
  } catch (probeError) {
6178
8891
  billingProbeFailed = true;
6179
- (_e = logger2 == null ? void 0 : logger2.warn) == null ? void 0 : _e.call(logger2, "shopify.health.billing.probe.failed", {
8892
+ (_c = logger2 == null ? void 0 : logger2.warn) == null ? void 0 : _c.call(logger2, "shopify.health.billing.probe.failed", {
6180
8893
  connectionId: connection2.id,
6181
8894
  message: probeError == null ? void 0 : probeError.message,
6182
8895
  shop: connection2.shop
6183
8896
  });
6184
8897
  }
6185
- if (sourceRepaired || metered !== void 0 && metered !== (((_f = connection2.source) == null ? void 0 : _f.metered) ?? void 0)) {
8898
+ if (sourceRepaired || metered !== void 0 && metered !== (((_d = connection2.source) == null ? void 0 : _d.metered) ?? void 0)) {
6186
8899
  writes.push({
6187
8900
  collection: "connection",
6188
8901
  data: {
@@ -6317,13 +9030,13 @@ var shopify_default2 = {
6317
9030
  // They are the same two questions every other vendor answers through
6318
9031
  // resources.*, so they answer them the same way now.
6319
9032
  //
6320
- // `shopify` is INJECTED: this package cannot import @drawbridge/shopify,
9033
+ // `shopify` DEFAULTS to the client this file imports; nothing injects it,
6321
9034
  // which depends on it. What arrives is the SDK's pure HTTP namespaces
6322
9035
  // and nothing else — no controller, no collection access. Resolving the
6323
9036
  // credential is the caller's job because it is Drawbridge's job: the
6324
9037
  // admin token refreshes and writes itself back, which is service work,
6325
9038
  // not vendor work.
6326
- products: async ({ cursor, limit = 100, search, settings, sort }, { shopify } = {}) => {
9039
+ products: async ({ cursor, limit = 100, search, settings, sort }, { shopify = client } = {}) => {
6327
9040
  var _a, _b, _c, _d;
6328
9041
  const products = await shopify.storefront.getProducts({
6329
9042
  cursor,
@@ -6345,7 +9058,7 @@ var shopify_default2 = {
6345
9058
  }
6346
9059
  };
6347
9060
  },
6348
- promotions: async ({ cursor, limit = 100, search, settings }, { shopify } = {}) => {
9061
+ promotions: async ({ cursor, limit = 100, search, settings }, { shopify = client } = {}) => {
6349
9062
  var _a, _b;
6350
9063
  const discounts = await shopify.admin.getDiscounts({
6351
9064
  adminAccessToken: settings == null ? void 0 : settings.adminAccessToken,
@@ -6850,14 +9563,15 @@ var webhook_default = {
6850
9563
  "Drawbridge can POST event payloads to your endpoint as activity happens in your account, so your own systems can react to it.",
6851
9564
  "Generate a signing secret and Drawbridge signs every request with it. Your endpoint recomputes the signature to confirm each payload genuinely came from Drawbridge before acting on it."
6852
9565
  ],
6853
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
6854
- // The dashboard already carries generic reasons for every way an
6855
- // authorization can fail declined, expired state, a vendor we are not set
6856
- // up for and a sentence here is an ADDITION to those, for a vendor whose
6857
- // failures need saying differently. This one's do not.
9566
+ // THERE IS NO CONSENT SCREEN TO FAIL. Connecting mints a signing secret;
9567
+ // nothing is authorized against a third party, so neither `denied` nor
9568
+ // `invalid` has a state it could describe. The failures this connection
9569
+ // really has are at DELIVERY a merchant's endpoint refusing a POST and
9570
+ // those reach them through the connection's own errors rather than through
9571
+ // connect copy.
6858
9572
  //
6859
- // Answered rather than omitted, because `errors` existed on two of six
6860
- // manifests and there was no way to tell "nothing to add" from "nobody
9573
+ // `false` is the recorded decision, not silence: `errors` existed on two of
9574
+ // six manifests and there was no way to tell "nothing to add" from "nobody
6861
9575
  // wrote it".
6862
9576
  errors: false,
6863
9577
  excerpt: "Sign outgoing webhook payloads with an HMAC secret to verify authenticity.",