@drawbridge/drawbridge-utils 0.0.176 → 0.0.178

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 +3391 -271
  8. package/dist/connections/index.d.cts +13 -4
  9. package/dist/connections/index.d.ts +13 -4
  10. package/dist/connections/index.js +3388 -270
  11. package/dist/features.cjs +3080 -241
  12. package/dist/features.d.cts +13 -4
  13. package/dist/features.d.ts +13 -4
  14. package/dist/features.js +3120 -275
  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-qY18QITf.d.cts → index-C2rxasGZ.d.cts} +2670 -354
  20. package/dist/{index-B8JhYfvU.d.ts → index-DOYCXtd7.d.ts} +2670 -354
  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 +3079 -240
  28. package/dist/plans.d.cts +13 -4
  29. package/dist/plans.d.ts +13 -4
  30. package/dist/plans.js +3120 -275
  31. package/dist/pricing.cjs +3112 -273
  32. package/dist/pricing.d.cts +13 -4
  33. package/dist/pricing.d.ts +13 -4
  34. package/dist/pricing.js +3117 -272
  35. package/dist/providers.cjs +3082 -262
  36. package/dist/providers.d.cts +12 -3
  37. package/dist/providers.d.ts +12 -3
  38. package/dist/providers.js +3086 -260
  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/plans.cjs CHANGED
@@ -163,6 +163,10 @@ var HOOKS = Object.freeze({
163
163
  "code",
164
164
  // Create the buyer at the vendor, so an order can be attributed to them.
165
165
  "customer",
166
+ // HOW MANY OF THIS PRODUCT ARE LEFT, at the vendor. Read at the moment a
167
+ // campaign's product list is rendered rather than stored, because stock is
168
+ // the one product fact that is stale the instant it is written down.
169
+ "inventory",
166
170
  // An order arrived at the vendor: attribute it, record it, update totals.
167
171
  "order",
168
172
  // Pull product data across on a vendor update.
@@ -230,7 +234,19 @@ var HOOKS = Object.freeze({
230
234
  organizations: Object.freeze(["add", "list", "remove"]),
231
235
  // What the merchant pays the VENDOR. Pairs with auth.install.billing, which
232
236
  // declares the plan they are being charged on.
233
- plan: Object.freeze(["cancel", "reselect"]),
237
+ //
238
+ // `verify` is the odd one of the three: not something a merchant does, but
239
+ // the question "is this store's billing actually metered right now". It is
240
+ // here because it is the same subject — and because the answer was being
241
+ // derived in TWO places, the vendor's health check and drawbridge-sync's
242
+ // approval webhook, whose copy said in its own comment that it matched the
243
+ // other and did not.
244
+ // `charge` and `verify` are the two that are not merchant actions: one
245
+ // sends a usage charge to the vendor's meter, the other asks whether that
246
+ // meter is actually working. Both are here because both are the same
247
+ // subject — what the merchant pays the vendor — and both were being done
248
+ // from drawbridge-sync with a direct import of the vendor's client.
249
+ plan: Object.freeze(["cancel", "charge", "reselect", "verify"]),
234
250
  // The embedded app's own session, stored by us on the vendor's behalf.
235
251
  session: Object.freeze(["clear", "read", "save"]),
236
252
  // The one-time code that hands a merchant from the embedded app into
@@ -315,7 +331,7 @@ var ANSWER_KEYS = Object.freeze([
315
331
  "usage"
316
332
  ].sort());
317
333
  var WRITE_OPERATIONS = Object.freeze(["create", "delete", "update"]);
318
- var INSTALL_SIGNATURE = Object.freeze({ options: ["read", "request"], props: ["context"] });
334
+ var INSTALL_SIGNATURE = Object.freeze({ options: ["read"], props: ["context"] });
319
335
  var LIFECYCLE_SIGNATURE = Object.freeze({ options: ["dispatch"], props: ["context"] });
320
336
  var RESOURCE_SIGNATURE = Object.freeze({
321
337
  options: ["fetcher", "shopify"],
@@ -332,15 +348,30 @@ var HOOK_SLOT_PROPS = Object.freeze({
332
348
  // the second bag would be silently discarded, which is exactly the
333
349
  // stubbed-fetcher-reaches-production failure the split exists to prevent.
334
350
  "auth.token": false,
335
- // COMMERCE. `cart` is declared and unimplemented the Checkout Kit path in
336
- // api/route/subdomain.js writes nothing, which is why it never became a hook
337
- // so its signature mirrors `code`, its nearest sibling, and moving the
338
- // route here is a deliberate widening of this line rather than a silent one.
339
- "commerce.cart": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context", "step"] }),
351
+ // COMMERCE. `cart` is the odd one: it runs for a SHOPPER on a public page,
352
+ // not for an organization inside a workflow, so it takes no `connection` and
353
+ // no `step`. It reads the storefront with the store's own storefront token
354
+ // and mints a checkout token from DRAWBRIDGE'S app credentials, which is why
355
+ // `clientId`/`clientSecret` are here as props, the way auth.disconnect
356
+ // already carries them, because a credential is a fact of the run rather
357
+ // than a service.
358
+ "commerce.cart": Object.freeze({
359
+ options: ["fetcher", "shopify"],
360
+ props: ["clientId", "clientSecret", "context", "settings"]
361
+ }),
340
362
  "commerce.code": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context", "step"] }),
341
363
  "commerce.customer": Object.freeze({ options: ["adminToken", "read", "shopify"], props: ["connection", "context"] }),
364
+ "commerce.inventory": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context"] }),
342
365
  "commerce.order": Object.freeze({ options: ["conversionRate", "logger", "mintId", "read"], props: ["connection", "context"] }),
343
- "commerce.product": Object.freeze({ options: ["mintId", "read"], props: ["connection", "context", "workflow"] }),
366
+ // THREE OPERATIONS, one slot — record, sync, variants. `settings` and
367
+ // `adminToken` arrived with the pull half: the storefront read needs the
368
+ // store's storefront token and the product-feedback send needs its admin one,
369
+ // and both are resolved by the caller because minting either needs a
370
+ // controller.
371
+ "commerce.product": Object.freeze({
372
+ options: ["adminToken", "mintId", "read", "shopify"],
373
+ props: ["connection", "context", "settings", "workflow"]
374
+ }),
344
375
  // THE ADDRESS IS `contact` IN BOTH, and the shell already says why: it is the
345
376
  // person, not the lead document. `remove` called it `email` and `sync` called
346
377
  // it `doc` on one vendor and `lead` on three — three names for two facts.
@@ -353,19 +384,58 @@ var HOOK_SLOT_PROPS = Object.freeze({
353
384
  "inbound.process": Object.freeze({ options: ["dispatch"], props: ["context"] }),
354
385
  "inbound.receive": Object.freeze({ options: [], props: ["channel", "event", "headers", "payload"] }),
355
386
  "inbound.verify": Object.freeze({ options: [], props: ["body", "channel", "headers", "secret", "url"] }),
356
- // INSTALL — thirteen slots, none implemented yet. They are what the thirteen
357
- // routes in api/route/shopify-embedded.js become, and the signature is
358
- // deliberately narrow: `context` is the request's own body, `read` and
359
- // `request` are the only services an install surface has been shown to need.
360
- // A route that cannot be expressed inside this line is a finding to bring
361
- // back here, not a name to add at the call site.
387
+ // INSTALL — thirteen slots, and they are the thirteen routes that used to be
388
+ // api/route/shopify-embedded.js. `context` is the request's own body in all
389
+ // of them; the options are where they differ, and every difference below was
390
+ // forced by a line in those routes rather than chosen.
391
+ //
392
+ // SEVEN NEED NOTHING BUT `read`. The two session slots that write, the two
393
+ // token slots that write, the two clears, and both account slots answer from
394
+ // the shared install record alone.
395
+ //
396
+ // SIX TAKE MORE, and the widenings are worth naming because each is a fact
397
+ // Drawbridge owns that the manifest must not:
398
+ //
399
+ // conversionRate, planTitle what Drawbridge charges this organization.
400
+ // The org list renders both, and importing the
401
+ // plan catalogue here is the cycle
402
+ // features -> connections -> shopify -> plans
403
+ // -> features that was just broken.
404
+ // currencies which settlement currencies Drawbridge can
405
+ // bill. A store outside them fails the
406
+ // connection validator INSIDE the transaction,
407
+ // which surfaces as an opaque 500, so `add`
408
+ // checks first and says so.
409
+ // mintId the connection's id, known before the write
410
+ // that creates it, because the organization's
411
+ // own refs have to name it in the same
412
+ // transaction.
413
+ // shopify the vendor. Four slots call the store: two
414
+ // read the live plan, two release it.
415
+ // mark THE ONE WRITE A DESCRIPTION CANNOT CARRY, and
416
+ // `reselect` is the only slot with one. See its
417
+ // implementation for why the order is the point.
362
418
  "install.account.link": INSTALL_SIGNATURE,
363
419
  "install.account.unlink": INSTALL_SIGNATURE,
364
- "install.organizations.add": INSTALL_SIGNATURE,
365
- "install.organizations.list": INSTALL_SIGNATURE,
420
+ "install.organizations.add": Object.freeze({
421
+ options: ["currencies", "mintId", "read", "shopify"],
422
+ props: ["context"]
423
+ }),
424
+ "install.organizations.list": Object.freeze({
425
+ options: ["conversionRate", "planTitle", "read", "shopify"],
426
+ props: ["context"]
427
+ }),
366
428
  "install.organizations.remove": INSTALL_SIGNATURE,
367
- "install.plan.cancel": INSTALL_SIGNATURE,
368
- "install.plan.reselect": INSTALL_SIGNATURE,
429
+ "install.plan.cancel": Object.freeze({ options: ["read", "shopify"], props: ["context"] }),
430
+ // `manifest` because the handle this charge bills under is the vendor's own
431
+ // declaration (auth.install.billing.handle), and checking the job against the
432
+ // declaration is what the enqueuer-checks-itself version could not do.
433
+ "install.plan.charge": Object.freeze({
434
+ options: ["shopify"],
435
+ props: ["clientId", "clientSecret", "context", "manifest"]
436
+ }),
437
+ "install.plan.reselect": Object.freeze({ options: ["mark", "read", "shopify"], props: ["context"] }),
438
+ "install.plan.verify": Object.freeze({ options: ["adminToken", "read", "shopify"], props: ["context"] }),
369
439
  "install.session.clear": INSTALL_SIGNATURE,
370
440
  "install.session.read": INSTALL_SIGNATURE,
371
441
  "install.session.save": INSTALL_SIGNATURE,
@@ -416,6 +486,16 @@ var TRIGGERS = Object.freeze({
416
486
  "range.ended": Object.freeze({ event: "range.ended", type: "range" }),
417
487
  "range.started": Object.freeze({ event: "range.started", type: "range" }),
418
488
  "schedule.day": Object.freeze({ event: "day", type: "schedule" }),
489
+ // THE THREE SHOPIFY TRIGGERS, which were never in this vocabulary because the
490
+ // four workflows they fire were hand-written in drawbridge-sync's register job
491
+ // rather than provisioned from the manifest. `webhook` is a fourth trigger
492
+ // TYPE, and it is the honest name: these fire when the vendor calls us, which
493
+ // is neither an event Drawbridge raised nor a schedule it keeps.
494
+ "shopify.order.create": Object.freeze({ event: "shopify.order.create", type: "webhook" }),
495
+ "shopify.product.update": Object.freeze({ event: "shopify.product.update", type: "webhook" }),
496
+ // The token audit, dispatched programmatically by the register job when a
497
+ // store's grant is exchanged or rotated.
498
+ "shopify.token": Object.freeze({ event: "shopify.token", type: "event" }),
419
499
  "schedule.month": Object.freeze({ event: "month", type: "schedule" }),
420
500
  "schedule.week": Object.freeze({ event: "week", type: "schedule" }),
421
501
  "segment.contact.add": Object.freeze({ event: "segment.contact.add", type: "event" }),
@@ -468,7 +548,7 @@ var OUTCOMES = Object.freeze({
468
548
  unimplemented: "unimplemented",
469
549
  unsupported: "unsupported"
470
550
  });
471
- var STATUSES = Object.freeze(["active", "disconnected", "error", "pending"]);
551
+ var STATUSES = Object.freeze(["active", "error", "pending"]);
472
552
  var PLATFORM_CREDENTIALS = Object.freeze([
473
553
  // Seals a merchant's stored connection settings. The webhook connection is
474
554
  // gated on it because its whole credential is a secret WE mint and store, so
@@ -524,6 +604,52 @@ var ERROR_SOURCES = Object.freeze({
524
604
  "shopify.register.webhooks": true
525
605
  });
526
606
 
607
+ // lib/encrypt.js
608
+ var import_crypto2 = __toESM(require("crypto"), 1);
609
+
610
+ // lib/token.js
611
+ var import_crypto = __toESM(require("crypto"), 1);
612
+ var generate = (bytes = 32, encoding = "base64url") => {
613
+ const buf = import_crypto.default.randomBytes(bytes);
614
+ return encoding ? buf.toString(encoding) : buf;
615
+ };
616
+ var hash = (value, key) => {
617
+ if (!value) return null;
618
+ if (key) {
619
+ return import_crypto.default.createHmac("sha256", key).update(String(value)).digest("base64url");
620
+ }
621
+ return import_crypto.default.createHash("sha256").update(String(value)).digest("base64url");
622
+ };
623
+
624
+ // lib/encrypt.js
625
+ var ALGORITHM = "aes-256-gcm";
626
+ var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
627
+ var encrypt = (value) => {
628
+ const iv = generate(12, null);
629
+ const cipher = import_crypto2.default.createCipheriv(ALGORITHM, getKey(), iv);
630
+ const data2 = Buffer.concat([
631
+ cipher.update(JSON.stringify(value), "utf8"),
632
+ cipher.final()
633
+ ]);
634
+ const tag = cipher.getAuthTag();
635
+ return [iv, tag, data2].map((b) => b.toString("hex")).join(":");
636
+ };
637
+ var decrypt = (value) => {
638
+ if (typeof value !== "string") return value;
639
+ const [ivHex, tagHex, dataHex] = value.split(":");
640
+ const decipher = import_crypto2.default.createDecipheriv(
641
+ ALGORITHM,
642
+ getKey(),
643
+ Buffer.from(ivHex, "hex")
644
+ );
645
+ decipher.setAuthTag(Buffer.from(tagHex, "hex"));
646
+ const result = Buffer.concat([
647
+ decipher.update(Buffer.from(dataHex, "hex")),
648
+ decipher.final()
649
+ ]);
650
+ return JSON.parse(result.toString("utf8"));
651
+ };
652
+
527
653
  // lib/connections/oauth.js
528
654
  var import_node_crypto = require("crypto");
529
655
  var credentials = ({ basic, clientId, clientSecret }) => basic ? {
@@ -550,10 +676,10 @@ var authToken = async ({
550
676
  const renewing = !code2;
551
677
  if (renewing && !refreshToken) throw new Error("Nothing has been consented to yet, so there is no refresh token to spend");
552
678
  if (!renewing && descriptor.pkce && !verifier) throw new Error("This connection requires PKCE, so the code verifier is not optional");
553
- const client = credentials({ basic, clientId, clientSecret });
679
+ const client2 = credentials({ basic, clientId, clientSecret });
554
680
  const response = await fetcher(descriptor.endpoints.token, {
555
681
  body: new URLSearchParams({
556
- ...client.body,
682
+ ...client2.body,
557
683
  ...renewing ? { grant_type: "refresh_token", refresh_token: refreshToken } : {
558
684
  code: decodeURIComponent(String(code2 || "").trim()),
559
685
  grant_type: "authorization_code",
@@ -561,7 +687,7 @@ var authToken = async ({
561
687
  ...descriptor.pkce && { code_verifier: verifier }
562
688
  }
563
689
  }),
564
- headers: { "content-type": "application/x-www-form-urlencoded", ...client.headers },
690
+ headers: { "content-type": "application/x-www-form-urlencoded", ...client2.headers },
565
691
  method: "POST",
566
692
  signal: AbortSignal.timeout(15e3)
567
693
  });
@@ -956,9 +1082,18 @@ var scaffold_default = {
956
1082
  commerce: {
957
1083
  // NEW in phase 1 — the Checkout Kit cart path, which writes nothing and is
958
1084
  // the last api surface Shopify owns outside a hook.
959
- cart: async ({ connection: connection2, context }, { read } = {}) => ANSWER,
1085
+ // NO `connection` AND NO `step`: this one runs for a SHOPPER on a public
1086
+ // page, not for an organization inside a workflow. It reads the storefront
1087
+ // with the store's storefront token and mints a checkout token from
1088
+ // DRAWBRIDGE'S app credentials, which is why the credential pair rides in
1089
+ // as props — the way auth.disconnect already carries it.
1090
+ cart: async ({ clientId, clientSecret, context, settings }, { fetcher, shopify } = {}) => ANSWER,
960
1091
  code: async ({ connection: connection2, context, step }, { adminToken, shopify } = {}) => ANSWER,
961
1092
  customer: async ({ connection: connection2, context }, { adminToken, read, shopify } = {}) => ANSWER,
1093
+ // STOCK, READ AT RENDER TIME rather than stored. It is the one product
1094
+ // fact that is stale the instant it is written down, so the campaign
1095
+ // product list asks the vendor and caches the answer for a minute.
1096
+ inventory: async ({ connection: connection2, context }, { adminToken, shopify } = {}) => ANSWER,
962
1097
  order: async ({ connection: connection2, context }, { logger, mintId, read } = {}) => ANSWER,
963
1098
  // THIS IS WHERE `product.insert` LANDS.
964
1099
  //
@@ -980,7 +1115,7 @@ var scaffold_default = {
980
1115
  // nothing and shows up only as `workflow.dispatch.candidates matched : 0` in
981
1116
  // a log. Phase 1 closes it and build() checks every trigger against it.
982
1117
  product: {
983
- hook: async ({ connection: connection2, context, workflow }, { mintId, read } = {}) => ANSWER,
1118
+ hook: async ({ connection: connection2, context, settings, workflow }, { adminToken, mintId, read, shopify } = {}) => ANSWER,
984
1119
  step: () => ({
985
1120
  description: "Syncs product data from the vendor when a product changes.",
986
1121
  key: "Vendor Product Sync",
@@ -1128,8 +1263,19 @@ var scaffold_default = {
1128
1263
  // Vendor billing, the only group that is not generic. Pairs with
1129
1264
  // auth.install.billing, which declares what the merchant is being charged.
1130
1265
  plan: {
1131
- cancel: async ({ context }, { dispatch, read } = {}) => ANSWER,
1132
- reselect: async ({ context }, { dispatch, read } = {}) => ANSWER
1266
+ cancel: async ({ context }, { read, shopify } = {}) => ANSWER,
1267
+ // NOT A MERCHANT ACTION EITHER one attributed order's usage charge,
1268
+ // sent to the vendor's meter. The credential pair rides in as props
1269
+ // because the charge authenticates as the APP, not as the store.
1270
+ charge: async ({ clientId, clientSecret, context, manifest }, { shopify } = {}) => ANSWER,
1271
+ // `mark` is the one write a description cannot carry: the marker must
1272
+ // be persisted BEFORE the approval is released, and a described write
1273
+ // lands after the hook returns.
1274
+ reselect: async ({ context }, { mark, read, shopify } = {}) => ANSWER,
1275
+ // NOT A MERCHANT ACTION — the question "is this store's billing
1276
+ // actually metered right now", asked by the daily health check and by
1277
+ // the vendor's own approval webhook, which used to hand-copy it.
1278
+ verify: async ({ context }, { adminToken, read, shopify } = {}) => ANSWER
1133
1279
  },
1134
1280
  // The embedded app's own session, stored by us on the vendor's behalf.
1135
1281
  session: {
@@ -1615,16 +1761,19 @@ var attentive_default2 = {
1615
1761
  "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.",
1616
1762
  "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."
1617
1763
  ],
1618
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
1619
- // The dashboard already carries generic reasons for every way an
1620
- // authorization can fail — declined, expired state, a vendor we are not set
1621
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
1622
- // failures need saying differently. This one's do not.
1764
+ // WHAT THE MERCHANT READS WHEN A CONNECT FAILS. Two states, because the
1765
+ // consent screen has two ways to end: they said no, or something between
1766
+ // here and the vendor went wrong.
1623
1767
  //
1624
- // Answered rather than omitted, because `errors` existed on two of six
1625
- // manifests and there was no way to tell "nothing to add" from "nobody
1626
- // wrote it".
1627
- errors: false,
1768
+ // THE VENDOR IS NAMED IN BOTH. The dashboard's generic copy says "the
1769
+ // authorization"; a merchant connecting two accounts in one sitting needs
1770
+ // to know which one this was.
1771
+ errors: {
1772
+ connect: {
1773
+ denied: "The Attentive authorization was declined, so nothing was connected.",
1774
+ invalid: "We couldn't complete the Attentive connection. Try connecting again."
1775
+ }
1776
+ },
1628
1777
  excerpt: "Sync your Drawbridge contacts into an Attentive segment.",
1629
1778
  // NAMES THE SEGMENT STEP, because `status` below gates on it: a grant with
1630
1779
  // no segment chosen sits at Pending, and a guide that stops at the consent
@@ -2152,6 +2301,15 @@ var readEventHeader = ({ descriptor, headers }) => ({ result: { event: headers[d
2152
2301
  var DEFAULT_TIMEOUT_MS = 15e3;
2153
2302
  var request = async ({
2154
2303
  body,
2304
+ // THE TRANSPORT, injectable and defaulted to the real one.
2305
+ //
2306
+ // Every other vendor client in this package takes a `fetcher` — it is how
2307
+ // klaviyo, mailchimp and attentive are tested without a network, and it is a
2308
+ // declared HOOK_OPTION. The Shopify client had no seam at all, so the only way
2309
+ // to test a hook that used it was to inject the whole SDK namespace; that
2310
+ // injection existed to work around an import cycle, and when the cycle went
2311
+ // the tests lost their only hold. This is the seam they should have had.
2312
+ fetcher = fetch,
2155
2313
  headers = {},
2156
2314
  method = "GET",
2157
2315
  query,
@@ -2165,7 +2323,7 @@ var request = async ({
2165
2323
  }
2166
2324
  ;
2167
2325
  const isForm = type === "form";
2168
- const response = await fetch(fullUrl.toString(), {
2326
+ const response = await fetcher(fullUrl.toString(), {
2169
2327
  method,
2170
2328
  headers: {
2171
2329
  "Content-Type": isForm ? "application/x-www-form-urlencoded" : "application/json",
@@ -2622,15 +2780,12 @@ var drawbridge_default2 = {
2622
2780
  description: [
2623
2781
  "Drawbridge sends your notification emails and your entrants' emails, and recalculates segment membership on a schedule. It is always on and needs nothing connected."
2624
2782
  ],
2625
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
2626
- // The dashboard already carries generic reasons for every way an
2627
- // authorization can fail declined, expired state, a vendor we are not set
2628
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
2629
- // failures need saying differently. This one's do not.
2783
+ // NOTHING IS EVER CONNECTED, so no connect can fail. This is the platform's
2784
+ // own manifest always on, private, never in the catalogue — and it exists
2785
+ // to give Drawbridge's own steps a hook to point at. `denied` and `invalid`
2786
+ // describe a consent screen this connection does not have.
2630
2787
  //
2631
- // Answered rather than omitted, because `errors` existed on two of six
2632
- // manifests and there was no way to tell "nothing to add" from "nobody
2633
- // wrote it".
2788
+ // `false` is the recorded decision, not silence.
2634
2789
  errors: false,
2635
2790
  excerpt: "The steps Drawbridge runs itself.",
2636
2791
  guide: [
@@ -3390,10 +3545,10 @@ var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
3390
3545
 
3391
3546
  // lib/connections/scopes.js
3392
3547
  var list = (value) => (Array.isArray(value) ? value.flatMap((entry) => String(entry).split(/\s+/)) : String(value ?? "").split(/\s+/)).map((entry) => entry.trim()).filter(Boolean);
3393
- var missingScopes = ({ granted, required }) => {
3548
+ var missingScopes = ({ granted, required: required2 }) => {
3394
3549
  if (granted === null || granted === void 0 || granted === "") return null;
3395
3550
  const held = new Set(list(granted));
3396
- return list(required).filter((scope) => !held.has(scope));
3551
+ return list(required2).filter((scope) => !held.has(scope));
3397
3552
  };
3398
3553
 
3399
3554
  // lib/connections/manifests/klaviyo.js
@@ -4292,16 +4447,19 @@ var mailchimp_default2 = {
4292
4447
  "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.",
4293
4448
  "Someone who unsubscribed inside Mailchimp keeps that choice: a resync only sets the status of a subscriber Mailchimp has never seen before."
4294
4449
  ],
4295
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
4296
- // The dashboard already carries generic reasons for every way an
4297
- // authorization can fail — declined, expired state, a vendor we are not set
4298
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
4299
- // failures need saying differently. This one's do not.
4450
+ // WHAT THE MERCHANT READS WHEN A CONNECT FAILS. Two states, because the
4451
+ // consent screen has two ways to end: they said no, or something between
4452
+ // here and the vendor went wrong.
4300
4453
  //
4301
- // Answered rather than omitted, because `errors` existed on two of six
4302
- // manifests and there was no way to tell "nothing to add" from "nobody
4303
- // wrote it".
4304
- errors: false,
4454
+ // THE VENDOR IS NAMED IN BOTH. The dashboard's generic copy says "the
4455
+ // authorization"; a merchant connecting two accounts in one sitting needs
4456
+ // to know which one this was.
4457
+ errors: {
4458
+ connect: {
4459
+ denied: "The Mailchimp authorization was declined, so nothing was connected.",
4460
+ invalid: "We couldn't complete the Mailchimp connection. Try connecting again."
4461
+ }
4462
+ },
4305
4463
  excerpt: "Sync your Drawbridge contacts into a Mailchimp audience.",
4306
4464
  // NAMES THE AUDIENCE STEP, because `status` below gates on it: a grant with
4307
4465
  // no audience chosen sits at Pending, and a guide that stops at the consent
@@ -4400,7 +4558,7 @@ var mailchimp_default2 = {
4400
4558
  if (!audience) return { message: "No Mailchimp audience is chosen for this connection.", request: request2, skipped: true };
4401
4559
  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);
4402
4560
  if (!email) return { message: "That lead has no email address to sync.", request: request2, skipped: true };
4403
- const hash = subscriberHash(email);
4561
+ const hash2 = subscriberHash(email);
4404
4562
  const [firstName, ...restOfName] = String((lead == null ? void 0 : lead.name) || "").trim().split(/\s+/).filter(Boolean);
4405
4563
  const lastName = restOfName.join(" ");
4406
4564
  const phone = ((_e = lead == null ? void 0 : lead.phone) == null ? void 0 : _e.number) || null;
@@ -4409,7 +4567,7 @@ var mailchimp_default2 = {
4409
4567
  ...lastName && { LNAME: lastName },
4410
4568
  ...phone && { PHONE: phone }
4411
4569
  };
4412
- const member = await api3("/lists/" + audience + "/members/" + hash, {
4570
+ const member = await api3("/lists/" + audience + "/members/" + hash2, {
4413
4571
  dc: settings == null ? void 0 : settings.dc,
4414
4572
  fetcher,
4415
4573
  method: "PUT",
@@ -4450,7 +4608,7 @@ var mailchimp_default2 = {
4450
4608
  status: joined.has(entry.id) ? "active" : "inactive"
4451
4609
  }));
4452
4610
  if (tags.length > 0) {
4453
- await api3("/lists/" + audience + "/members/" + hash + "/tags", {
4611
+ await api3("/lists/" + audience + "/members/" + hash2 + "/tags", {
4454
4612
  dc: settings == null ? void 0 : settings.dc,
4455
4613
  fetcher,
4456
4614
  method: "POST",
@@ -4461,12 +4619,12 @@ var mailchimp_default2 = {
4461
4619
  }
4462
4620
  return {
4463
4621
  // Merged into `context` for later steps in this run.
4464
- context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash },
4622
+ context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash2 },
4465
4623
  message: suppressed ? "Synced to Mailchimp as unsubscribed \u2014 this contact has opted out." : "Synced to the Mailchimp audience.",
4466
4624
  request: request2,
4467
4625
  // Recorded on the run for support to read back, not a write
4468
4626
  // instruction — the hook has already written what it needed to.
4469
- response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash }
4627
+ response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash2 }
4470
4628
  };
4471
4629
  }
4472
4630
  },
@@ -4836,139 +4994,2030 @@ var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
4836
4994
  <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"/>
4837
4995
  </svg>`;
4838
4996
 
4839
- // lib/email.js
4840
- var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
4841
- var toCanonicalEmail = (value) => {
4842
- if (!value || typeof value !== "string") return null;
4843
- const email = value.trim().toLowerCase();
4844
- const at = email.lastIndexOf("@");
4845
- if (at < 1 || at === email.length - 1) return null;
4846
- let local = email.slice(0, at);
4847
- const domain = email.slice(at + 1);
4848
- const plus = local.indexOf("+");
4849
- if (plus > 0) local = local.slice(0, plus);
4850
- if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
4851
- if (!local) return null;
4852
- return local + "@" + domain;
4853
- };
4997
+ // lib/shopify/admin.js
4998
+ var admin_exports = {};
4999
+ __export(admin_exports, {
5000
+ adminFetch: () => adminFetch,
5001
+ createDiscountCode: () => createDiscountCode,
5002
+ createUsageRecord: () => createUsageRecord,
5003
+ createUsageSubscription: () => createUsageSubscription,
5004
+ getActiveAppSubscriptions: () => getActiveAppSubscriptions,
5005
+ getDiscounts: () => getDiscounts,
5006
+ getOrCreateCustomer: () => getOrCreateCustomer,
5007
+ getProductInventory: () => getProductInventory,
5008
+ sendProductResourceFeedback: () => sendProductResourceFeedback
5009
+ });
4854
5010
 
4855
- // lib/encrypt.js
4856
- var import_crypto = __toESM(require("crypto"), 1);
4857
- var ALGORITHM = "aes-256-gcm";
4858
- var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
4859
- var decrypt = (value) => {
4860
- if (typeof value !== "string") return value;
4861
- const [ivHex, tagHex, dataHex] = value.split(":");
4862
- const decipher = import_crypto.default.createDecipheriv(
4863
- ALGORITHM,
4864
- getKey(),
4865
- Buffer.from(ivHex, "hex")
4866
- );
4867
- decipher.setAuthTag(Buffer.from(tagHex, "hex"));
4868
- const result = Buffer.concat([
4869
- decipher.update(Buffer.from(dataHex, "hex")),
4870
- decipher.final()
4871
- ]);
4872
- return JSON.parse(result.toString("utf8"));
4873
- };
5011
+ // lib/shopify/constants.js
5012
+ var SHOPIFY_STOREFRONT_API_VERSION = "2025-01";
5013
+ var SHOPIFY_ADMIN_API_VERSION = "2026-04";
5014
+ var SHOPIFY_APP_API_VERSION = "unstable";
5015
+ var SHOPIFY_REQUIRED_SCOPES = [
5016
+ "read_customers",
5017
+ "write_customers",
5018
+ "read_discounts",
5019
+ "write_discounts",
5020
+ "read_orders",
5021
+ "read_products",
5022
+ "read_publications",
5023
+ "write_resource_feedbacks",
5024
+ "unauthenticated_read_checkouts",
5025
+ "unauthenticated_read_product_inventory",
5026
+ "unauthenticated_read_product_listings",
5027
+ "unauthenticated_write_checkouts"
5028
+ ];
5029
+ var REFRESH_TOKEN_LIFETIME_MS = 90 * 24 * 60 * 60 * 1e3;
5030
+ var ACCESS_TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1e3;
5031
+ var PARTNER_API_VERSION = process.env.SHOPIFY_PARTNER_API_VERSION || "2026-07";
4874
5032
 
4875
- // lib/slugify.js
4876
- var import_slugify = __toESM(require("slugify"), 1);
4877
- var slugify = (value, nochars = false) => {
4878
- const remove = nochars ? /[-?*+~.()'"!:@#^_{}\[\];,/\\]/g : /[?*+~.()'"!:@#^_{}\[\];,/\\]/g;
4879
- const replacement = nochars ? "" : "-";
4880
- return (0, import_slugify.default)(
4881
- value,
4882
- {
4883
- remove,
4884
- replacement,
4885
- lower: true,
4886
- trim: true
5033
+ // lib/shopify/admin.js
5034
+ var adminUrl = (domain) => `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}`;
5035
+ var adminFetch = async ({ adminAccessToken, domain, fetcher, query, variables }) => {
5036
+ var _a;
5037
+ const { data: data2, errors } = await request({
5038
+ fetcher,
5039
+ method: "POST",
5040
+ url: adminUrl(domain) + "/graphql.json",
5041
+ headers: {
5042
+ "X-Shopify-Access-Token": adminAccessToken
5043
+ },
5044
+ body: {
5045
+ query,
5046
+ ...variables && { variables }
4887
5047
  }
4888
- );
5048
+ });
5049
+ if (errors) {
5050
+ throw new Error("Shopify GraphQL error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
5051
+ }
5052
+ ;
5053
+ return data2;
4889
5054
  };
4890
-
4891
- // lib/connections/manifests/shopify.js
4892
- var toLine = ({
4893
- price,
4894
- product_id: productId,
4895
- quantity,
4896
- title,
4897
- variant_id: variantId,
4898
- variant_title: variantTitle
4899
- }) => ({
4900
- price: parseFloat(price) || 0,
4901
- productId: productId ? "gid://shopify/Product/" + productId : null,
4902
- quantity: quantity || 1,
4903
- title: title || null,
4904
- variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
4905
- variantTitle: variantTitle || null
4906
- });
4907
- var attributeLineItems = (lineItems = []) => lineItems.reduce(
4908
- (acc, item) => {
4909
- const attrs = (item.properties || []).reduce(
4910
- (map, { name, value }) => {
4911
- map[name] = value;
4912
- return map;
4913
- },
4914
- {}
4915
- );
4916
- if (!attrs["_drwbrdg_ca"]) return acc;
4917
- if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
4918
- const line = toLine(item);
4919
- acc.attributedGross += line.price * line.quantity;
4920
- acc.attributedLines.push(line);
4921
- return acc;
4922
- },
4923
- { attrMap: {}, attributedGross: 0, attributedLines: [] }
4924
- );
4925
- var generateDiscountCode = (0, import_nanoid.customAlphabet)("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
4926
- var blockedReason = (discount) => {
5055
+ var DISCOUNT_FIELDS = `
5056
+ title
5057
+ status
5058
+ startsAt
5059
+ endsAt
5060
+ usageLimit
5061
+ asyncUsageCount
5062
+ appliesOncePerCustomer
5063
+ context { __typename }
5064
+ `;
5065
+ var discountsQuery = (search, cursor, limit) => `{
5066
+ codeDiscountNodes(first: ${limit}${search ? `, query: "title:*${search}*"` : ""}${cursor ? `, after: "${cursor}"` : ""}) {
5067
+ edges {
5068
+ node {
5069
+ id
5070
+ codeDiscount {
5071
+ ... on DiscountCodeBasic { ${DISCOUNT_FIELDS} }
5072
+ ... on DiscountCodeBxgy { ${DISCOUNT_FIELDS} }
5073
+ ... on DiscountCodeFreeShipping { ${DISCOUNT_FIELDS} }
5074
+ ... on DiscountCodeApp { ${DISCOUNT_FIELDS} }
5075
+ }
5076
+ }
5077
+ }
5078
+ pageInfo {
5079
+ endCursor
5080
+ hasNextPage
5081
+ hasPreviousPage
5082
+ startCursor
5083
+ }
5084
+ }
5085
+ }`;
5086
+ var getDiscounts = async ({ fetcher, adminAccessToken, domain, search, cursor, limit }) => {
5087
+ const data2 = await adminFetch({
5088
+ fetcher,
5089
+ adminAccessToken,
5090
+ domain,
5091
+ query: discountsQuery(search, cursor, limit)
5092
+ });
5093
+ return data2 == null ? void 0 : data2.codeDiscountNodes;
5094
+ };
5095
+ var discountGid = (id) => String(id).startsWith("gid://") ? String(id) : "gid://shopify/DiscountCodeNode/" + id;
5096
+ var createDiscountCode = async ({ fetcher, adminAccessToken, domain, discountId, code: code2 }) => {
5097
+ var _a, _b, _c, _d, _e, _f, _g, _h;
5098
+ const added = await adminFetch({
5099
+ fetcher,
5100
+ adminAccessToken,
5101
+ domain,
5102
+ query: `
5103
+ mutation DiscountRedeemCodeBulkAdd($discountId: ID!, $codes: [DiscountRedeemCodeInput!]!) {
5104
+ discountRedeemCodeBulkAdd(discountId: $discountId, codes: $codes) {
5105
+ bulkCreation {
5106
+ id
5107
+ }
5108
+ userErrors {
5109
+ field
5110
+ message
5111
+ }
5112
+ }
5113
+ }
5114
+ `,
5115
+ variables: {
5116
+ codes: [{ code: code2 }],
5117
+ discountId: discountGid(discountId)
5118
+ }
5119
+ });
5120
+ const addErrors = (_a = added == null ? void 0 : added.discountRedeemCodeBulkAdd) == null ? void 0 : _a.userErrors;
5121
+ if (addErrors == null ? void 0 : addErrors.length) {
5122
+ throw new Error("Shopify discount code create failed: " + addErrors[0].message);
5123
+ }
5124
+ ;
5125
+ const bulkCreationId = (_c = (_b = added == null ? void 0 : added.discountRedeemCodeBulkAdd) == null ? void 0 : _b.bulkCreation) == null ? void 0 : _c.id;
5126
+ if (!bulkCreationId) {
5127
+ throw new Error("Shopify discount code create failed: no bulk creation id returned");
5128
+ }
5129
+ ;
5130
+ for (let attempt = 0; attempt < 15; attempt++) {
5131
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
5132
+ const polled = await adminFetch({
5133
+ fetcher,
5134
+ adminAccessToken,
5135
+ domain,
5136
+ query: `
5137
+ query DiscountRedeemCodeBulkCreationPoll($id: ID!) {
5138
+ discountRedeemCodeBulkCreation(id: $id) {
5139
+ done
5140
+ codes(first: 1) {
5141
+ nodes {
5142
+ code
5143
+ discountRedeemCode {
5144
+ id
5145
+ }
5146
+ errors {
5147
+ message
5148
+ }
5149
+ }
5150
+ }
5151
+ }
5152
+ }
5153
+ `,
5154
+ variables: {
5155
+ id: bulkCreationId
5156
+ }
5157
+ });
5158
+ const creation = polled == null ? void 0 : polled.discountRedeemCodeBulkCreation;
5159
+ if (!(creation == null ? void 0 : creation.done)) continue;
5160
+ const node = (_e = (_d = creation.codes) == null ? void 0 : _d.nodes) == null ? void 0 : _e[0];
5161
+ if (!((_f = node == null ? void 0 : node.discountRedeemCode) == null ? void 0 : _f.id)) {
5162
+ 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"));
5163
+ }
5164
+ ;
5165
+ return {
5166
+ code: node.code,
5167
+ // Numeric tail keeps the stored shopifyDiscountId in the shape the
5168
+ // legacy REST endpoint returned — it feeds a merchant-visible
5169
+ // workflow template variable, so no gid:// leakage.
5170
+ id: node.discountRedeemCode.id.split("/").pop()
5171
+ };
5172
+ }
5173
+ ;
5174
+ throw new Error("Shopify discount code create timed out waiting for bulk creation " + bulkCreationId);
5175
+ };
5176
+ var getOrCreateCustomer = async ({ fetcher, adminAccessToken, domain, email, firstName, lastName, source }) => {
5177
+ var _a, _b, _c, _d, _e, _f, _g, _h;
5178
+ const lookupQuery = `
5179
+ query customerByEmail( $query : String! ) {
5180
+ customers( first : 1, query : $query ) {
5181
+ edges {
5182
+ node {
5183
+ id
5184
+ }
5185
+ }
5186
+ }
5187
+ }
5188
+ `;
5189
+ const data2 = await adminFetch({
5190
+ fetcher,
5191
+ adminAccessToken,
5192
+ domain,
5193
+ query: lookupQuery,
5194
+ variables: { query: "email:" + email }
5195
+ });
5196
+ 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;
5197
+ if (existing) return existing;
5198
+ const input = { email };
5199
+ if (firstName) input.firstName = firstName;
5200
+ if (lastName) input.lastName = lastName;
5201
+ if (source) {
5202
+ input.metafields = [{
5203
+ namespace: "drwbrdg",
5204
+ key: "source",
5205
+ type: "single_line_text_field",
5206
+ value: source
5207
+ }];
5208
+ }
5209
+ ;
5210
+ const result = await adminFetch({
5211
+ fetcher,
5212
+ adminAccessToken,
5213
+ domain,
5214
+ query: `
5215
+ mutation customerCreate( $input : CustomerInput! ) {
5216
+ customerCreate( input : $input ) {
5217
+ customer {
5218
+ id
5219
+ }
5220
+ userErrors {
5221
+ field
5222
+ message
5223
+ }
5224
+ }
5225
+ }
5226
+ `,
5227
+ variables: { input }
5228
+ });
5229
+ const userErrors = (_d = result == null ? void 0 : result.customerCreate) == null ? void 0 : _d.userErrors;
5230
+ if (userErrors == null ? void 0 : userErrors.length) {
5231
+ const emailTaken = userErrors.some((e) => {
5232
+ var _a2;
5233
+ return (_a2 = e.message) == null ? void 0 : _a2.includes("Email has already been taken");
5234
+ });
5235
+ if (emailTaken) {
5236
+ const retry = await adminFetch({
5237
+ fetcher,
5238
+ adminAccessToken,
5239
+ domain,
5240
+ query: lookupQuery,
5241
+ variables: { query: "email:" + email }
5242
+ });
5243
+ 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;
5244
+ if (found) return found;
5245
+ }
5246
+ ;
5247
+ throw new Error("Shopify customer create failed: " + userErrors[0].message);
5248
+ }
5249
+ ;
5250
+ return (_h = result == null ? void 0 : result.customerCreate) == null ? void 0 : _h.customer;
5251
+ };
5252
+ var getActiveAppSubscriptions = async ({ fetcher, adminAccessToken, domain }) => {
5253
+ var _a, _b;
5254
+ const data2 = await adminFetch({
5255
+ fetcher,
5256
+ adminAccessToken,
5257
+ domain,
5258
+ query: `{
5259
+ currentAppInstallation {
5260
+ activeSubscriptions {
5261
+ id
5262
+ name
5263
+ status
5264
+ test
5265
+ lineItems {
5266
+ id
5267
+ plan {
5268
+ pricingDetails {
5269
+ __typename
5270
+ }
5271
+ }
5272
+ }
5273
+ }
5274
+ }
5275
+ shop {
5276
+ myshopifyDomain
5277
+ }
5278
+ }`
5279
+ });
5280
+ return {
5281
+ shopDomain: ((_a = data2 == null ? void 0 : data2.shop) == null ? void 0 : _a.myshopifyDomain) || null,
5282
+ subscriptions: (((_b = data2 == null ? void 0 : data2.currentAppInstallation) == null ? void 0 : _b.activeSubscriptions) || []).map((subscription) => {
5283
+ var _a2;
5284
+ return {
5285
+ ...subscription,
5286
+ metered: ((subscription == null ? void 0 : subscription.lineItems) || []).some(
5287
+ (item) => {
5288
+ var _a3, _b2;
5289
+ return ((_b2 = (_a3 = item == null ? void 0 : item.plan) == null ? void 0 : _a3.pricingDetails) == null ? void 0 : _b2.__typename) === "AppUsagePricing";
5290
+ }
5291
+ ),
5292
+ // The usage line's own id — the address appUsageRecordCreate charges
5293
+ // against. Null when the approval carries no usage component.
5294
+ usageLineItemId: ((_a2 = ((subscription == null ? void 0 : subscription.lineItems) || []).find(
5295
+ (item) => {
5296
+ var _a3, _b2;
5297
+ return ((_b2 = (_a3 = item == null ? void 0 : item.plan) == null ? void 0 : _a3.pricingDetails) == null ? void 0 : _b2.__typename) === "AppUsagePricing";
5298
+ }
5299
+ )) == null ? void 0 : _a2.id) || null
5300
+ };
5301
+ })
5302
+ };
5303
+ };
5304
+ var createUsageSubscription = async ({ fetcher, adminAccessToken, cappedAmount, currencyCode = "USD", domain, name, recurringPrice = 0, returnUrl, terms, test = false }) => {
5305
+ if (!name || !returnUrl || !terms || !(Number(cappedAmount) > 0)) {
5306
+ throw new Error("createUsageSubscription requires name, returnUrl, terms, and a positive cappedAmount");
5307
+ }
5308
+ ;
5309
+ const data2 = await adminFetch({
5310
+ fetcher,
5311
+ adminAccessToken,
5312
+ domain,
5313
+ query: `mutation createUsageSubscription( $lineItems : [AppSubscriptionLineItemInput!]!, $name : String!, $returnUrl : URL!, $test : Boolean ) {
5314
+ appSubscriptionCreate( lineItems : $lineItems, name : $name, returnUrl : $returnUrl, test : $test ) {
5315
+ appSubscription { id name status test lineItems { id plan { pricingDetails { __typename } } } }
5316
+ confirmationUrl
5317
+ userErrors { field message }
5318
+ }
5319
+ }`,
5320
+ variables: {
5321
+ lineItems: [
5322
+ {
5323
+ plan: {
5324
+ appRecurringPricingDetails: {
5325
+ interval: "EVERY_30_DAYS",
5326
+ price: { amount: Number(recurringPrice), currencyCode }
5327
+ }
5328
+ }
5329
+ },
5330
+ {
5331
+ plan: {
5332
+ appUsagePricingDetails: {
5333
+ cappedAmount: { amount: Number(cappedAmount), currencyCode },
5334
+ terms
5335
+ }
5336
+ }
5337
+ }
5338
+ ],
5339
+ name,
5340
+ returnUrl,
5341
+ test
5342
+ }
5343
+ });
5344
+ const payload = data2 == null ? void 0 : data2.appSubscriptionCreate;
5345
+ const userErrors = (payload == null ? void 0 : payload.userErrors) || [];
5346
+ if (userErrors.length) {
5347
+ throw new Error("Shopify subscription create failed: " + userErrors.map((entry) => entry.message).join("; "));
5348
+ }
5349
+ ;
5350
+ if (!(payload == null ? void 0 : payload.confirmationUrl)) {
5351
+ throw new Error("Shopify subscription create failed: no confirmation url returned");
5352
+ }
5353
+ ;
5354
+ return {
5355
+ confirmationUrl: payload.confirmationUrl,
5356
+ subscription: payload.appSubscription
5357
+ };
5358
+ };
5359
+ var createUsageRecord = async ({ fetcher, adminAccessToken, amount, currencyCode = "USD", description, domain, idempotencyKey, subscriptionLineItemId }) => {
4927
5360
  var _a;
4928
- if ((discount == null ? void 0 : discount.status) === "EXPIRED") return "This discount has expired.";
4929
- const buyers = (_a = discount == null ? void 0 : discount.context) == null ? void 0 : _a.__typename;
4930
- if (buyers && buyers !== "DiscountBuyerSelectionAll") {
4931
- 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.";
5361
+ if (!subscriptionLineItemId || !description || !(Number(amount) > 0)) {
5362
+ throw new Error("createUsageRecord requires subscriptionLineItemId, description, and a positive amount");
4932
5363
  }
4933
5364
  ;
4934
- if (typeof (discount == null ? void 0 : discount.usageLimit) === "number" && discount.usageLimit > 0 && ((discount == null ? void 0 : discount.asyncUsageCount) || 0) >= discount.usageLimit) {
4935
- return "This discount has reached its total usage limit.";
5365
+ const data2 = await adminFetch({
5366
+ fetcher,
5367
+ adminAccessToken,
5368
+ domain,
5369
+ query: `mutation createUsageRecord( $description : String!, $idempotencyKey : String, $price : MoneyInput!, $subscriptionLineItemId : ID! ) {
5370
+ appUsageRecordCreate( description : $description, idempotencyKey : $idempotencyKey, price : $price, subscriptionLineItemId : $subscriptionLineItemId ) {
5371
+ appUsageRecord { id }
5372
+ userErrors { field message }
5373
+ }
5374
+ }`,
5375
+ variables: {
5376
+ description,
5377
+ idempotencyKey: idempotencyKey ? String(idempotencyKey) : null,
5378
+ price: { amount: Number(amount), currencyCode },
5379
+ subscriptionLineItemId
5380
+ }
5381
+ });
5382
+ const payload = data2 == null ? void 0 : data2.appUsageRecordCreate;
5383
+ const userErrors = (payload == null ? void 0 : payload.userErrors) || [];
5384
+ if (userErrors.length || !((_a = payload == null ? void 0 : payload.appUsageRecord) == null ? void 0 : _a.id)) {
5385
+ throw new Error("Shopify usage record failed: " + (userErrors.map((entry) => entry.message).join("; ") || "no record returned"));
4936
5386
  }
4937
5387
  ;
4938
- return null;
5388
+ return { id: payload.appUsageRecord.id };
4939
5389
  };
4940
- var discountWarning = (discount) => {
4941
- if ((discount == null ? void 0 : discount.status) === "SCHEDULED") {
4942
- return "This discount hasn't started yet, so codes issued before it does won't work until then.";
5390
+ var getProductInventory = async ({ fetcher, adminAccessToken, domain, productId }) => {
5391
+ var _a, _b;
5392
+ const data2 = await adminFetch({
5393
+ fetcher,
5394
+ adminAccessToken,
5395
+ domain,
5396
+ query: `{
5397
+ product( id : "${productId}" ) {
5398
+ variants( first : 100 ) {
5399
+ edges {
5400
+ node {
5401
+ id
5402
+ inventoryQuantity
5403
+ }
5404
+ }
5405
+ }
5406
+ }
5407
+ }`
5408
+ });
5409
+ const edges = ((_b = (_a = data2 == null ? void 0 : data2.product) == null ? void 0 : _a.variants) == null ? void 0 : _b.edges) || [];
5410
+ return edges.reduce((accumulator, edge) => {
5411
+ var _a2, _b2;
5412
+ const id = (_a2 = edge == null ? void 0 : edge.node) == null ? void 0 : _a2.id;
5413
+ const quantity = (_b2 = edge == null ? void 0 : edge.node) == null ? void 0 : _b2.inventoryQuantity;
5414
+ if (id) {
5415
+ accumulator[id] = Number.isFinite(quantity) ? quantity : 0;
5416
+ }
5417
+ ;
5418
+ return accumulator;
5419
+ }, {});
5420
+ };
5421
+ var getProductUpdatedAt = async ({ adminAccessToken, domain, fetcher, productId }) => {
5422
+ var _a;
5423
+ const data2 = await adminFetch({
5424
+ fetcher,
5425
+ adminAccessToken,
5426
+ domain,
5427
+ query: `
5428
+ query ProductUpdatedAt($id: ID!) {
5429
+ product(id: $id) {
5430
+ updatedAt
5431
+ }
5432
+ }
5433
+ `,
5434
+ variables: { id: productId }
5435
+ });
5436
+ return ((_a = data2 == null ? void 0 : data2.product) == null ? void 0 : _a.updatedAt) || null;
5437
+ };
5438
+ var NOT_ON_CHANNEL = "not available to the channel";
5439
+ var OUTDATED_FEEDBACK = "later version";
5440
+ var sendProductResourceFeedback = async ({ fetcher, adminAccessToken, domain, productId, state, messages = [] }) => {
5441
+ var _a, _b, _c;
5442
+ const productUpdatedAt = await getProductUpdatedAt({ adminAccessToken, domain, fetcher, productId });
5443
+ if (!productUpdatedAt) return null;
5444
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5445
+ const submit = async (version) => {
5446
+ const data2 = await adminFetch({
5447
+ fetcher,
5448
+ adminAccessToken,
5449
+ domain,
5450
+ query: `
5451
+ mutation ProductFeedback($feedbackInput: [ProductResourceFeedbackInput!]!) {
5452
+ bulkProductResourceFeedbackCreate(feedbackInput: $feedbackInput) {
5453
+ feedback {
5454
+ productId
5455
+ state
5456
+ }
5457
+ userErrors {
5458
+ field
5459
+ message
5460
+ }
5461
+ }
5462
+ }
5463
+ `,
5464
+ variables: {
5465
+ feedbackInput: [
5466
+ {
5467
+ productId,
5468
+ state,
5469
+ feedbackGeneratedAt: now,
5470
+ productUpdatedAt: version,
5471
+ messages
5472
+ }
5473
+ ]
5474
+ }
5475
+ });
5476
+ return data2 == null ? void 0 : data2.bulkProductResourceFeedbackCreate;
5477
+ };
5478
+ let result = await submit(productUpdatedAt);
5479
+ if ((((_b = (_a = result == null ? void 0 : result.userErrors) == null ? void 0 : _a[0]) == null ? void 0 : _b.message) || "").toLowerCase().includes(OUTDATED_FEEDBACK)) {
5480
+ result = await submit(now);
4943
5481
  }
4944
5482
  ;
4945
- if (discount == null ? void 0 : discount.appliesOncePerCustomer) return "Each customer can use this discount only once.";
4946
- return null;
5483
+ const feedbackErrors = result == null ? void 0 : result.userErrors;
5484
+ if (feedbackErrors == null ? void 0 : feedbackErrors.length) {
5485
+ const message = feedbackErrors[0].message || "";
5486
+ if (message.toLowerCase().includes(NOT_ON_CHANNEL)) return null;
5487
+ throw new Error("Shopify product feedback failed: " + message);
5488
+ }
5489
+ ;
5490
+ return ((_c = result == null ? void 0 : result.feedback) == null ? void 0 : _c[0]) || null;
4947
5491
  };
4948
- var ORDER_EVENT_HANDLE = slugify("drawbridge-orders");
4949
- var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
4950
- var OAUTH_ERROR_SOURCE = "oauth";
4951
- var BILLING_ERROR_SOURCE = "billing";
4952
- var BILLING_ERROR_MESSAGE = "Order billing isn't set up for this store \u2014 reselect and approve the plan from the Shopify connection page.";
4953
- var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
4954
- var inbound = {
4955
- headers: {
4956
- event: "x-shopify-topic",
4957
- id: "x-shopify-webhook-id",
4958
- shop: "x-shopify-shop-domain",
4959
- signature: "x-shopify-hmac-sha256"
4960
- },
4961
- signature: {
4962
- algorithm: "sha256",
4963
- encoding: "base64",
4964
- secret: "SHOPIFY_API_SECRET"
5492
+
5493
+ // lib/shopify/billing.js
5494
+ var billing_exports = {};
5495
+ __export(billing_exports, {
5496
+ sendAppEvent: () => sendAppEvent
5497
+ });
5498
+ var APP_API = "https://api.shopify.com";
5499
+ var APP_API_VERSION = process.env.SHOPIFY_APP_API_VERSION || SHOPIFY_APP_API_VERSION;
5500
+ var cachedTokens = {};
5501
+ var fetchAppToken = async ({ clientId, clientSecret, fetcher }) => {
5502
+ const data2 = await request({
5503
+ fetcher,
5504
+ method: "POST",
5505
+ url: APP_API + "/auth/access_token",
5506
+ body: {
5507
+ client_id: clientId,
5508
+ client_secret: clientSecret,
5509
+ grant_type: "client_credentials"
5510
+ }
5511
+ });
5512
+ if (!(data2 == null ? void 0 : data2.access_token)) {
5513
+ throw new Error("Shopify app token request failed: no access token returned");
4965
5514
  }
5515
+ ;
5516
+ const ttl = data2.expires_in ? data2.expires_in * 1e3 : 60 * 60 * 1e3;
5517
+ cachedTokens[clientId] = {
5518
+ expiresAt: Date.now() + ttl - 60 * 1e3,
5519
+ token: data2.access_token
5520
+ };
5521
+ return data2.access_token;
4966
5522
  };
4967
- var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
5523
+ var getAppToken = async ({ clientId, clientSecret, fetcher }) => {
5524
+ const cached = cachedTokens[clientId];
5525
+ if (cached && cached.expiresAt > Date.now()) {
5526
+ return cached.token;
5527
+ }
5528
+ ;
5529
+ return fetchAppToken({ clientId, clientSecret, fetcher });
5530
+ };
5531
+ var toShopGid = (shopId) => String(shopId).startsWith("gid://") ? String(shopId) : "gid://shopify/Shop/" + shopId;
5532
+ var sendAppEvent = async ({ fetcher, clientId, clientSecret, eventHandle, idempotencyKey, reference: reference2, revision, shopId, timestamp, value }) => {
5533
+ if (!shopId || !eventHandle || !(Number(value) > 0)) {
5534
+ throw new Error("sendAppEvent requires shopId, eventHandle, and a positive value");
5535
+ }
5536
+ ;
5537
+ if (!clientId || !clientSecret) {
5538
+ throw new Error("sendAppEvent requires clientId and clientSecret");
5539
+ }
5540
+ ;
5541
+ const suffix = revision ? ".r" + revision : "";
5542
+ const key = idempotencyKey && String(idempotencyKey).slice(0, Math.max(0, 64 - suffix.length)) + suffix;
5543
+ const body = {
5544
+ attributes: {
5545
+ value: Number(value),
5546
+ ...reference2 && {
5547
+ reference: String(reference2).slice(0, 128)
5548
+ }
5549
+ },
5550
+ event_handle: eventHandle,
5551
+ shop_id: toShopGid(shopId),
5552
+ timestamp: timestamp || (/* @__PURE__ */ new Date()).toISOString(),
5553
+ ...key && {
5554
+ idempotency_key: key
5555
+ }
5556
+ };
5557
+ const send2 = async (token) => request({
5558
+ method: "POST",
5559
+ url: APP_API + "/app/" + APP_API_VERSION + "/events",
5560
+ headers: {
5561
+ "Authorization": "Bearer " + token
5562
+ },
5563
+ body
5564
+ });
5565
+ try {
5566
+ return await send2(await getAppToken({ clientId, clientSecret, fetcher }));
5567
+ } catch (error) {
5568
+ if ((error == null ? void 0 : error.status) === 401) {
5569
+ delete cachedTokens[clientId];
5570
+ return send2(await fetchAppToken({ clientId, clientSecret, fetcher }));
5571
+ }
5572
+ ;
5573
+ throw error;
5574
+ }
5575
+ };
5576
+
5577
+ // lib/shopify/oauth.js
5578
+ var oauth_exports = {};
5579
+ __export(oauth_exports, {
5580
+ SHOPIFY_REQUIRED_SCOPES: () => SHOPIFY_REQUIRED_SCOPES,
5581
+ createStorefrontToken: () => createStorefrontToken,
5582
+ getAdminToken: () => getAdminToken,
5583
+ getShop: () => getShop,
5584
+ missingScopes: () => missingScopes2,
5585
+ ping: () => ping,
5586
+ refreshAdminToken: () => refreshAdminToken,
5587
+ resolveConnectionSettings: () => resolveConnectionSettings
5588
+ });
5589
+ var required = (name, value) => {
5590
+ if (!value) {
5591
+ throw new Error("Shopify " + name + " is required");
5592
+ }
5593
+ ;
5594
+ return value;
5595
+ };
5596
+ var missingScopes2 = (granted) => {
5597
+ const grantedSet = new Set(
5598
+ (Array.isArray(granted) ? granted : String(granted || "").split(",")).map((scope) => scope.trim()).filter(Boolean)
5599
+ );
5600
+ const satisfied = (scope) => grantedSet.has(scope) || grantedSet.has(scope.replace(/(^|_)read_/, "$1write_"));
5601
+ return SHOPIFY_REQUIRED_SCOPES.filter((scope) => !satisfied(scope));
5602
+ };
5603
+ var ping = async ({ fetcher, adminAccessToken, domain }) => {
5604
+ var _a;
5605
+ const response = await fetch(
5606
+ `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}/graphql.json`,
5607
+ {
5608
+ body: JSON.stringify({ query: "{ shop { name } }" }),
5609
+ headers: {
5610
+ "Content-Type": "application/json",
5611
+ "X-Shopify-Access-Token": adminAccessToken
5612
+ },
5613
+ method: "POST"
5614
+ }
5615
+ );
5616
+ if (!response.ok) {
5617
+ const text = await response.text().catch(() => "");
5618
+ const error = new Error(response.status + ": " + text);
5619
+ error.status = response.status;
5620
+ throw error;
5621
+ }
5622
+ ;
5623
+ const { errors } = await response.json().catch(() => ({}));
5624
+ if (errors == null ? void 0 : errors.length) {
5625
+ throw new Error("GraphQL: " + (((_a = errors[0]) == null ? void 0 : _a.message) || "unknown error"));
5626
+ }
5627
+ ;
5628
+ };
5629
+ var OAUTH_ERROR_TITLE_PATTERN = /Oauth error (\w+)/i;
5630
+ var parseOAuthErrorCode = (text) => {
5631
+ var _a;
5632
+ try {
5633
+ const parsed = JSON.parse(text);
5634
+ if (parsed == null ? void 0 : parsed.error) return parsed.error;
5635
+ } catch {
5636
+ }
5637
+ ;
5638
+ return ((_a = text.match(OAUTH_ERROR_TITLE_PATTERN)) == null ? void 0 : _a[1]) || null;
5639
+ };
5640
+ var shopifyOAuthFetch = async (url, body) => {
5641
+ const response = await fetch(url, {
5642
+ method: "POST",
5643
+ headers: {
5644
+ "Content-Type": "application/json"
5645
+ },
5646
+ body: JSON.stringify(body)
5647
+ });
5648
+ if (!response.ok) {
5649
+ const text = await response.text().catch(() => "");
5650
+ const error = new Error(response.status + ": " + text);
5651
+ error.status = response.status;
5652
+ error.code = parseOAuthErrorCode(text);
5653
+ throw error;
5654
+ }
5655
+ ;
5656
+ return response.json();
5657
+ };
5658
+ var getShop = async ({ fetcher, adminAccessToken, shop }) => {
5659
+ const data2 = await adminFetch({
5660
+ fetcher,
5661
+ adminAccessToken,
5662
+ domain: shop,
5663
+ query: `{
5664
+ shop {
5665
+ currencyCode
5666
+ id
5667
+ myshopifyDomain
5668
+ name
5669
+ }
5670
+ }`
5671
+ });
5672
+ const shopData = data2 == null ? void 0 : data2.shop;
5673
+ if (!(shopData == null ? void 0 : shopData.id)) {
5674
+ throw new Error("Shopify shop lookup failed: no shop returned");
5675
+ }
5676
+ ;
5677
+ return {
5678
+ currency: shopData.currencyCode || null,
5679
+ id: shopData.id.split("/").pop(),
5680
+ myshopifyDomain: shopData.myshopifyDomain,
5681
+ name: shopData.name
5682
+ };
5683
+ };
5684
+ var createStorefrontToken = async ({ fetcher, adminAccessToken, shop }) => {
5685
+ var _a, _b, _c, _d, _e;
5686
+ try {
5687
+ const listed = await adminFetch({
5688
+ fetcher,
5689
+ adminAccessToken,
5690
+ domain: shop,
5691
+ query: `{
5692
+ shop {
5693
+ storefrontAccessTokens(first: 100) {
5694
+ edges {
5695
+ node {
5696
+ id
5697
+ title
5698
+ }
5699
+ }
5700
+ }
5701
+ }
5702
+ }`
5703
+ });
5704
+ 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);
5705
+ const orphaned = existing.filter((token) => (token == null ? void 0 : token.title) === "Drawbridge");
5706
+ await Promise.allSettled(
5707
+ orphaned.map((token) => adminFetch({
5708
+ adminAccessToken,
5709
+ domain: shop,
5710
+ query: `
5711
+ mutation StorefrontAccessTokenDelete($input: StorefrontAccessTokenDeleteInput!) {
5712
+ storefrontAccessTokenDelete(input: $input) {
5713
+ deletedStorefrontAccessTokenId
5714
+ userErrors {
5715
+ field
5716
+ message
5717
+ }
5718
+ }
5719
+ }
5720
+ `,
5721
+ variables: {
5722
+ input: {
5723
+ id: token.id
5724
+ }
5725
+ }
5726
+ }))
5727
+ );
5728
+ } catch {
5729
+ }
5730
+ const created = await adminFetch({
5731
+ fetcher,
5732
+ adminAccessToken,
5733
+ domain: shop,
5734
+ query: `
5735
+ mutation StorefrontAccessTokenCreate($input: StorefrontAccessTokenInput!) {
5736
+ storefrontAccessTokenCreate(input: $input) {
5737
+ storefrontAccessToken {
5738
+ accessToken
5739
+ }
5740
+ userErrors {
5741
+ field
5742
+ message
5743
+ }
5744
+ }
5745
+ }
5746
+ `,
5747
+ variables: {
5748
+ input: {
5749
+ title: "Drawbridge"
5750
+ }
5751
+ }
5752
+ });
5753
+ const createErrors = (_c = created == null ? void 0 : created.storefrontAccessTokenCreate) == null ? void 0 : _c.userErrors;
5754
+ if (createErrors == null ? void 0 : createErrors.length) {
5755
+ throw new Error("Shopify storefront token create failed: " + createErrors[0].message);
5756
+ }
5757
+ ;
5758
+ return ((_e = (_d = created == null ? void 0 : created.storefrontAccessTokenCreate) == null ? void 0 : _d.storefrontAccessToken) == null ? void 0 : _e.accessToken) || null;
5759
+ };
5760
+ var resolveTokenContext = async ({ connection: connection2, controller }) => {
5761
+ const decrypted = (connection2 == null ? void 0 : connection2.settings) ? decrypt(connection2.settings) : {};
5762
+ if ((decrypted == null ? void 0 : decrypted.ref) !== "shop") {
5763
+ return {
5764
+ raw: (connection2 == null ? void 0 : connection2.settings) || null,
5765
+ session: null,
5766
+ settings: decrypted,
5767
+ shop: null,
5768
+ target: "connection"
5769
+ };
5770
+ }
5771
+ ;
5772
+ const shop = decrypted.shop;
5773
+ if (!controller || !shop) {
5774
+ return { raw: null, session: {}, settings: {}, shop, target: "shop" };
5775
+ }
5776
+ ;
5777
+ const record = await controller.get({ collection: "shop", query: { shop } });
5778
+ const session = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : {};
5779
+ const storefront = (record == null ? void 0 : record.storefront) ? decrypt(record.storefront) : null;
5780
+ return {
5781
+ raw: (record == null ? void 0 : record.settings) || null,
5782
+ session,
5783
+ settings: {
5784
+ adminAccessToken: session.accessToken || null,
5785
+ refreshToken: session.refreshToken || null,
5786
+ refreshTokenExpiresAt: session.refreshTokenExpires || null,
5787
+ storefrontAccessToken: (storefront == null ? void 0 : storefront.token) || null,
5788
+ tokenExpiresAt: session.expires || null
5789
+ },
5790
+ shop,
5791
+ target: "shop"
5792
+ };
5793
+ };
5794
+ var resolveConnectionSettings = async ({ fetcher, connection: connection2, controller }) => {
5795
+ const { settings } = await resolveTokenContext({ connection: connection2, controller });
5796
+ return settings;
5797
+ };
5798
+ var refreshAdminToken = async ({ fetcher, clientId, clientSecret, connection: connection2, controller }) => {
5799
+ var _a;
5800
+ const { raw, session, settings, shop, target } = await resolveTokenContext({ connection: connection2, controller });
5801
+ const domain = (connection2 == null ? void 0 : connection2.shop) || ((_a = settings.source) == null ? void 0 : _a.domain) || settings.domain || shop;
5802
+ const { refreshToken } = settings;
5803
+ const data2 = await shopifyOAuthFetch(
5804
+ `https://${domain}/admin/oauth/access_token`,
5805
+ {
5806
+ grant_type: "refresh_token",
5807
+ // Throw before the grant: rotation RETIRES the old pair the moment it
5808
+ // returns, so a credential-less call that Shopify rejects opaquely is
5809
+ // the one failure mode worth being loud about.
5810
+ client_id: required("clientId", clientId),
5811
+ client_secret: required("clientSecret", clientSecret),
5812
+ refresh_token: refreshToken
5813
+ }
5814
+ );
5815
+ const adminAccessToken = data2.access_token;
5816
+ const newRefreshToken = data2.refresh_token;
5817
+ const expiresIn = data2.expires_in;
5818
+ const tokenExpiresAt = expiresIn ? new Date(Date.now() + expiresIn * 1e3) : null;
5819
+ const refreshTokenExpiresAt = new Date(Date.now() + REFRESH_TOKEN_LIFETIME_MS);
5820
+ let liveToken = adminAccessToken;
5821
+ if (target === "shop") {
5822
+ const written = await controller.update({
5823
+ collection: "shop",
5824
+ data: {
5825
+ $set: {
5826
+ settings: encrypt({
5827
+ ...session,
5828
+ accessToken: adminAccessToken,
5829
+ expires: tokenExpiresAt,
5830
+ refreshToken: newRefreshToken,
5831
+ refreshTokenExpires: refreshTokenExpiresAt
5832
+ })
5833
+ }
5834
+ },
5835
+ query: {
5836
+ shop,
5837
+ ...raw && { settings: raw }
5838
+ }
5839
+ });
5840
+ if (!written) {
5841
+ const current = await controller.get({ collection: "shop", query: { shop } });
5842
+ if (!(current == null ? void 0 : current.settings)) {
5843
+ throw new Error("Shopify token refresh write-back failed: shop record missing for " + shop);
5844
+ }
5845
+ ;
5846
+ const currentSession = decrypt(current.settings);
5847
+ if ((currentSession == null ? void 0 : currentSession.accessToken) && currentSession.accessToken !== settings.adminAccessToken) {
5848
+ liveToken = currentSession.accessToken;
5849
+ } else {
5850
+ throw new Error("Shopify token refresh write-back failed for " + shop);
5851
+ }
5852
+ ;
5853
+ }
5854
+ ;
5855
+ } else {
5856
+ const written = await controller.update({
5857
+ collection: "connection",
5858
+ data: {
5859
+ $set: {
5860
+ settings: encrypt({
5861
+ ...settings,
5862
+ adminAccessToken,
5863
+ refreshToken: newRefreshToken,
5864
+ refreshTokenExpiresAt,
5865
+ tokenExpiresAt
5866
+ })
5867
+ }
5868
+ },
5869
+ query: {
5870
+ id: connection2.id,
5871
+ ...raw && { settings: raw }
5872
+ }
5873
+ });
5874
+ if (!written) {
5875
+ const current = await controller.get({ collection: "connection", query: { id: connection2.id } });
5876
+ const currentSettings = (current == null ? void 0 : current.settings) ? decrypt(current.settings) : null;
5877
+ if ((currentSettings == null ? void 0 : currentSettings.adminAccessToken) && currentSettings.adminAccessToken !== settings.adminAccessToken) {
5878
+ liveToken = currentSettings.adminAccessToken;
5879
+ } else {
5880
+ throw new Error("Shopify token refresh write-back failed for connection " + (connection2 == null ? void 0 : connection2.id));
5881
+ }
5882
+ ;
5883
+ }
5884
+ ;
5885
+ }
5886
+ ;
5887
+ await ping({ adminAccessToken: liveToken, domain });
5888
+ return liveToken;
5889
+ };
5890
+ var getAdminToken = async ({ fetcher, clientId, clientSecret, connection: connection2, controller }) => {
5891
+ required("clientId", clientId);
5892
+ required("clientSecret", clientSecret);
5893
+ const settings = await resolveConnectionSettings({ connection: connection2, controller });
5894
+ const { adminAccessToken, refreshToken, tokenExpiresAt } = settings;
5895
+ if (!adminAccessToken) {
5896
+ return null;
5897
+ }
5898
+ ;
5899
+ if (!refreshToken) {
5900
+ return adminAccessToken;
5901
+ }
5902
+ ;
5903
+ const needsRefresh = !tokenExpiresAt || new Date(tokenExpiresAt) < new Date(Date.now() + ACCESS_TOKEN_REFRESH_BUFFER_MS);
5904
+ if (needsRefresh) {
5905
+ return refreshAdminToken({ clientId, clientSecret, connection: connection2, controller });
5906
+ }
5907
+ ;
5908
+ return adminAccessToken;
5909
+ };
5910
+
5911
+ // lib/shopify/partner.js
5912
+ var partner_exports = {};
5913
+ __export(partner_exports, {
5914
+ getUsageChargeEvents: () => getUsageChargeEvents
5915
+ });
5916
+ var PARTNER_API = "https://partners.shopify.com";
5917
+ var getUsageChargeEvents = async ({ fetcher, appId, first = 10, occurredAtMin, organizationId, partnerToken, shopId }) => {
5918
+ var _a, _b, _c;
5919
+ if (!partnerToken || !organizationId || !appId) {
5920
+ throw new Error("getUsageChargeEvents requires partnerToken, organizationId, and appId");
5921
+ }
5922
+ ;
5923
+ const data2 = await request({
5924
+ fetcher,
5925
+ method: "POST",
5926
+ url: PARTNER_API + "/" + organizationId + "/api/" + PARTNER_API_VERSION + "/graphql.json",
5927
+ headers: {
5928
+ "X-Shopify-Access-Token": partnerToken
5929
+ },
5930
+ body: {
5931
+ query: `query usageCharges( $filter : EventFilterInput!, $first : Int! ) {
5932
+ events( filter : $filter, orderBy : OCCURRED_AT_DESC, first : $first ) {
5933
+ edges {
5934
+ node {
5935
+ id
5936
+ occurredAt
5937
+ eventType
5938
+ shop { id myshopifyDomain }
5939
+ ... on Charge {
5940
+ chargeId
5941
+ chargeType
5942
+ amount { amount currencyCode }
5943
+ usageQuantity
5944
+ planHandle
5945
+ description
5946
+ }
5947
+ }
5948
+ }
5949
+ pageInfo { hasNextPage endCursor }
5950
+ }
5951
+ }`,
5952
+ variables: {
5953
+ filter: {
5954
+ eventTypes: ["CHARGE_USAGE"],
5955
+ subjectId: String(appId),
5956
+ ...occurredAtMin && { occurredAtMin },
5957
+ ...shopId && { shopId: String(shopId) }
5958
+ },
5959
+ first
5960
+ }
5961
+ }
5962
+ });
5963
+ if ((_a = data2 == null ? void 0 : data2.errors) == null ? void 0 : _a.length) {
5964
+ throw new Error("Shopify partner events query failed: " + data2.errors.map((entry) => entry.message).join("; "));
5965
+ }
5966
+ ;
5967
+ return (((_c = (_b = data2 == null ? void 0 : data2.data) == null ? void 0 : _b.events) == null ? void 0 : _c.edges) || []).map((edge) => {
5968
+ var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j;
5969
+ return {
5970
+ amount: ((_a2 = edge.node) == null ? void 0 : _a2.amount) || null,
5971
+ chargeId: ((_b2 = edge.node) == null ? void 0 : _b2.chargeId) || null,
5972
+ // USAGE vs the recurring plan charge an approval emits — the
5973
+ // disambiguator callers filter on.
5974
+ chargeType: ((_c2 = edge.node) == null ? void 0 : _c2.chargeType) || null,
5975
+ description: ((_d = edge.node) == null ? void 0 : _d.description) || null,
5976
+ eventType: ((_e = edge.node) == null ? void 0 : _e.eventType) || null,
5977
+ id: ((_f = edge.node) == null ? void 0 : _f.id) || null,
5978
+ occurredAt: ((_g = edge.node) == null ? void 0 : _g.occurredAt) || null,
5979
+ planHandle: ((_h = edge.node) == null ? void 0 : _h.planHandle) || null,
5980
+ shop: ((_i = edge.node) == null ? void 0 : _i.shop) || null,
5981
+ usageQuantity: ((_j = edge.node) == null ? void 0 : _j.usageQuantity) ?? null
5982
+ };
5983
+ });
5984
+ };
5985
+
5986
+ // lib/shopify/storefront.js
5987
+ var storefront_exports = {};
5988
+ __export(storefront_exports, {
5989
+ cartCreate: () => cartCreate,
5990
+ cartGet: () => cartGet,
5991
+ cartLinesAdd: () => cartLinesAdd,
5992
+ cartLinesRemove: () => cartLinesRemove,
5993
+ cartLinesUpdate: () => cartLinesUpdate,
5994
+ createCheckoutToken: () => createCheckoutToken,
5995
+ getProduct: () => getProduct,
5996
+ getProductVariantsPage: () => getProductVariantsPage,
5997
+ getProducts: () => getProducts,
5998
+ probeVariantsOutOfStock: () => probeVariantsOutOfStock
5999
+ });
6000
+ var SORT_KEY_MAP = {
6001
+ bestSelling: "BEST_SELLING",
6002
+ createdAt: "CREATED_AT",
6003
+ id: "ID",
6004
+ price: "PRICE",
6005
+ productType: "PRODUCT_TYPE",
6006
+ title: "TITLE",
6007
+ updatedAt: "UPDATED_AT",
6008
+ vendor: "VENDOR"
6009
+ };
6010
+ var resolveProductSort = (sort) => {
6011
+ const entry = sort && Object.entries(sort)[0];
6012
+ if (!entry) return null;
6013
+ const [field2, direction] = entry;
6014
+ const sortKey = SORT_KEY_MAP[field2];
6015
+ if (!sortKey) return null;
6016
+ return {
6017
+ sortKey,
6018
+ reverse: Number(direction) < 0
6019
+ };
6020
+ };
6021
+ var storefrontUrl = (domain) => `https://${domain}/api/${SHOPIFY_STOREFRONT_API_VERSION}/graphql.json`;
6022
+ var storefrontFetch = async ({ fetcher, domain, storefrontAccessToken, query, variables }) => {
6023
+ return request({
6024
+ method: "POST",
6025
+ url: storefrontUrl(domain),
6026
+ headers: {
6027
+ "X-Shopify-Storefront-Access-Token": storefrontAccessToken
6028
+ },
6029
+ body: {
6030
+ query,
6031
+ ...variables && { variables }
6032
+ }
6033
+ });
6034
+ };
6035
+ var shopCountryCache = {};
6036
+ var getShopCountry = async ({ domain, fetcher, storefrontAccessToken }) => {
6037
+ var _a, _b;
6038
+ if (shopCountryCache[domain]) return shopCountryCache[domain];
6039
+ const { data: data2 } = await storefrontFetch({
6040
+ fetcher,
6041
+ domain,
6042
+ storefrontAccessToken,
6043
+ query: `{
6044
+ shop {
6045
+ paymentSettings {
6046
+ countryCode
6047
+ }
6048
+ }
6049
+ }`
6050
+ });
6051
+ const countryCode = ((_b = (_a = data2 == null ? void 0 : data2.shop) == null ? void 0 : _a.paymentSettings) == null ? void 0 : _b.countryCode) || null;
6052
+ if (countryCode) shopCountryCache[domain] = countryCode;
6053
+ return countryCode;
6054
+ };
6055
+ var OUT_OF_STOCK_WARNING_CODES = [
6056
+ "MERCHANDISE_OUT_OF_STOCK",
6057
+ "MERCHANDISE_NOT_ENOUGH_STOCK"
6058
+ ];
6059
+ var probeVariantsOutOfStock = async ({ fetcher, domain, storefrontAccessToken, variantIds, countryCode }) => {
6060
+ var _a, _b;
6061
+ if (!(variantIds == null ? void 0 : variantIds.length)) return [];
6062
+ const resolvedCountry = countryCode || await getShopCountry({ domain, fetcher, storefrontAccessToken });
6063
+ const { data: data2, errors } = await storefrontFetch({
6064
+ fetcher,
6065
+ domain,
6066
+ storefrontAccessToken,
6067
+ query: `
6068
+ mutation probe( $input : CartInput! ){
6069
+ cartCreate( input : $input ){
6070
+ cart {
6071
+ lines( first : 250 ){
6072
+ edges {
6073
+ node {
6074
+ id
6075
+ merchandise {
6076
+ ... on ProductVariant {
6077
+ id
6078
+ }
6079
+ }
6080
+ }
6081
+ }
6082
+ }
6083
+ }
6084
+ warnings {
6085
+ code
6086
+ message
6087
+ target
6088
+ }
6089
+ }
6090
+ }
6091
+ `,
6092
+ variables: {
6093
+ input: {
6094
+ lines: variantIds.map((merchandiseId) => ({
6095
+ merchandiseId,
6096
+ quantity: 1
6097
+ })),
6098
+ ...resolvedCountry && {
6099
+ buyerIdentity: {
6100
+ countryCode: resolvedCountry
6101
+ }
6102
+ }
6103
+ }
6104
+ }
6105
+ });
6106
+ if (errors) return [];
6107
+ const payload = data2 == null ? void 0 : data2.cartCreate;
6108
+ const soldOut = new Set(
6109
+ ((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)
6110
+ );
6111
+ 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 }) => {
6112
+ var _a2;
6113
+ return (_a2 = node == null ? void 0 : node.merchandise) == null ? void 0 : _a2.id;
6114
+ }).filter(Boolean);
6115
+ };
6116
+ var productsQuery = (search, cursor, limit, sort) => {
6117
+ const resolved = resolveProductSort(sort);
6118
+ const sortArgs = resolved ? `, sortKey: ${resolved.sortKey}, reverse: ${resolved.reverse}` : "";
6119
+ return `{
6120
+ products(first: ${limit}${search ? `, query: "title:*${search}*"` : ""}${cursor ? `, after: "${cursor}"` : ""}${sortArgs}) {
6121
+ edges {
6122
+ node {
6123
+ id
6124
+ title
6125
+ description
6126
+ handle
6127
+ productType
6128
+ featuredImage {
6129
+ url
6130
+ }
6131
+ variants(first: 10) {
6132
+ edges {
6133
+ node {
6134
+ id
6135
+ title
6136
+ image {
6137
+ url
6138
+ }
6139
+ price {
6140
+ amount
6141
+ currencyCode
6142
+ }
6143
+ compareAtPrice {
6144
+ amount
6145
+ currencyCode
6146
+ }
6147
+ availableForSale
6148
+ requiresShipping
6149
+ }
6150
+ }
6151
+ }
6152
+ }
6153
+ }
6154
+ pageInfo {
6155
+ endCursor
6156
+ hasNextPage
6157
+ hasPreviousPage
6158
+ startCursor
6159
+ }
6160
+ }
6161
+ }`;
6162
+ };
6163
+ var productQuery = (productId) => `{
6164
+ product(id: "${productId}") {
6165
+ id
6166
+ title
6167
+ description
6168
+ handle
6169
+ productType
6170
+ featuredImage {
6171
+ url
6172
+ }
6173
+ variants(first: 10) {
6174
+ edges {
6175
+ node {
6176
+ id
6177
+ title
6178
+ image {
6179
+ url
6180
+ }
6181
+ price {
6182
+ amount
6183
+ currencyCode
6184
+ }
6185
+ compareAtPrice {
6186
+ amount
6187
+ currencyCode
6188
+ }
6189
+ availableForSale
6190
+ requiresShipping
6191
+ }
6192
+ }
6193
+ }
6194
+ }
6195
+ }`;
6196
+ var variantsQuery = (productId, cursor) => `{
6197
+ product(id: "${productId}") {
6198
+ variants(first: 250${cursor ? `, after: "${cursor}"` : ""}) {
6199
+ edges {
6200
+ node {
6201
+ id
6202
+ title
6203
+ image {
6204
+ url
6205
+ }
6206
+ price {
6207
+ amount
6208
+ currencyCode
6209
+ }
6210
+ compareAtPrice {
6211
+ amount
6212
+ currencyCode
6213
+ }
6214
+ availableForSale
6215
+ requiresShipping
6216
+ }
6217
+ }
6218
+ pageInfo {
6219
+ hasNextPage
6220
+ endCursor
6221
+ }
6222
+ }
6223
+ }
6224
+ }`;
6225
+ var getProducts = async ({ fetcher, domain, storefrontAccessToken, search, cursor, limit, sort }) => {
6226
+ const { data: data2, errors } = await storefrontFetch({
6227
+ fetcher,
6228
+ domain,
6229
+ storefrontAccessToken,
6230
+ query: productsQuery(search, cursor, limit, sort)
6231
+ });
6232
+ if (errors) {
6233
+ throw new Error("Failed to fetch Shopify products");
6234
+ }
6235
+ ;
6236
+ return data2 == null ? void 0 : data2.products;
6237
+ };
6238
+ var getProduct = async ({ fetcher, domain, storefrontAccessToken, productId }) => {
6239
+ var _a;
6240
+ const { data: data2, errors } = await storefrontFetch({
6241
+ fetcher,
6242
+ domain,
6243
+ storefrontAccessToken,
6244
+ query: productQuery(productId)
6245
+ });
6246
+ if (errors) {
6247
+ throw new Error("Shopify storefront error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
6248
+ }
6249
+ ;
6250
+ if (!(data2 == null ? void 0 : data2.product)) {
6251
+ throw new Error("Shopify product not found");
6252
+ }
6253
+ ;
6254
+ return data2.product;
6255
+ };
6256
+ var getProductVariantsPage = async ({ fetcher, domain, storefrontAccessToken, productId, cursor }) => {
6257
+ var _a;
6258
+ const { data: data2, errors } = await storefrontFetch({
6259
+ fetcher,
6260
+ domain,
6261
+ storefrontAccessToken,
6262
+ query: variantsQuery(productId, cursor)
6263
+ });
6264
+ if (errors) {
6265
+ throw new Error("Shopify storefront error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
6266
+ }
6267
+ ;
6268
+ if (!(data2 == null ? void 0 : data2.product)) {
6269
+ throw new Error("Shopify product not found");
6270
+ }
6271
+ ;
6272
+ return data2.product.variants;
6273
+ };
6274
+ var CART_FIELDS = `
6275
+ id
6276
+ checkoutUrl
6277
+ lines(first: 100) {
6278
+ edges {
6279
+ node {
6280
+ id
6281
+ quantity
6282
+ merchandise {
6283
+ ... on ProductVariant {
6284
+ id
6285
+ title
6286
+ availableForSale
6287
+ image {
6288
+ url
6289
+ }
6290
+ price {
6291
+ amount
6292
+ currencyCode
6293
+ }
6294
+ product {
6295
+ title
6296
+ }
6297
+ }
6298
+ }
6299
+ }
6300
+ }
6301
+ }
6302
+ `;
6303
+ var mapCart = (cart) => {
6304
+ var _a;
6305
+ if (!cart) return null;
6306
+ return {
6307
+ checkoutUrl: cart.checkoutUrl,
6308
+ id: cart.id,
6309
+ lines: (((_a = cart.lines) == null ? void 0 : _a.edges) || []).map(({ node }) => {
6310
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
6311
+ return {
6312
+ availableForSale: ((_a2 = node == null ? void 0 : node.merchandise) == null ? void 0 : _a2.availableForSale) ?? true,
6313
+ currency: ((_c = (_b = node == null ? void 0 : node.merchandise) == null ? void 0 : _b.price) == null ? void 0 : _c.currencyCode) || null,
6314
+ id: node.id,
6315
+ image: ((_e = (_d = node == null ? void 0 : node.merchandise) == null ? void 0 : _d.image) == null ? void 0 : _e.url) || null,
6316
+ price: ((_g = (_f = node == null ? void 0 : node.merchandise) == null ? void 0 : _f.price) == null ? void 0 : _g.amount) || null,
6317
+ productTitle: ((_i = (_h = node == null ? void 0 : node.merchandise) == null ? void 0 : _h.product) == null ? void 0 : _i.title) || null,
6318
+ quantity: node.quantity,
6319
+ variantId: (_j = node == null ? void 0 : node.merchandise) == null ? void 0 : _j.id,
6320
+ variantTitle: ((_k = node == null ? void 0 : node.merchandise) == null ? void 0 : _k.title) || null
6321
+ };
6322
+ })
6323
+ };
6324
+ };
6325
+ var firstUserError = (userErrors) => {
6326
+ const error = userErrors == null ? void 0 : userErrors[0];
6327
+ if (!error) return null;
6328
+ const message = new Error(error.message || "Shopify cart error");
6329
+ message.userError = true;
6330
+ return message;
6331
+ };
6332
+ var createCheckoutToken = async ({ fetcher, clientId, clientSecret } = {}) => {
6333
+ if (!clientId || !clientSecret) {
6334
+ throw new Error("createCheckoutToken requires clientId and clientSecret");
6335
+ }
6336
+ ;
6337
+ const response = await request({
6338
+ fetcher,
6339
+ method: "POST",
6340
+ url: "https://api.shopify.com/auth/access_token",
6341
+ body: {
6342
+ client_id: clientId,
6343
+ client_secret: clientSecret,
6344
+ grant_type: "client_credentials"
6345
+ }
6346
+ });
6347
+ const token = response == null ? void 0 : response.access_token;
6348
+ if (!token) {
6349
+ throw new Error("Failed to create Shopify checkout token");
6350
+ }
6351
+ ;
6352
+ return token;
6353
+ };
6354
+ var cartCreate = async ({ fetcher, domain, storefrontAccessToken, lines }) => {
6355
+ var _a, _b;
6356
+ const { data: data2, errors } = await storefrontFetch({
6357
+ fetcher,
6358
+ domain,
6359
+ storefrontAccessToken,
6360
+ query: `
6361
+ mutation cartCreate($input: CartInput!) {
6362
+ cartCreate(input: $input) {
6363
+ cart {
6364
+ ${CART_FIELDS}
6365
+ }
6366
+ userErrors {
6367
+ field
6368
+ message
6369
+ }
6370
+ }
6371
+ }
6372
+ `,
6373
+ variables: {
6374
+ input: {
6375
+ lines
6376
+ }
6377
+ }
6378
+ });
6379
+ if (errors) {
6380
+ throw new Error("Failed to create Shopify cart");
6381
+ }
6382
+ ;
6383
+ const userError = firstUserError((_a = data2 == null ? void 0 : data2.cartCreate) == null ? void 0 : _a.userErrors);
6384
+ if (userError) throw userError;
6385
+ return mapCart((_b = data2 == null ? void 0 : data2.cartCreate) == null ? void 0 : _b.cart);
6386
+ };
6387
+ var cartGet = async ({ fetcher, domain, storefrontAccessToken, cartId }) => {
6388
+ const { data: data2, errors } = await storefrontFetch({
6389
+ fetcher,
6390
+ domain,
6391
+ storefrontAccessToken,
6392
+ query: `
6393
+ query cart($id: ID!) {
6394
+ cart(id: $id) {
6395
+ ${CART_FIELDS}
6396
+ }
6397
+ }
6398
+ `,
6399
+ variables: {
6400
+ id: cartId
6401
+ }
6402
+ });
6403
+ if (errors) {
6404
+ throw new Error("Failed to fetch Shopify cart");
6405
+ }
6406
+ ;
6407
+ return mapCart(data2 == null ? void 0 : data2.cart);
6408
+ };
6409
+ var cartLinesAdd = async ({ fetcher, domain, storefrontAccessToken, cartId, lines }) => {
6410
+ var _a, _b;
6411
+ const { data: data2, errors } = await storefrontFetch({
6412
+ fetcher,
6413
+ domain,
6414
+ storefrontAccessToken,
6415
+ query: `
6416
+ mutation cartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {
6417
+ cartLinesAdd(cartId: $cartId, lines: $lines) {
6418
+ cart {
6419
+ ${CART_FIELDS}
6420
+ }
6421
+ userErrors {
6422
+ field
6423
+ message
6424
+ }
6425
+ }
6426
+ }
6427
+ `,
6428
+ variables: {
6429
+ cartId,
6430
+ lines
6431
+ }
6432
+ });
6433
+ if (errors) {
6434
+ throw new Error("Failed to add Shopify cart lines");
6435
+ }
6436
+ ;
6437
+ const userError = firstUserError((_a = data2 == null ? void 0 : data2.cartLinesAdd) == null ? void 0 : _a.userErrors);
6438
+ if (userError) throw userError;
6439
+ return mapCart((_b = data2 == null ? void 0 : data2.cartLinesAdd) == null ? void 0 : _b.cart);
6440
+ };
6441
+ var cartLinesRemove = async ({ fetcher, domain, storefrontAccessToken, cartId, lineIds }) => {
6442
+ var _a, _b;
6443
+ const { data: data2, errors } = await storefrontFetch({
6444
+ fetcher,
6445
+ domain,
6446
+ storefrontAccessToken,
6447
+ query: `
6448
+ mutation cartLinesRemove($cartId: ID!, $lineIds: [ID!]!) {
6449
+ cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {
6450
+ cart {
6451
+ ${CART_FIELDS}
6452
+ }
6453
+ userErrors {
6454
+ field
6455
+ message
6456
+ }
6457
+ }
6458
+ }
6459
+ `,
6460
+ variables: {
6461
+ cartId,
6462
+ lineIds
6463
+ }
6464
+ });
6465
+ if (errors) {
6466
+ throw new Error("Failed to remove Shopify cart lines");
6467
+ }
6468
+ ;
6469
+ const userError = firstUserError((_a = data2 == null ? void 0 : data2.cartLinesRemove) == null ? void 0 : _a.userErrors);
6470
+ if (userError) throw userError;
6471
+ return mapCart((_b = data2 == null ? void 0 : data2.cartLinesRemove) == null ? void 0 : _b.cart);
6472
+ };
6473
+ var cartLinesUpdate = async ({ fetcher, domain, storefrontAccessToken, cartId, lines }) => {
6474
+ var _a, _b;
6475
+ const { data: data2, errors } = await storefrontFetch({
6476
+ fetcher,
6477
+ domain,
6478
+ storefrontAccessToken,
6479
+ query: `
6480
+ mutation cartLinesUpdate($cartId: ID!, $lines: [CartLineUpdateInput!]!) {
6481
+ cartLinesUpdate(cartId: $cartId, lines: $lines) {
6482
+ cart {
6483
+ ${CART_FIELDS}
6484
+ }
6485
+ userErrors {
6486
+ field
6487
+ message
6488
+ }
6489
+ }
6490
+ }
6491
+ `,
6492
+ variables: {
6493
+ cartId,
6494
+ lines
6495
+ }
6496
+ });
6497
+ if (errors) {
6498
+ throw new Error("Failed to update Shopify cart lines");
6499
+ }
6500
+ ;
6501
+ const userError = firstUserError((_a = data2 == null ? void 0 : data2.cartLinesUpdate) == null ? void 0 : _a.userErrors);
6502
+ if (userError) throw userError;
6503
+ return mapCart((_b = data2 == null ? void 0 : data2.cartLinesUpdate) == null ? void 0 : _b.cart);
6504
+ };
6505
+
6506
+ // lib/email.js
6507
+ var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
6508
+ var toCanonicalEmail = (value) => {
6509
+ if (!value || typeof value !== "string") return null;
6510
+ const email = value.trim().toLowerCase();
6511
+ const at = email.lastIndexOf("@");
6512
+ if (at < 1 || at === email.length - 1) return null;
6513
+ let local = email.slice(0, at);
6514
+ const domain = email.slice(at + 1);
6515
+ const plus = local.indexOf("+");
6516
+ if (plus > 0) local = local.slice(0, plus);
6517
+ if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
6518
+ if (!local) return null;
6519
+ return local + "@" + domain;
6520
+ };
6521
+
6522
+ // lib/oauth/index.js
6523
+ var lifetimes = {
6524
+ access: 60 * 60 * 8,
6525
+ // 8 hours
6526
+ authorizationCode: 10 * 60,
6527
+ // 10 minutes
6528
+ code: 15 * 60,
6529
+ // 15 minutes (email OTC)
6530
+ refresh: 30 * 24 * 60 * 60
6531
+ // 30 days
6532
+ };
6533
+ var tokenTypes = {
6534
+ access: "access",
6535
+ oauthState: "oauth.state",
6536
+ pat: "pat",
6537
+ refresh: "refresh"
6538
+ };
6539
+ var scopes = [
6540
+ "profile:read",
6541
+ "profile:write",
6542
+ "organization:read",
6543
+ "organization:write",
6544
+ "campaigns:read",
6545
+ "campaigns:write",
6546
+ "contacts:read",
6547
+ "contacts:write",
6548
+ "workflows:read",
6549
+ "workflows:write",
6550
+ "connections:read",
6551
+ "connections:write",
6552
+ "billing:read",
6553
+ "billing:write",
6554
+ "admin"
6555
+ ];
6556
+ var developer = [
6557
+ "profile:read",
6558
+ "organization:read",
6559
+ "campaigns:read",
6560
+ "campaigns:write",
6561
+ "contacts:read",
6562
+ "contacts:write",
6563
+ "workflows:read",
6564
+ "workflows:write",
6565
+ "connections:read",
6566
+ "connections:write"
6567
+ ];
6568
+ var scopeLabels = {
6569
+ "profile:read": "Read own profile",
6570
+ "profile:write": "Update own profile",
6571
+ "organization:read": "Read organization info",
6572
+ "organization:write": "Manage organization",
6573
+ "campaigns:read": "Read campaigns",
6574
+ "campaigns:write": "Manage campaigns",
6575
+ "contacts:read": "Read contacts",
6576
+ "contacts:write": "Manage contacts",
6577
+ "workflows:read": "Read workflows",
6578
+ "workflows:write": "Manage workflows",
6579
+ "connections:read": "Read integrations",
6580
+ "connections:write": "Manage integrations",
6581
+ "billing:read": "Read billing",
6582
+ "billing:write": "Manage billing",
6583
+ admin: "Admin access"
6584
+ };
6585
+ var toOption = (scope) => ({
6586
+ key: scopeLabels[scope] || scope,
6587
+ value: scope
6588
+ });
6589
+ var developerOptions = developer.map(toOption);
6590
+ var scopeOptions = scopes.map(toOption);
6591
+ var hashToken = (raw) => hash(raw, process.env.HMAC_OAUTH_TOKEN_KEY);
6592
+
6593
+ // lib/sanitize.js
6594
+ var import_disposable_email_domains = __toESM(require("disposable-email-domains/index.js"), 1);
6595
+ var disposableBlacklist = new Set(import_disposable_email_domains.default.map((d) => d.toLowerCase()));
6596
+ var sanitizeDomain = (value, pattern) => {
6597
+ if (!value) return value;
6598
+ const cleaned = value.trim().toLowerCase().replace(/^https?:\/\//i, "").replace(/\/+$/, "");
6599
+ if (pattern) {
6600
+ const match = cleaned.match(pattern);
6601
+ return match ? match[0] : cleaned;
6602
+ }
6603
+ return cleaned;
6604
+ };
6605
+
6606
+ // lib/slugify.js
6607
+ var import_slugify = __toESM(require("slugify"), 1);
6608
+ var slugify = (value, nochars = false) => {
6609
+ const remove = nochars ? /[-?*+~.()'"!:@#^_{}\[\];,/\\]/g : /[?*+~.()'"!:@#^_{}\[\];,/\\]/g;
6610
+ const replacement = nochars ? "" : "-";
6611
+ return (0, import_slugify.default)(
6612
+ value,
6613
+ {
6614
+ remove,
6615
+ replacement,
6616
+ lower: true,
6617
+ trim: true
6618
+ }
6619
+ );
6620
+ };
6621
+
6622
+ // lib/connections/manifests/shopify.js
6623
+ var client = Object.freeze({
6624
+ admin: admin_exports,
6625
+ billing: billing_exports,
6626
+ oauth: oauth_exports,
6627
+ partner: partner_exports,
6628
+ storefront: storefront_exports
6629
+ });
6630
+ var toLine = ({
6631
+ price,
6632
+ product_id: productId,
6633
+ quantity,
6634
+ title,
6635
+ variant_id: variantId,
6636
+ variant_title: variantTitle
6637
+ }) => ({
6638
+ price: parseFloat(price) || 0,
6639
+ productId: productId ? "gid://shopify/Product/" + productId : null,
6640
+ quantity: quantity || 1,
6641
+ title: title || null,
6642
+ variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
6643
+ variantTitle: variantTitle || null
6644
+ });
6645
+ var attributeLineItems = (lineItems = []) => lineItems.reduce(
6646
+ (acc, item) => {
6647
+ const attrs = (item.properties || []).reduce(
6648
+ (map, { name, value }) => {
6649
+ map[name] = value;
6650
+ return map;
6651
+ },
6652
+ {}
6653
+ );
6654
+ if (!attrs["_drwbrdg_ca"]) return acc;
6655
+ if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
6656
+ const line = toLine(item);
6657
+ acc.attributedGross += line.price * line.quantity;
6658
+ acc.attributedLines.push(line);
6659
+ return acc;
6660
+ },
6661
+ { attrMap: {}, attributedGross: 0, attributedLines: [] }
6662
+ );
6663
+ var generateDiscountCode = (0, import_nanoid.customAlphabet)("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
6664
+ var blockedReason = (discount) => {
6665
+ var _a;
6666
+ if ((discount == null ? void 0 : discount.status) === "EXPIRED") return "This discount has expired.";
6667
+ const buyers = (_a = discount == null ? void 0 : discount.context) == null ? void 0 : _a.__typename;
6668
+ if (buyers && buyers !== "DiscountBuyerSelectionAll") {
6669
+ 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.";
6670
+ }
6671
+ ;
6672
+ if (typeof (discount == null ? void 0 : discount.usageLimit) === "number" && discount.usageLimit > 0 && ((discount == null ? void 0 : discount.asyncUsageCount) || 0) >= discount.usageLimit) {
6673
+ return "This discount has reached its total usage limit.";
6674
+ }
6675
+ ;
6676
+ return null;
6677
+ };
6678
+ var discountWarning = (discount) => {
6679
+ if ((discount == null ? void 0 : discount.status) === "SCHEDULED") {
6680
+ return "This discount hasn't started yet, so codes issued before it does won't work until then.";
6681
+ }
6682
+ ;
6683
+ if (discount == null ? void 0 : discount.appliesOncePerCustomer) return "Each customer can use this discount only once.";
6684
+ return null;
6685
+ };
6686
+ var ORDER_EVENT_HANDLE = slugify("drawbridge-orders");
6687
+ var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
6688
+ var OAUTH_ERROR_SOURCE = "oauth";
6689
+ var BILLING_ERROR_SOURCE = "billing";
6690
+ var BILLING_ERROR_MESSAGE = "Order billing isn't set up for this store \u2014 reselect and approve the plan from the Shopify connection page.";
6691
+ var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
6692
+ var inbound = {
6693
+ headers: {
6694
+ event: "x-shopify-topic",
6695
+ id: "x-shopify-webhook-id",
6696
+ shop: "x-shopify-shop-domain",
6697
+ signature: "x-shopify-hmac-sha256"
6698
+ },
6699
+ signature: {
6700
+ algorithm: "sha256",
6701
+ encoding: "base64",
6702
+ secret: "SHOPIFY_API_SECRET"
6703
+ }
6704
+ };
6705
+ var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
4968
6706
  "customers/data_request",
4969
6707
  "customers/redact",
4970
6708
  "shop/redact"
4971
6709
  ]);
6710
+ var refusal = (message, status) => Object.assign(new Error(message), { status });
6711
+ var LINK_TOKEN_TTL_MS = 30 * 60 * 1e3;
6712
+ var CONNECTABLE_STATUSES = ["active", "unsubscribed"];
6713
+ var merchantOrganizations = ({ read, user }) => read.aggregate({
6714
+ collection: "organization",
6715
+ pipeline: [
6716
+ // A member qualifies only at `manage`; an owner always qualifies.
6717
+ {
6718
+ $lookup: {
6719
+ as: "membership",
6720
+ from: "member",
6721
+ let: { organization: "$id" },
6722
+ pipeline: [
6723
+ {
6724
+ $match: {
6725
+ $expr: { $eq: ["$organization", "$$organization"] },
6726
+ "capabilities.connections": "manage",
6727
+ status: "accepted",
6728
+ user
6729
+ }
6730
+ },
6731
+ { $limit: 1 },
6732
+ { $project: { _id: 0, organization: 1 } }
6733
+ ]
6734
+ }
6735
+ },
6736
+ {
6737
+ $match: {
6738
+ status: { $ne: "canceled" },
6739
+ $or: [{ owner: user }, { "membership.0": { $exists: true } }]
6740
+ }
6741
+ },
6742
+ // `organization.subscription` is a subscription RECORD ID — resolved here so
6743
+ // the list can read the real plan and conversion rate. Without it every org
6744
+ // rendered as free tier.
6745
+ { $lookup: { as: "subscription", foreignField: "id", from: "subscription", localField: "subscription" } },
6746
+ { $unwind: { path: "$subscription", preserveNullAndEmptyArrays: true } },
6747
+ {
6748
+ $lookup: {
6749
+ as: "connection",
6750
+ foreignField: "organization",
6751
+ from: "connection",
6752
+ localField: "id",
6753
+ pipeline: [
6754
+ { $match: { slug: "shopify" } },
6755
+ { $limit: 1 },
6756
+ { $project: { _id: 0, id: 1, shop: 1, status: 1 } }
6757
+ ]
6758
+ }
6759
+ },
6760
+ { $unwind: { path: "$connection", preserveNullAndEmptyArrays: true } },
6761
+ { $project: { _id: 0, billingStatus: "$status", connection: 1, id: 1, name: "$title", subscription: 1 } },
6762
+ { $sort: { name: 1 } }
6763
+ ]
6764
+ });
6765
+ var storePlan = async ({ record, shopify }) => {
6766
+ var _a;
6767
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
6768
+ if (!(settings == null ? void 0 : settings.accessToken)) return { active: false, name: null };
6769
+ try {
6770
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
6771
+ adminAccessToken: settings.accessToken,
6772
+ domain: record.shop
6773
+ });
6774
+ const active = (subscriptions || []).length > 0;
6775
+ const metered = active && subscriptions.some((subscription) => subscription.metered === true) ? true : null;
6776
+ return { active, metered, name: active ? ((_a = subscriptions[0]) == null ? void 0 : _a.name) || null : null };
6777
+ } catch (_) {
6778
+ return { active: false, name: null, unavailable: true };
6779
+ }
6780
+ };
6781
+ var releaseApprovals = async ({ context, read, shopify }) => {
6782
+ var _a;
6783
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
6784
+ if (!shop) throw refusal("shop is required", 400);
6785
+ const record = await read.get({ collection: "shop", query: { shop } });
6786
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
6787
+ if (!(settings == null ? void 0 : settings.accessToken)) throw refusal("Store is not installed", 409);
6788
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
6789
+ adminAccessToken: settings.accessToken,
6790
+ domain: shop
6791
+ });
6792
+ for (const subscription of subscriptions || []) {
6793
+ const data2 = await shopify.admin.adminFetch({
6794
+ adminAccessToken: settings.accessToken,
6795
+ domain: shop,
6796
+ query: "mutation appSubscriptionCancel( $id : ID! ) { appSubscriptionCancel( id : $id ) { appSubscription { id status } userErrors { field message } } }",
6797
+ variables: { id: subscription.id }
6798
+ });
6799
+ const [userError] = ((_a = data2 == null ? void 0 : data2.appSubscriptionCancel) == null ? void 0 : _a.userErrors) || [];
6800
+ if (userError) throw refusal(userError.message, 422);
6801
+ }
6802
+ return {
6803
+ message: "Released " + (subscriptions || []).length + " approval(s).",
6804
+ request: { shop },
6805
+ result: { ok: true }
6806
+ };
6807
+ };
6808
+ var LEDGER_WINDOW_MS = 30 * 24 * 60 * 60 * 1e3;
6809
+ var meterVerdict = async ({ adminAccessToken, ledgerFloor, partner, shop, shopId, shopify }) => {
6810
+ var _a;
6811
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({ adminAccessToken, domain: shop });
6812
+ let metered = (_a = subscriptions.find((subscription) => subscription.usageLineItemId)) == null ? void 0 : _a.usageLineItemId;
6813
+ if (!((partner == null ? void 0 : partner.partnerToken) && (partner == null ? void 0 : partner.partnerOrgId) && (partner == null ? void 0 : partner.partnerAppId) && shopId)) {
6814
+ return { boundaries: [], ledger: false, metered };
6815
+ }
6816
+ const accruals = await shopify.partner.getUsageChargeEvents({
6817
+ appId: "gid://shopify/App/" + partner.partnerAppId,
6818
+ first: 10,
6819
+ occurredAtMin: ledgerFloor.toISOString(),
6820
+ organizationId: partner.partnerOrgId,
6821
+ partnerToken: partner.partnerToken,
6822
+ shopId: "gid://shopify/Shop/" + shopId
6823
+ });
6824
+ const boundaries = (accruals || []).filter((event) => event.occurredAt).sort((a, b) => new Date(a.occurredAt) - new Date(b.occurredAt));
6825
+ const accrued = [...boundaries].reverse().find((event) => Number(event.usageQuantity) > 0);
6826
+ if (accrued) metered = String(accrued.chargeId || accrued.id);
6827
+ return { boundaries, ledger: true, metered };
6828
+ };
6829
+ var toVariant = (edge) => {
6830
+ var _a, _b, _c, _d;
6831
+ return {
6832
+ availableForSale: edge.node.availableForSale || false,
6833
+ currency: ((_a = edge.node.price) == null ? void 0 : _a.currencyCode) || null,
6834
+ id: edge.node.id,
6835
+ image: ((_b = edge.node.image) == null ? void 0 : _b.url) || null,
6836
+ price: parseFloat((_c = edge.node.price) == null ? void 0 : _c.amount) || null,
6837
+ requiresShipping: edge.node.requiresShipping || false,
6838
+ sale: parseFloat((_d = edge.node.compareAtPrice) == null ? void 0 : _d.amount) || null,
6839
+ title: edge.node.title !== "Default Title" ? edge.node.title : null
6840
+ };
6841
+ };
6842
+ var applyOutOfStock = async ({ domain, shopify, storefrontAccessToken, variants }) => {
6843
+ try {
6844
+ const outOfStock = new Set(await shopify.storefront.probeVariantsOutOfStock({
6845
+ domain,
6846
+ storefrontAccessToken,
6847
+ variantIds: variants.map((variant) => variant.id)
6848
+ }));
6849
+ return variants.map((variant) => ({
6850
+ ...variant,
6851
+ availableForSale: variant.availableForSale && !outOfStock.has(variant.id)
6852
+ }));
6853
+ } catch (_) {
6854
+ return variants;
6855
+ }
6856
+ };
6857
+ var sendFeedback = async ({ adminToken, connection: connection2, messages, productId, shopify, state }) => {
6858
+ try {
6859
+ await shopify.admin.sendProductResourceFeedback({
6860
+ adminAccessToken: await adminToken(),
6861
+ domain: connection2.shop,
6862
+ messages,
6863
+ productId,
6864
+ state
6865
+ });
6866
+ return null;
6867
+ } catch (error) {
6868
+ return error;
6869
+ }
6870
+ };
6871
+ var resolveProduct = async ({ connection: connection2, context, read }) => {
6872
+ const byId = (context == null ? void 0 : context.product) ? await read.get({ collection: "product", query: { id: context.product } }) : null;
6873
+ const row2 = byId || ((context == null ? void 0 : context.providerId) && ((context == null ? void 0 : context.shop) || (connection2 == null ? void 0 : connection2.shop)) ? await read.get({
6874
+ collection: "product",
6875
+ query: {
6876
+ "provider.id": context.providerId,
6877
+ "provider.slug": "shopify",
6878
+ "source.domain": context.shop || connection2.shop
6879
+ }
6880
+ }) : null);
6881
+ return row2;
6882
+ };
6883
+ var UNAVAILABLE_FEEDBACK = "Drawbridge can't display this product. Check it is active and available in the United States.";
6884
+ var NOT_FOUND = "Shopify product not found";
6885
+ var syncProduct = async ({ adminToken, connection: connection2, context, read, settings, shopify }) => {
6886
+ var _a, _b, _c;
6887
+ const row2 = await resolveProduct({ connection: connection2, context, read });
6888
+ if (!row2) return { message: "No product row to sync.", request: { product: (context == null ? void 0 : context.product) || null }, skipped: true };
6889
+ const domain = connection2.shop;
6890
+ const providerId = (_a = row2.provider) == null ? void 0 : _a.id;
6891
+ const request2 = { product: row2.id, providerId: providerId || null, shop: domain };
6892
+ let product;
6893
+ try {
6894
+ product = await shopify.storefront.getProduct({
6895
+ domain,
6896
+ productId: providerId,
6897
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
6898
+ });
6899
+ } catch (error) {
6900
+ if (error.message !== NOT_FOUND) throw error;
6901
+ const failed2 = await sendFeedback({
6902
+ adminToken,
6903
+ connection: connection2,
6904
+ messages: [UNAVAILABLE_FEEDBACK],
6905
+ productId: providerId,
6906
+ shopify,
6907
+ state: "REQUIRES_ACTION"
6908
+ });
6909
+ return {
6910
+ failed: failed2 ? [failed2.message] : void 0,
6911
+ message: "Storefront cannot see this product \u2014 deactivated.",
6912
+ request: request2,
6913
+ result: { status: "inactive" },
6914
+ writes: [
6915
+ {
6916
+ collection: "product",
6917
+ data: { $set: { status: "inactive" } },
6918
+ operation: "update",
6919
+ query: { id: row2.id }
6920
+ },
6921
+ {
6922
+ collection: "advertisement",
6923
+ data: { $set: { status: "drafted" } },
6924
+ multiple: true,
6925
+ operation: "update",
6926
+ query: { product: row2.id }
6927
+ }
6928
+ ]
6929
+ };
6930
+ }
6931
+ const variants = await applyOutOfStock({
6932
+ domain,
6933
+ shopify,
6934
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken,
6935
+ variants: (((_b = product == null ? void 0 : product.variants) == null ? void 0 : _b.edges) || []).map(toVariant)
6936
+ });
6937
+ const failed = await sendFeedback({
6938
+ adminToken,
6939
+ connection: connection2,
6940
+ messages: [],
6941
+ productId: providerId,
6942
+ shopify,
6943
+ state: "ACCEPTED"
6944
+ });
6945
+ return {
6946
+ // EVERYTHING PAST THE FIRST PAGE, filled in silently. The first page is
6947
+ // written above; a product with thousands of variants becomes N short
6948
+ // sequential jobs rather than one long loop that risks a BullMQ stall.
6949
+ enqueues: [{
6950
+ data: { operation: "variants", product: row2.id },
6951
+ name: "sync",
6952
+ options: { jobId: "product.shopify.variants." + row2.id + "." + Date.now() },
6953
+ queue: "product.shopify.variants"
6954
+ }],
6955
+ failed: failed ? [failed.message] : void 0,
6956
+ message: "Synced " + (product.title || "product") + ".",
6957
+ request: request2,
6958
+ result: { status: "active", variants: variants.length },
6959
+ writes: [{
6960
+ collection: "product",
6961
+ data: {
6962
+ $set: {
6963
+ description: product.description || null,
6964
+ image: ((_c = product.featuredImage) == null ? void 0 : _c.url) || null,
6965
+ // A successful sync PROVES channel visibility, which reverses the
6966
+ // deactivation above. Ads stay drafted.
6967
+ status: "active",
6968
+ title: product.title || null,
6969
+ type: product.productType || null,
6970
+ url: domain && product.handle ? "https://" + domain + "/products/" + product.handle : null,
6971
+ variants
6972
+ }
6973
+ },
6974
+ operation: "update",
6975
+ query: { id: row2.id }
6976
+ }]
6977
+ };
6978
+ };
6979
+ var syncVariants = async ({ connection: connection2, context, read, settings, shopify }) => {
6980
+ var _a, _b, _c;
6981
+ const row2 = await resolveProduct({ connection: connection2, context, read });
6982
+ if (!row2) return { message: "No product row to paginate.", request: { product: (context == null ? void 0 : context.product) || null }, skipped: true };
6983
+ const cursor = (context == null ? void 0 : context.cursor) || null;
6984
+ const request2 = { cursor, product: row2.id };
6985
+ let page2;
6986
+ try {
6987
+ page2 = await shopify.storefront.getProductVariantsPage({
6988
+ cursor,
6989
+ domain: connection2.shop,
6990
+ productId: (_a = row2.provider) == null ? void 0 : _a.id,
6991
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
6992
+ });
6993
+ } catch (error) {
6994
+ if (error.message !== NOT_FOUND) throw error;
6995
+ return { message: "Storefront lost this product mid-pagination \u2014 stopping.", request: request2, skipped: true };
6996
+ }
6997
+ const variants = await applyOutOfStock({
6998
+ domain: connection2.shop,
6999
+ shopify,
7000
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken,
7001
+ variants: (page2.edges || []).map(toVariant)
7002
+ });
7003
+ return {
7004
+ ...((_b = page2.pageInfo) == null ? void 0 : _b.hasNextPage) && { enqueues: [{
7005
+ data: { cursor: page2.pageInfo.endCursor, operation: "variants", product: row2.id },
7006
+ name: "page",
7007
+ options: { jobId: "product.shopify.variants." + row2.id + "." + Date.now() },
7008
+ queue: "product.shopify.variants"
7009
+ }] },
7010
+ message: variants.length + " variant(s) on this page.",
7011
+ request: request2,
7012
+ result: { hasNextPage: Boolean((_c = page2.pageInfo) == null ? void 0 : _c.hasNextPage), variants: variants.length },
7013
+ writes: [{
7014
+ collection: "product",
7015
+ data: cursor ? { $push: { variants: { $each: variants } } } : { $set: { variants } },
7016
+ operation: "update",
7017
+ query: { id: row2.id }
7018
+ }]
7019
+ };
7020
+ };
4972
7021
  var shopify_default2 = {
4973
7022
  // THE WORDS ON THE BUTTONS. `listing` was `content.redirect.title`, which put
4974
7023
  // a BUTTON LABEL inside the copy object next to a url — the title and the
@@ -5155,8 +7204,8 @@ var shopify_default2 = {
5155
7204
  // string; this answers what is missing from it.
5156
7205
  //
5157
7206
  // `shopify` is injected for the same reason it is everywhere else — this
5158
- // package cannot import @drawbridge/shopify, which depends on it.
5159
- scopes: ({ scope }, { shopify } = {}) => ({ result: { missing: scope ? shopify.oauth.missingScopes(scope) : null } }),
7207
+ // client is imported here and defaulted, never wired in by a caller.
7208
+ scopes: ({ scope }, { shopify = client } = {}) => ({ result: { missing: scope ? shopify.oauth.missingScopes(scope) : null } }),
5160
7209
  // Shopify's install grant is exchanged inside its own app flow, not
5161
7210
  // through the shared OAuth runner.
5162
7211
  token: false
@@ -5170,17 +7219,53 @@ var shopify_default2 = {
5170
7219
  // can reference another), `dispatch` (the caller's own coordinator table,
5171
7220
  // for the hooks that are dispatches).
5172
7221
  commerce: {
5173
- // NOT YET. The Checkout Kit cart path is `api/route/subdomain.js`, six direct
5174
- // calls into `@drawbridge/shopify/storefront` that write nothing — which is
5175
- // exactly why it never became a hook: a hook is reached to have its effects
5176
- // performed, and this one has none to perform. It moves here when the vendor
5177
- // client moves into the manifest and `subdomain.js` stops importing the
5178
- // package directly.
5179
- cart: false,
7222
+ // THE CHECKOUT KIT CART. Six operations that were six direct calls into
7223
+ // the storefront client from api/route/subdomain.js.
7224
+ //
7225
+ // IT WRITES NOTHING, which is exactly why it was the last surface to
7226
+ // become a hook a hook is usually reached to have its effects performed
7227
+ // and this one has none. That reasoning was wrong: a hook is also the one
7228
+ // place a vendor's client is allowed to be called from, and leaving the
7229
+ // cart out meant a public route importing a vendor SDK directly.
7230
+ //
7231
+ // ONE HOOK, OPERATION IN THE CONTEXT, the same shape `inbound.process`
7232
+ // uses for its topic table. Six slots would be six names in the closed
7233
+ // vocabulary for one question — what does this shopper's cart look like
7234
+ // now — asked six ways.
7235
+ //
7236
+ // A USER ERROR IS A 400 AND THE SHOPPER'S OWN WORDS. Shopify's cart
7237
+ // mutations answer "that variant is sold out" as a userError rather than a
7238
+ // transport failure, and the route it replaced already told the two apart.
7239
+ // runHook carries `status` off a thrown error, so it survives to the
7240
+ // caller; the rest of a thrown error's shape does not.
7241
+ cart: async ({ clientId, clientSecret, context, settings }, { fetcher, shopify = client } = {}) => {
7242
+ const { cartId, lineIds, lines, operation } = context || {};
7243
+ const { domain, storefrontAccessToken } = settings || {};
7244
+ if (operation === "checkout") {
7245
+ const token = await shopify.storefront.createCheckoutToken({ clientId, clientSecret, fetcher });
7246
+ return { message: "Checkout token minted.", result: { token } };
7247
+ }
7248
+ const storefront = { domain, fetcher, storefrontAccessToken };
7249
+ try {
7250
+ const cart = await ({
7251
+ create: () => shopify.storefront.cartCreate({ ...storefront, lines }),
7252
+ get: () => shopify.storefront.cartGet({ ...storefront, cartId }),
7253
+ linesAdd: () => shopify.storefront.cartLinesAdd({ ...storefront, cartId, lines }),
7254
+ linesRemove: () => shopify.storefront.cartLinesRemove({ ...storefront, cartId, lineIds }),
7255
+ linesUpdate: () => shopify.storefront.cartLinesUpdate({ ...storefront, cartId, lines })
7256
+ }[operation] || (() => {
7257
+ throw Object.assign(new Error("Unknown cart operation: " + operation), { status: 400 });
7258
+ }))();
7259
+ return { message: "Cart " + operation + ".", request: { cartId: cartId || null, operation }, result: cart };
7260
+ } catch (error) {
7261
+ if (error == null ? void 0 : error.userError) throw Object.assign(error, { status: 400 });
7262
+ throw error;
7263
+ }
7264
+ },
5180
7265
  // MINT A DISCOUNT CODE against the merchant's chosen discount, mapped to
5181
7266
  // one lead — which is what lets an order that redeems it be attributed
5182
7267
  // back.
5183
- code: async ({ connection: connection2, context, step }, { adminToken, shopify } = {}) => {
7268
+ code: async ({ connection: connection2, context, step }, { adminToken, shopify = client } = {}) => {
5184
7269
  var _a;
5185
7270
  const discount = (_a = step.settings) == null ? void 0 : _a.discount;
5186
7271
  const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
@@ -5226,7 +7311,7 @@ var shopify_default2 = {
5226
7311
  // customer at the store is a support ticket: the context may already
5227
7312
  // carry the id from an earlier step, the lead may already be linked from
5228
7313
  // an earlier run, and Shopify's own get-or-create settles the rest.
5229
- customer: async ({ connection: connection2, context }, { adminToken, read, shopify } = {}) => {
7314
+ customer: async ({ connection: connection2, context }, { adminToken, read, shopify = client } = {}) => {
5230
7315
  const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
5231
7316
  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 };
5232
7317
  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 };
@@ -5276,6 +7361,30 @@ var shopify_default2 = {
5276
7361
  }]
5277
7362
  };
5278
7363
  },
7364
+ // HOW MANY ARE LEFT. Read at the moment a campaign's product list is
7365
+ // rendered rather than stored on the product, because stock is the one
7366
+ // product fact that is stale the instant it is written down.
7367
+ //
7368
+ // SUMMED HERE, not by the caller. Shopify answers per variant and every
7369
+ // caller wanted the total; the one that existed summed it inline, and
7370
+ // summing `Object.values()` over the raw map is how a cache wrapper's own
7371
+ // bookkeeping key got counted as a quantity.
7372
+ inventory: async ({ connection: connection2, context }, { adminToken, shopify = client } = {}) => {
7373
+ const productId = context == null ? void 0 : context.product;
7374
+ const request2 = { product: productId || null, shop: connection2.shop };
7375
+ if (!productId) return { message: "No product id \u2014 nothing to count.", request: request2, result: { total: null }, skipped: true };
7376
+ const adminAccessToken = await adminToken();
7377
+ const byVariant = await shopify.admin.getProductInventory({
7378
+ adminAccessToken,
7379
+ domain: connection2.shop,
7380
+ productId
7381
+ });
7382
+ return {
7383
+ message: "Inventory read.",
7384
+ request: request2,
7385
+ result: { total: Object.values(byVariant || {}).reduce((sum, quantity) => sum + quantity, 0) }
7386
+ };
7387
+ },
5279
7388
  // AN ORDER ARRIVED AT THE STORE. The largest hook in the family, because
5280
7389
  // attribution genuinely is: an order can reach Drawbridge two ways and
5281
7390
  // they bill differently.
@@ -5596,6 +7705,12 @@ var shopify_default2 = {
5596
7705
  orderId: String(orderId),
5597
7706
  rate,
5598
7707
  shopId: connection2.source.id,
7708
+ // WHICH VENDOR IS BEING CHARGED, so the sender does not have
7709
+ // to assume. queue/usage.js named the slug itself and
7710
+ // defaults to it for anything already queued when this
7711
+ // shipped — an app-store vendor billing through its own meter
7712
+ // enqueues the same job with its own slug.
7713
+ slug: connection2.slug,
5599
7714
  // The App Events API returns no event id, so one is generated
5600
7715
  // here — the event handle plus the order id — and sent as the
5601
7716
  // event's `reference`. queue/usage.js stamps the same id onto
@@ -5635,10 +7750,28 @@ var shopify_default2 = {
5635
7750
  //
5636
7751
  // The shell has already refused a missing or inactive Shopify connection,
5637
7752
  // so what is left is the two things only this hook can know are wrong.
5638
- product: async ({ connection: connection2, context, workflow }, { mintId, read } = {}) => {
7753
+ // A PRODUCT, IN THREE MOVES. Nested by operation rather than by three
7754
+ // slots in the closed vocabulary, the same shape inbound.process uses
7755
+ // for its topic table — they are one subject, and a vendor that syncs
7756
+ // products has to answer all three or none.
7757
+ //
7758
+ // record a webhook said a product changed: upsert the row and
7759
+ // queue the pull
7760
+ // sync pull the product from the storefront and write what it
7761
+ // says, including what it says by NOT answering
7762
+ // variants one page of variants, self-chaining
7763
+ //
7764
+ // `sync` and `variants` were 443 lines of drawbridge-sync's
7765
+ // queue/product.js — a shadow implementation of the step this manifest
7766
+ // already declared, importing three of the vendor's client modules from
7767
+ // a worker file.
7768
+ product: async ({ connection: connection2, context, settings, workflow }, { adminToken, mintId, read, shopify = client } = {}) => {
7769
+ const operation = (context == null ? void 0 : context.operation) || "record";
7770
+ if (operation === "sync") return syncProduct({ adminToken, connection: connection2, context, read, settings, shopify });
7771
+ if (operation === "variants") return syncVariants({ connection: connection2, context, read, settings, shopify });
5639
7772
  const request2 = {
5640
7773
  numericId: (context == null ? void 0 : context.id) || null,
5641
- organizationId: workflow.organization,
7774
+ organizationId: (workflow == null ? void 0 : workflow.organization) || null,
5642
7775
  title: (context == null ? void 0 : context.title) || null
5643
7776
  };
5644
7777
  if (!(context == null ? void 0 : context.id)) return { message: "Skipped \u2014 product webhook payload had no id.", request: request2, response: { skipped: true }, skipped: true };
@@ -5688,9 +7821,612 @@ var shopify_default2 = {
5688
7821
  }
5689
7822
  },
5690
7823
  contacts: { remove: false, sync: false },
5691
- // The embedded-app surface. Only a vendor whose merchants arrive from its
5692
- // own app store has one.
5693
- install: false,
7824
+ // THE EMBEDDED-APP SURFACE. Only a vendor whose merchants arrive from its
7825
+ // own app store has one, and these thirteen slots are the thirteen routes
7826
+ // that used to live in api/route/shopify-embedded.js.
7827
+ //
7828
+ // A HOOK DESCRIBES ITS WRITES and the shell performs them, so none of these
7829
+ // holds a controller — `read` is the controller's read methods and nothing
7830
+ // else. Where one REFUSES it throws with a status, and the route answers
7831
+ // what it said. The helpers they share are above the manifest.
7832
+ install: {
7833
+ account: {
7834
+ // ESTABLISH THE DURABLE MERCHANT-TO-STORE LINK. The breakout
7835
+ // authenticates the merchant once, top-level, and stashes their user
7836
+ // token in `install.token.save`; App Bridge has already proven shop
7837
+ // control by the time this runs.
7838
+ //
7839
+ // THE STASHED TOKEN IS THE TRUST ANCHOR, not merely any valid user
7840
+ // token: the presented one must BE this shop's one-shot handoff token,
7841
+ // unexpired, and an access or pat record — a refresh or oauth-state
7842
+ // token that happens to resolve to a user must not qualify, which is
7843
+ // the rule a session is held to in drawbridge-api's middleware.
7844
+ link: async ({ context }, { read } = {}) => {
7845
+ var _a;
7846
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
7847
+ const token = context == null ? void 0 : context.token;
7848
+ if (!shop || !token) throw refusal("shop and token are required", 400);
7849
+ const now = /* @__PURE__ */ new Date();
7850
+ const record = await read.get({ collection: "shop", query: { shop } });
7851
+ const stashed = (record == null ? void 0 : record.linkToken) ? (_a = decrypt(record.linkToken)) == null ? void 0 : _a.token : null;
7852
+ const expired = !(record == null ? void 0 : record.linkTokenExpiresAt) || new Date(record.linkTokenExpiresAt) <= now;
7853
+ if (!stashed || expired || stashed !== token) throw refusal("Invalid or expired link token", 401);
7854
+ const granted = await read.get({
7855
+ collection: "token",
7856
+ query: {
7857
+ revoked: false,
7858
+ tokenHash: hashToken(token),
7859
+ type: { $in: [tokenTypes.access, tokenTypes.pat] }
7860
+ }
7861
+ });
7862
+ if (!(granted == null ? void 0 : granted.user) || granted.expiresAt && new Date(granted.expiresAt) <= now) {
7863
+ throw refusal("Invalid or expired link token", 401);
7864
+ }
7865
+ const switching = Boolean(record == null ? void 0 : record.user) && record.user !== granted.user;
7866
+ const connections2 = switching ? await read.aggregate({
7867
+ collection: "connection",
7868
+ pipeline: [
7869
+ { $match: { shop, slug: "shopify" } },
7870
+ { $project: { _id: 0, id: 1 } }
7871
+ ]
7872
+ }) : [];
7873
+ return {
7874
+ message: switching ? "Linked to a different Drawbridge account." : "Linked.",
7875
+ request: { shop },
7876
+ result: { connected: true, switched: switching },
7877
+ // ALL OR NONE. A half-done switch is a store linked to the new
7878
+ // account while the old account's connections still serve from it.
7879
+ transaction: true,
7880
+ writes: [
7881
+ ...(connections2 || []).map((connection2) => ({
7882
+ collection: "connection",
7883
+ operation: "delete",
7884
+ query: { id: connection2.id }
7885
+ })),
7886
+ {
7887
+ collection: "shop",
7888
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null, user: granted.user } },
7889
+ operation: "update",
7890
+ query: { shop }
7891
+ }
7892
+ ]
7893
+ };
7894
+ },
7895
+ // DISCONNECT THE ACCOUNT FROM THE STORE. Every org connection goes and
7896
+ // the durable link clears; the offline token and the shop record stay,
7897
+ // because the app is still installed and the merchant may link a
7898
+ // different account next.
7899
+ unlink: async ({ context }, { read } = {}) => {
7900
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
7901
+ if (!shop) throw refusal("shop is required", 400);
7902
+ const connections2 = await read.aggregate({
7903
+ collection: "connection",
7904
+ pipeline: [
7905
+ { $match: { shop, slug: "shopify" } },
7906
+ { $project: { _id: 0, id: 1 } }
7907
+ ]
7908
+ });
7909
+ return {
7910
+ message: "Unlinked " + (connections2 || []).length + " connection(s).",
7911
+ request: { shop },
7912
+ result: { ok: true },
7913
+ transaction: true,
7914
+ writes: [
7915
+ ...(connections2 || []).map((connection2) => ({
7916
+ collection: "connection",
7917
+ operation: "delete",
7918
+ query: { id: connection2.id }
7919
+ })),
7920
+ {
7921
+ collection: "shop",
7922
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null, user: null } },
7923
+ operation: "update",
7924
+ query: { shop }
7925
+ }
7926
+ ]
7927
+ };
7928
+ }
7929
+ },
7930
+ organizations: {
7931
+ // BIND ONE ORGANIZATION TO THIS STORE. The longest slot here, and every
7932
+ // gate in it came from a line in the route it replaces.
7933
+ add: async ({ context }, { currencies: currencies2, mintId, read, shopify = client } = {}) => {
7934
+ var _a, _b;
7935
+ const organization2 = context == null ? void 0 : context.organization;
7936
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
7937
+ if (!shop) throw refusal("shop is required", 400);
7938
+ if (!organization2) throw refusal("organization is required", 400);
7939
+ const record = await read.get({ collection: "shop", query: { shop } });
7940
+ if (!(record == null ? void 0 : record.user)) throw refusal("Account is not connected for this store", 409);
7941
+ const owned = await merchantOrganizations({ read, user: record.user });
7942
+ const org = (owned || []).find((entry) => entry.id === organization2);
7943
+ if (!org) throw refusal("No access to this organization", 403);
7944
+ if (!CONNECTABLE_STATUSES.includes(org.billingStatus)) {
7945
+ throw refusal("This organization can't accept connections right now \u2014 check its billing status in the dashboard", 403);
7946
+ }
7947
+ if (org.connection && org.connection.shop !== shop) {
7948
+ throw refusal("This organization is already connected to another Shopify store", 409);
7949
+ }
7950
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
7951
+ if (!(settings == null ? void 0 : settings.accessToken)) {
7952
+ throw refusal("Store is not installed \u2014 open the app in the Shopify admin first", 409);
7953
+ }
7954
+ const plan = await storePlan({ record, shopify });
7955
+ if (plan.unavailable) throw refusal("Couldn't verify the store's plan \u2014 try again shortly", 502);
7956
+ if (!plan.active) throw refusal("Approve a plan before connecting organizations", 402);
7957
+ let storefront = null;
7958
+ if (!record.storefront) {
7959
+ try {
7960
+ const minted2 = await shopify.oauth.createStorefrontToken({
7961
+ adminAccessToken: settings.accessToken,
7962
+ shop
7963
+ });
7964
+ if (minted2) storefront = encrypt({ token: minted2 });
7965
+ } catch (_) {
7966
+ }
7967
+ }
7968
+ let currency = (record == null ? void 0 : record.currency) || null;
7969
+ let source = (record == null ? void 0 : record.source) || null;
7970
+ try {
7971
+ const shopData = await shopify.oauth.getShop({ adminAccessToken: settings.accessToken, shop });
7972
+ if (shopData) {
7973
+ currency = String(shopData.currency || "").toLowerCase() || null;
7974
+ source = { domain: shopData.myshopifyDomain, id: String(shopData.id), label: shopData.name };
7975
+ }
7976
+ } catch (_) {
7977
+ }
7978
+ if (currency && currencies2 && !currencies2.includes(currency)) {
7979
+ throw refusal("This store settles in a currency we can't bill yet. Connect a store with a supported settlement currency.", 422);
7980
+ }
7981
+ const minted = ((_a = org.connection) == null ? void 0 : _a.id) ? null : mintId();
7982
+ const connectionId = ((_b = org.connection) == null ? void 0 : _b.id) || minted.id;
7983
+ return {
7984
+ message: "Connected " + org.name + " to " + shop + ".",
7985
+ request: { organization: organization2, shop },
7986
+ result: { ok: true },
7987
+ transaction: true,
7988
+ writes: [
7989
+ ...storefront ? [{
7990
+ collection: "shop",
7991
+ data: { $set: { storefront } },
7992
+ operation: "update",
7993
+ query: { shop }
7994
+ }] : [],
7995
+ {
7996
+ collection: "connection",
7997
+ data: {
7998
+ $set: {
7999
+ currency,
8000
+ errors: [],
8001
+ // The token of record lives on the shared `shop` row; this
8002
+ // is the pointer that satisfies the required `settings`
8003
+ // string, and `auth.install.shared` declares how to read it.
8004
+ settings: encrypt({ ref: "shop", shop }),
8005
+ shop,
8006
+ status: "pending",
8007
+ ...source && { source }
8008
+ },
8009
+ $setOnInsert: {
8010
+ ...minted && { _id: minted._id, id: minted.id },
8011
+ feature: "organization:connection:shopify",
8012
+ organization: organization2,
8013
+ slug: "shopify"
8014
+ }
8015
+ },
8016
+ operation: "update",
8017
+ options: { upsert: true },
8018
+ query: { organization: organization2, slug: "shopify" }
8019
+ },
8020
+ {
8021
+ collection: "organization",
8022
+ data: {
8023
+ // $addToSet UNCONDITIONALLY. The route this replaces only
8024
+ // registered the refs when the upsert INSERTED, which meant an
8025
+ // org whose refs had drifted stayed drifted through every
8026
+ // re-link. Adding a member that is already there is a no-op,
8027
+ // so doing it every time costs nothing and repairs the drift.
8028
+ $addToSet: {
8029
+ "connections.groups": "ecommerce",
8030
+ "connections.ids": connectionId,
8031
+ "connections.keys": "shopify"
8032
+ },
8033
+ $set: { billingProvider: "shopify" }
8034
+ },
8035
+ operation: "update",
8036
+ query: { id: organization2 }
8037
+ }
8038
+ ]
8039
+ };
8040
+ },
8041
+ // WHAT THIS STORE CAN SEE: the linked merchant's organizations, the
8042
+ // store's live plan, and the products the merchant has to act on.
8043
+ //
8044
+ // AN ORG CONNECTED TO A DIFFERENT STORE IS OMITTED ENTIRELY, because
8045
+ // `add` would refuse it — a list that offers what the next call rejects
8046
+ // is worse than a shorter one.
8047
+ list: async ({ context }, { conversionRate: conversionRate2, planTitle, read, shopify = client } = {}) => {
8048
+ var _a;
8049
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8050
+ if (!shop) throw refusal("shop is required", 400);
8051
+ const record = await read.get({ collection: "shop", query: { shop } });
8052
+ if (!(record == null ? void 0 : record.user)) {
8053
+ return {
8054
+ message: "No account linked to this store.",
8055
+ request: { shop },
8056
+ result: {
8057
+ account: null,
8058
+ connected: false,
8059
+ organizations: [],
8060
+ plan: { active: false, name: null },
8061
+ unavailableProducts: [],
8062
+ unavailableProductsTotal: 0
8063
+ }
8064
+ };
8065
+ }
8066
+ const owned = await merchantOrganizations({ read, user: record.user });
8067
+ const organizations = (owned || []).filter((org) => !org.connection || org.connection.shop === shop).map((org) => {
8068
+ var _a2;
8069
+ return {
8070
+ // The org's OWN billing status decides whether `add` accepts it.
8071
+ // Sent up so the app can disable Connect and name the reason
8072
+ // rather than letting the merchant click into a 403 —
8073
+ // listed-but-blocked beats hidden, because an org vanishing from
8074
+ // the list is indistinguishable from a bug.
8075
+ billingStatus: org.billingStatus || null,
8076
+ connectable: CONNECTABLE_STATUSES.includes(org.billingStatus),
8077
+ connected: Boolean(org.connection),
8078
+ conversion: conversionRate2(org.subscription),
8079
+ id: org.id,
8080
+ name: org.name,
8081
+ plan: planTitle(org.subscription),
8082
+ status: ((_a2 = org.connection) == null ? void 0 : _a2.status) || null
8083
+ };
8084
+ });
8085
+ const connections2 = (owned || []).filter((org) => {
8086
+ var _a2;
8087
+ return ((_a2 = org.connection) == null ? void 0 : _a2.shop) === shop && org.connection.id;
8088
+ }).map((org) => org.connection.id);
8089
+ const [account, plan, unavailable] = await Promise.all([
8090
+ read.get({ collection: "user", query: { id: record.user } }),
8091
+ storePlan({ record, shopify }),
8092
+ connections2.length ? read.aggregate({
8093
+ collection: "product",
8094
+ pipeline: [
8095
+ { $match: { connections: { $in: connections2 }, "source.domain": shop, status: "inactive" } },
8096
+ // $facet so the app can name the first 25 AND report a
8097
+ // truthful total: listing 25 of 40 under "25 products need
8098
+ // attention" would understate the problem.
8099
+ {
8100
+ $facet: {
8101
+ items: [{ $sort: { title: 1 } }, { $limit: 25 }, { $project: { _id: 0, id: 1, title: 1 } }],
8102
+ total: [{ $count: "count" }]
8103
+ }
8104
+ }
8105
+ ]
8106
+ }) : []
8107
+ ]);
8108
+ const facet = (unavailable || [])[0] || {};
8109
+ if (plan.active && plan.metered !== true) {
8110
+ const stamped = await read.aggregate({
8111
+ collection: "connection",
8112
+ pipeline: [
8113
+ { $match: { shop, slug: "shopify" } },
8114
+ { $project: { _id: 0, "source.metered": 1 } }
8115
+ ]
8116
+ });
8117
+ const verdicts = (stamped || []).map((row2) => {
8118
+ var _a2;
8119
+ return (_a2 = row2 == null ? void 0 : row2.source) == null ? void 0 : _a2.metered;
8120
+ });
8121
+ if (verdicts.some((verdict) => typeof verdict === "string")) plan.metered = true;
8122
+ else if (verdicts.some((verdict) => verdict === null)) plan.metered = false;
8123
+ }
8124
+ return {
8125
+ message: organizations.length + " organization(s) for this store.",
8126
+ request: { shop },
8127
+ result: {
8128
+ account: { email: (account == null ? void 0 : account.email) || null },
8129
+ connected: true,
8130
+ organizations,
8131
+ plan,
8132
+ unavailableProducts: (facet.items || []).map((product) => ({
8133
+ id: product.id,
8134
+ title: product.title || "Untitled product"
8135
+ })),
8136
+ // The total can exceed the 25 listed above, and has to.
8137
+ unavailableProductsTotal: ((_a = (facet.total || [])[0]) == null ? void 0 : _a.count) || 0
8138
+ }
8139
+ };
8140
+ },
8141
+ // DISCONNECT ONE ORGANIZATION. The connection is deleted and nothing
8142
+ // else: every dependent — products, ads, steps, workflows, and the org's
8143
+ // own connection refs — is torn down by drawbridge-sync's connection
8144
+ // change stream. The shared token and the other orgs are untouched.
8145
+ remove: async ({ context }, { read } = {}) => {
8146
+ const organization2 = context == null ? void 0 : context.organization;
8147
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8148
+ if (!shop) throw refusal("shop is required", 400);
8149
+ if (!organization2) throw refusal("organization is required", 400);
8150
+ const record = await read.get({ collection: "shop", query: { shop } });
8151
+ if (!(record == null ? void 0 : record.user)) throw refusal("Account is not connected for this store", 409);
8152
+ const owned = await merchantOrganizations({ read, user: record.user });
8153
+ if (!(owned || []).some((entry) => entry.id === organization2)) {
8154
+ throw refusal("No access to this organization", 403);
8155
+ }
8156
+ const connection2 = await read.get({
8157
+ collection: "connection",
8158
+ query: { organization: organization2, shop, slug: "shopify" }
8159
+ });
8160
+ if (!connection2) throw refusal("No connection to remove", 404);
8161
+ return {
8162
+ message: "Disconnected.",
8163
+ request: { organization: organization2, shop },
8164
+ result: { ok: true },
8165
+ writes: [{ collection: "connection", operation: "delete", query: { id: connection2.id } }]
8166
+ };
8167
+ }
8168
+ },
8169
+ plan: {
8170
+ // RELEASE EVERY ACTIVE APPROVAL. The App Home then re-checks the plan
8171
+ // and falls back to "Choose a plan".
8172
+ cancel: ({ context }, { read, shopify = client } = {}) => releaseApprovals({ context, read, shopify }),
8173
+ // ONE ATTRIBUTED ORDER'S USAGE CHARGE. Enqueued per conversion by the
8174
+ // order step and run on a retrying queue, so this may be called
8175
+ // several times for one order — which is safe because the idempotency
8176
+ // key is PERMANENT for billing events and Shopify settles the repeat.
8177
+ //
8178
+ // THE HANDLE IS CHECKED AGAINST THE MANIFEST'S OWN DECLARATION, which
8179
+ // is a real strengthening of what it replaced: drawbridge-sync compared
8180
+ // the job's `handle` against the job's `transaction` — two fields from
8181
+ // the same enqueuer, so a drifted enqueuer agreed with itself. The
8182
+ // handle is the one string that decides whether the event bills at all,
8183
+ // and this is the file that publishes it.
8184
+ //
8185
+ // REFUSE BEFORE SENDING, because sending burns the order's PERMANENT
8186
+ // idempotency key on an event that misclassifies or mistraces. The
8187
+ // throw rides the queue's normal retry path and the abandoned-job alert
8188
+ // pages on exhaustion.
8189
+ //
8190
+ // DELIBERATELY NO TIMESTAMP. sendAppEvent defaults to the SEND time,
8191
+ // which is always inside the merchant's current billing cycle at the
8192
+ // moment of sending and so can never hit PERIOD_CLOSED. Pinning the
8193
+ // purchase time reads more correct and is strictly worse: a retry
8194
+ // backoff crossing a cycle boundary would carry a closed-cycle
8195
+ // timestamp, Shopify would 202-accept, silently drop it, and the
8196
+ // commission would be lost. Send-time's worst case is benign — the
8197
+ // charge lands in the next cycle, but it lands.
8198
+ charge: async ({ clientId, clientSecret, context, manifest }, { shopify = client } = {}) => {
8199
+ const { idempotencyKey, order, orderId, rate, revision, shopId, timestamp, transaction, value } = context || {};
8200
+ const handle = (context == null ? void 0 : context.handle) || manifest.auth.install.billing.handle;
8201
+ if (!transaction || !String(transaction).startsWith(handle + ".")) {
8202
+ throw new Error("shopify.usage.billing.handle.mismatch on order " + orderId + ": transaction " + (transaction || "null") + " does not carry handle " + handle + " \u2014 refusing to send");
8203
+ }
8204
+ await shopify.billing.sendAppEvent({
8205
+ clientId,
8206
+ clientSecret,
8207
+ eventHandle: handle,
8208
+ idempotencyKey,
8209
+ // The Shopify-side event record names the order that produced it.
8210
+ reference: transaction,
8211
+ // OPERATOR-ONLY, BOTH OF THEM, and absent on every automatic
8212
+ // send. `revision` suffixes the idempotency key, which is what
8213
+ // makes a second attempt possible once a key has been consumed;
8214
+ // the encoding is owned by sendAppEvent so no caller builds keys
8215
+ // itself. `timestamp` pins the PURCHASE time, which the automatic
8216
+ // path must never do — see the note above — and the recovery
8217
+ // migration must, because it is resending orders from a closed
8218
+ // window and bounds its own run to the merchant's current cycle.
8219
+ ...revision && { revision },
8220
+ ...timestamp && { timestamp },
8221
+ shopId,
8222
+ value
8223
+ });
8224
+ return {
8225
+ message: "Usage charge sent for order " + orderId + ".",
8226
+ request: { order: order || null, orderId: orderId || null, shopId: shopId || null, value },
8227
+ result: { transaction: String(transaction) },
8228
+ // TRACEABILITY. The App Events API returns no event id, so the
8229
+ // trace key into Shopify's event logs is the transaction id the
8230
+ // commerce.order hook minted and this sent as `reference`.
8231
+ // `amount` is the per-order usage value in cents, mirroring the
8232
+ // Stripe path's marker.
8233
+ ...order && { writes: [{
8234
+ collection: "order",
8235
+ data: {
8236
+ $set: {
8237
+ billed: {
8238
+ amount: value,
8239
+ date: /* @__PURE__ */ new Date(),
8240
+ rate: rate || 0,
8241
+ transaction: String(transaction)
8242
+ }
8243
+ }
8244
+ },
8245
+ operation: "update",
8246
+ query: { id: order }
8247
+ }] }
8248
+ };
8249
+ },
8250
+ // RESELECT, NOT CANCEL. The same mechanics — the current approval has to
8251
+ // be released before the pricing page will offer the plan again — but
8252
+ // the intent is a thirty-second round trip rather than a departure.
8253
+ //
8254
+ // `mark` IS A DECLARED CAPABILITY, and this is the only slot here that
8255
+ // needs one. The marker has to be persisted BEFORE the approval is
8256
+ // released: it is what tells sync's CANCELLED handler to hold the pause
8257
+ // — no connection error, no owner email — and start a timed recheck that
8258
+ // pauses honestly if the merchant abandons. A described write lands
8259
+ // after the hook returns, which is after the cancel, and a marker
8260
+ // written then can race the very webhook it exists to soften. Same
8261
+ // precedent as `resolveContact`: the one write a description cannot
8262
+ // carry.
8263
+ reselect: async ({ context }, { mark, read, shopify = client } = {}) => {
8264
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8265
+ if (!shop) throw refusal("shop is required", 400);
8266
+ await mark({ shop });
8267
+ return releaseApprovals({ context, read, shopify });
8268
+ },
8269
+ // IS THIS STORE'S ORDER BILLING ACTUALLY METERED? Not a merchant
8270
+ // action — the other two slots here are — but the same subject, and
8271
+ // the reason it is a declared hook rather than a helper is that the
8272
+ // answer was being derived in two places: `lifecycle.health` below,
8273
+ // and drawbridge-sync's app_subscriptions/update handler, whose copy
8274
+ // stated in its own comment that it matched this one and did not.
8275
+ //
8276
+ // THREE ANSWERS, and the caller must keep them apart:
8277
+ //
8278
+ // a string PROVEN. The charge id or usage line id, stamped on
8279
+ // the connection as the evidence.
8280
+ // null PROBED, and nothing is accruing.
8281
+ // undefined NO VERDICT — the probe could not run. `probed` says
8282
+ // which, because undefined does not survive JSON.
8283
+ verify: async ({ context }, { adminToken, read, shopify = client } = {}) => {
8284
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8285
+ if (!shop) throw refusal("shop is required", 400);
8286
+ const adminAccessToken = await adminToken();
8287
+ if (!adminAccessToken) {
8288
+ return { message: "No admin token for this store \u2014 no verdict.", request: { shop }, result: { metered: null, probed: false }, skipped: true };
8289
+ }
8290
+ const partnerRow = (read == null ? void 0 : read.get) ? await read.get({ collection: "provider", query: { slug: "shopify" } }) : null;
8291
+ const partner = (partnerRow == null ? void 0 : partnerRow.settings) ? decrypt(partnerRow.settings) : {};
8292
+ const { ledger, metered } = await meterVerdict({
8293
+ adminAccessToken,
8294
+ ledgerFloor: new Date(Date.now() - LEDGER_WINDOW_MS),
8295
+ partner,
8296
+ shop,
8297
+ shopId: (context == null ? void 0 : context.shopId) || null,
8298
+ shopify
8299
+ });
8300
+ return {
8301
+ message: typeof metered === "string" ? "Billing is metered." : "No meter evidence for this store.",
8302
+ request: { shop },
8303
+ // `probed` is the LEDGER, not the call: a store whose Partner
8304
+ // credentials are absent was not asked, and reporting that as
8305
+ // "probed, nothing accruing" would stamp an unmetered verdict on
8306
+ // a store nobody looked at.
8307
+ result: { metered: metered ?? null, probed: ledger || typeof metered === "string" }
8308
+ };
8309
+ }
8310
+ },
8311
+ // THE EMBEDDED APP'S SESSION STORE. The @shopify/shopify-app library
8312
+ // persists the offline session on token exchange and refresh; it lives
8313
+ // encrypted on the shared `shop` record, which is the same row every
8314
+ // organization's connection to this store points at.
8315
+ session: {
8316
+ // SOFT-CLEAR, NEVER A DELETE. The library calls this on session
8317
+ // invalidation and not only on uninstall, so hard-deleting the record
8318
+ // would orphan every org connection pointing at it — token resolution
8319
+ // silently nulls — and destroy the durable account link and the
8320
+ // storefront token with it. The next embedded load re-runs token
8321
+ // exchange. The full record delete belongs to the uninstall webhook.
8322
+ clear: async ({ context }) => {
8323
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8324
+ if (!shop) throw refusal("shop is required", 400);
8325
+ return {
8326
+ message: "Session cleared.",
8327
+ request: { shop },
8328
+ result: { ok: true },
8329
+ writes: [{
8330
+ collection: "shop",
8331
+ data: { $set: { settings: null } },
8332
+ operation: "update",
8333
+ query: { shop }
8334
+ }]
8335
+ };
8336
+ },
8337
+ read: async ({ context }, { read } = {}) => {
8338
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8339
+ if (!shop) throw refusal("shop is required", 400);
8340
+ const record = await read.get({ collection: "shop", query: { shop } });
8341
+ if (!(record == null ? void 0 : record.settings)) throw refusal("No session for this store", 404);
8342
+ return {
8343
+ message: "Session read.",
8344
+ request: { shop },
8345
+ result: { session: decrypt(record.settings) }
8346
+ };
8347
+ },
8348
+ save: async ({ context }) => {
8349
+ const session = context == null ? void 0 : context.session;
8350
+ const shop = sanitizeDomain(session == null ? void 0 : session.shop);
8351
+ if (!shop || !(session == null ? void 0 : session.accessToken)) throw refusal("session.shop and session.accessToken are required", 400);
8352
+ return {
8353
+ message: "Session saved.",
8354
+ request: { shop },
8355
+ result: { ok: true },
8356
+ writes: [{
8357
+ collection: "shop",
8358
+ data: {
8359
+ $set: { settings: encrypt(session), shop },
8360
+ $setOnInsert: { status: "pending" }
8361
+ },
8362
+ operation: "update",
8363
+ options: { upsert: true },
8364
+ query: { shop }
8365
+ }]
8366
+ };
8367
+ }
8368
+ },
8369
+ // THE LINK-TOKEN HANDOFF. The breakout callback runs top-level and can set
8370
+ // a first-party cookie; the embedded App Home cannot read that cookie from
8371
+ // inside the Shopify admin iframe. So the callback stashes the merchant's
8372
+ // user token here keyed by shop, and App Home reads it once and clears it.
8373
+ //
8374
+ // DURABLE RATHER THAN IN REDIS: a restart must not strand a merchant
8375
+ // mid-handoff. Short-lived and encrypted.
8376
+ token: {
8377
+ clear: async ({ context }) => {
8378
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8379
+ if (!shop) throw refusal("shop is required", 400);
8380
+ return {
8381
+ message: "Link token cleared.",
8382
+ request: { shop },
8383
+ result: { ok: true },
8384
+ writes: [{
8385
+ collection: "shop",
8386
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null } },
8387
+ operation: "update",
8388
+ query: { shop }
8389
+ }]
8390
+ };
8391
+ },
8392
+ read: async ({ context }, { read } = {}) => {
8393
+ var _a;
8394
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8395
+ if (!shop) throw refusal("shop is required", 400);
8396
+ const record = await read.get({ collection: "shop", query: { shop } });
8397
+ const expiresAt = (record == null ? void 0 : record.linkTokenExpiresAt) ? new Date(record.linkTokenExpiresAt) : null;
8398
+ if (!(record == null ? void 0 : record.linkToken) || !expiresAt || expiresAt <= /* @__PURE__ */ new Date()) {
8399
+ throw refusal("No link token for this store", 404);
8400
+ }
8401
+ return {
8402
+ message: "Link token read.",
8403
+ request: { shop },
8404
+ result: { token: ((_a = decrypt(record.linkToken)) == null ? void 0 : _a.token) ?? null }
8405
+ };
8406
+ },
8407
+ save: async ({ context }) => {
8408
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8409
+ const token = context == null ? void 0 : context.token;
8410
+ if (!shop || !token) throw refusal("shop and token are required", 400);
8411
+ return {
8412
+ message: "Link token saved.",
8413
+ request: { shop },
8414
+ result: { ok: true },
8415
+ writes: [{
8416
+ collection: "shop",
8417
+ data: {
8418
+ $set: {
8419
+ linkToken: encrypt({ token }),
8420
+ linkTokenExpiresAt: new Date(Date.now() + LINK_TOKEN_TTL_MS)
8421
+ }
8422
+ },
8423
+ operation: "update",
8424
+ query: { shop }
8425
+ }]
8426
+ };
8427
+ }
8428
+ }
8429
+ },
5694
8430
  // Drawbridge sends its own notification email and SMS — see the private
5695
8431
  // `drawbridge` manifest. A vendor answering these would be a second sender,
5696
8432
  // which is the arrangement the platform sender replaced.
@@ -5752,8 +8488,8 @@ var shopify_default2 = {
5752
8488
  // access token still works, reconciles the scopes the store granted
5753
8489
  // against the ones the app now needs, and queues a webhook
5754
8490
  // reconciliation.
5755
- health: async ({ connection: connection2, workflow }, { adminToken, logger, read, reconcileScopes, resolveSettings, rotateToken, shopify } = {}) => {
5756
- var _a, _b, _c, _d, _e, _f;
8491
+ health: async ({ connection: connection2, workflow }, { adminToken, logger, read, reconcileScopes, resolveSettings, rotateToken, shopify = client } = {}) => {
8492
+ var _a, _b, _c, _d;
5757
8493
  const request2 = {
5758
8494
  connectionId: workflow.connection,
5759
8495
  organizationId: workflow.organization,
@@ -5790,33 +8526,26 @@ var shopify_default2 = {
5790
8526
  shopCurrency = String(shopData.currency || "").toLowerCase() || null;
5791
8527
  sourceRepaired = true;
5792
8528
  }
5793
- const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
5794
- adminAccessToken,
5795
- domain: connection2.shop
5796
- });
5797
- const usageLine = (_a = subscriptions.find((subscription) => subscription.usageLineItemId)) == null ? void 0 : _a.usageLineItemId;
5798
- if (usageLine) metered = usageLine;
5799
8529
  const partnerRow = (read == null ? void 0 : read.get) ? await read.get({ collection: "provider", query: { slug: "shopify" } }) : null;
5800
8530
  const partner = (partnerRow == null ? void 0 : partnerRow.settings) ? decrypt(partnerRow.settings) : {};
5801
- if (partner.partnerToken && partner.partnerOrgId && partner.partnerAppId && (source == null ? void 0 : source.id) && ((_b = shopify.partner) == null ? void 0 : _b.getUsageChargeEvents)) {
5802
- const ledgerFloor = new Date(Date.now() - 30 * 24 * 60 * 60 * 1e3);
5803
- const accruals = await shopify.partner.getUsageChargeEvents({
5804
- appId: "gid://shopify/App/" + partner.partnerAppId,
5805
- first: 10,
5806
- occurredAtMin: ledgerFloor.toISOString(),
5807
- organizationId: partner.partnerOrgId,
5808
- partnerToken: partner.partnerToken,
5809
- shopId: "gid://shopify/Shop/" + source.id
5810
- });
5811
- const boundaries = accruals.filter((event) => event.occurredAt).sort((a, b) => new Date(a.occurredAt) - new Date(b.occurredAt));
5812
- const accrued = [...boundaries].reverse().find((event) => Number(event.usageQuantity) > 0);
5813
- if (accrued) metered = String(accrued.chargeId || accrued.id);
5814
- const stampedAt = (_c = boundaries.find(
8531
+ const ledgerFloor = new Date(Date.now() - LEDGER_WINDOW_MS);
8532
+ const verdict = await meterVerdict({
8533
+ adminAccessToken,
8534
+ ledgerFloor,
8535
+ partner,
8536
+ shop: connection2.shop,
8537
+ shopId: source == null ? void 0 : source.id,
8538
+ shopify
8539
+ });
8540
+ if (verdict.metered !== void 0) metered = verdict.metered;
8541
+ const { boundaries } = verdict;
8542
+ if (boundaries.length) {
8543
+ const stampedAt = (_a = boundaries.find(
5815
8544
  (event) => {
5816
8545
  var _a2;
5817
8546
  return String(event.chargeId || event.id) === String(((_a2 = connection2.source) == null ? void 0 : _a2.metered) || "");
5818
8547
  }
5819
- )) == null ? void 0 : _c.occurredAt;
8548
+ )) == null ? void 0 : _a.occurredAt;
5820
8549
  reconciliation = [];
5821
8550
  let windowStart = ledgerFloor;
5822
8551
  for (const boundary of boundaries) {
@@ -5866,7 +8595,7 @@ var shopify_default2 = {
5866
8595
  }
5867
8596
  });
5868
8597
  } else {
5869
- (_d = logger == null ? void 0 : logger.error) == null ? void 0 : _d.call(logger, new Error(
8598
+ (_b = logger == null ? void 0 : logger.error) == null ? void 0 : _b.call(logger, new Error(
5870
8599
  "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"
5871
8600
  ), {
5872
8601
  extra: {
@@ -5885,13 +8614,13 @@ var shopify_default2 = {
5885
8614
  }
5886
8615
  } catch (probeError) {
5887
8616
  billingProbeFailed = true;
5888
- (_e = logger == null ? void 0 : logger.warn) == null ? void 0 : _e.call(logger, "shopify.health.billing.probe.failed", {
8617
+ (_c = logger == null ? void 0 : logger.warn) == null ? void 0 : _c.call(logger, "shopify.health.billing.probe.failed", {
5889
8618
  connectionId: connection2.id,
5890
8619
  message: probeError == null ? void 0 : probeError.message,
5891
8620
  shop: connection2.shop
5892
8621
  });
5893
8622
  }
5894
- if (sourceRepaired || metered !== void 0 && metered !== (((_f = connection2.source) == null ? void 0 : _f.metered) ?? void 0)) {
8623
+ if (sourceRepaired || metered !== void 0 && metered !== (((_d = connection2.source) == null ? void 0 : _d.metered) ?? void 0)) {
5895
8624
  writes.push({
5896
8625
  collection: "connection",
5897
8626
  data: {
@@ -6026,13 +8755,13 @@ var shopify_default2 = {
6026
8755
  // They are the same two questions every other vendor answers through
6027
8756
  // resources.*, so they answer them the same way now.
6028
8757
  //
6029
- // `shopify` is INJECTED: this package cannot import @drawbridge/shopify,
8758
+ // `shopify` DEFAULTS to the client this file imports; nothing injects it,
6030
8759
  // which depends on it. What arrives is the SDK's pure HTTP namespaces
6031
8760
  // and nothing else — no controller, no collection access. Resolving the
6032
8761
  // credential is the caller's job because it is Drawbridge's job: the
6033
8762
  // admin token refreshes and writes itself back, which is service work,
6034
8763
  // not vendor work.
6035
- products: async ({ cursor, limit = 100, search, settings, sort }, { shopify } = {}) => {
8764
+ products: async ({ cursor, limit = 100, search, settings, sort }, { shopify = client } = {}) => {
6036
8765
  var _a, _b, _c, _d;
6037
8766
  const products = await shopify.storefront.getProducts({
6038
8767
  cursor,
@@ -6054,7 +8783,7 @@ var shopify_default2 = {
6054
8783
  }
6055
8784
  };
6056
8785
  },
6057
- promotions: async ({ cursor, limit = 100, search, settings }, { shopify } = {}) => {
8786
+ promotions: async ({ cursor, limit = 100, search, settings }, { shopify = client } = {}) => {
6058
8787
  var _a, _b;
6059
8788
  const discounts = await shopify.admin.getDiscounts({
6060
8789
  adminAccessToken: settings == null ? void 0 : settings.adminAccessToken,
@@ -6205,6 +8934,13 @@ var shopify_default2 = {
6205
8934
  key: "Shopify Order Tracking",
6206
8935
  queue: "connection",
6207
8936
  system: true,
8937
+ // THE TRIGGER THE REGISTER JOB HAND-WROTE. It is byte-identical to
8938
+ // the one on every stored workflow, because these documents exist on
8939
+ // prod with thousands of runs behind them and provisioning is
8940
+ // idempotent on (connection, system, title) — a different trigger
8941
+ // here would not be picked up by the existing rows anyway, and a
8942
+ // different TITLE would provision a second workflow for every store.
8943
+ trigger: { event: "shopify.order.create", type: "webhook" },
6208
8944
  type: "step.commerce.order.record"
6209
8945
  })
6210
8946
  },
@@ -6215,6 +8951,15 @@ var shopify_default2 = {
6215
8951
  key: "Shopify Product Sync",
6216
8952
  queue: "connection",
6217
8953
  system: true,
8954
+ // `shopify.product.update`, NOT `product.insert`. The plan named the
8955
+ // latter, and it is the right long-term answer — a Drawbridge product
8956
+ // row appearing should pull the vendor's copy, rather than
8957
+ // stream/product.js branching on the slug and enqueueing a
8958
+ // vendor-named queue. But a workflow carries ONE trigger, this one is
8959
+ // stored on prod against the webhook, and changing a live workflow's
8960
+ // trigger is a data migration. So the declaration matches what exists
8961
+ // and `product.insert` stays a separate, migration-gated change.
8962
+ trigger: { event: "shopify.product.update", type: "webhook" },
6218
8963
  type: "step.commerce.product.sync"
6219
8964
  })
6220
8965
  }
@@ -6236,26 +8981,37 @@ var shopify_default2 = {
6236
8981
  type: "step.connection.health.check"
6237
8982
  })
6238
8983
  },
6239
- // Audit-only. The "Shopify Token Activity" system workflow lists these
6240
- // for descriptive grouping, but its audit step docs are written manually
6241
- // at OAuth time — the workflow is never dispatched. Routing is declared
6242
- // defensively so that if it ever IS dispatched, the job lands on a real
6243
- // queue and the handler lookup misses cleanly instead of throwing
6244
- // "Unknown step type".
8984
+ // THE ONE WORKFLOW THAT CARRIES TWO STEPS, and the shape the plan called
8985
+ // the single genuinely new thing in it.
8986
+ //
8987
+ // Every other system step is its own workflow, titled by its own `key`.
8988
+ // These two are "Shopify Token Activity", one row in the merchant's list
8989
+ // with both steps in it — so they declare `workflow`, which names the
8990
+ // title, the trigger and the ORDER, and the provisioner groups on it.
8991
+ // Without that key the pair could only be provisioned by the hand-written
8992
+ // spec in drawbridge-sync's register job, which is exactly why that spec
8993
+ // outlived every other one.
8994
+ //
8995
+ // AUDIT-ONLY. The step documents are written manually at OAuth time and
8996
+ // the workflow is never dispatched; `queue` is declared defensively so
8997
+ // that if it ever IS, the job lands on a real queue and the handler lookup
8998
+ // misses cleanly rather than throwing "Unknown step type".
6245
8999
  token: {
6246
9000
  exchange: () => ({
6247
9001
  description: "Records the token exchange that completed an install. Audit only \u2014 never dispatched.",
6248
9002
  key: "Shopify Token Exchange",
6249
9003
  queue: "connection",
6250
9004
  system: true,
6251
- type: "step.connection.token.exchange"
9005
+ type: "step.connection.token.exchange",
9006
+ workflow: { key: "Shopify Token Activity", order: 0, trigger: { event: "shopify.token", type: "event" } }
6252
9007
  }),
6253
9008
  refresh: () => ({
6254
9009
  description: "Records a token rotation. Audit only \u2014 never dispatched.",
6255
9010
  key: "Shopify Token Refresh",
6256
9011
  queue: "connection",
6257
9012
  system: true,
6258
- type: "step.connection.token.refresh"
9013
+ type: "step.connection.token.refresh",
9014
+ workflow: { key: "Shopify Token Activity", order: 1, trigger: { event: "shopify.token", type: "event" } }
6259
9015
  })
6260
9016
  }
6261
9017
  }
@@ -6559,14 +9315,15 @@ var webhook_default = {
6559
9315
  "Drawbridge can POST event payloads to your endpoint as activity happens in your account, so your own systems can react to it.",
6560
9316
  "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."
6561
9317
  ],
6562
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
6563
- // The dashboard already carries generic reasons for every way an
6564
- // authorization can fail declined, expired state, a vendor we are not set
6565
- // up for and a sentence here is an ADDITION to those, for a vendor whose
6566
- // failures need saying differently. This one's do not.
9318
+ // THERE IS NO CONSENT SCREEN TO FAIL. Connecting mints a signing secret;
9319
+ // nothing is authorized against a third party, so neither `denied` nor
9320
+ // `invalid` has a state it could describe. The failures this connection
9321
+ // really has are at DELIVERY a merchant's endpoint refusing a POST and
9322
+ // those reach them through the connection's own errors rather than through
9323
+ // connect copy.
6567
9324
  //
6568
- // Answered rather than omitted, because `errors` existed on two of six
6569
- // manifests and there was no way to tell "nothing to add" from "nobody
9325
+ // `false` is the recorded decision, not silence: `errors` existed on two of
9326
+ // six manifests and there was no way to tell "nothing to add" from "nobody
6570
9327
  // wrote it".
6571
9328
  errors: false,
6572
9329
  excerpt: "Sign outgoing webhook payloads with an HMAC secret to verify authenticity.",
@@ -6710,7 +9467,7 @@ var webhook_default = {
6710
9467
  // The connect prompt only where connecting is not already the card's whole
6711
9468
  // story: a disconnected or errored document renders a Connect action itself,
6712
9469
  // and a task repeating it talks over the button.
6713
- tasks: ({ settings, status } = {}) => ["disconnected", "error"].includes(status) ? [] : (settings == null ? void 0 : settings.secret) ? [
9470
+ tasks: ({ settings, status } = {}) => status === "error" ? [] : (settings == null ? void 0 : settings.secret) ? [
6714
9471
  {
6715
9472
  message: 'Compute HMAC-SHA256( secret, t + "." + raw body ) and constant-time compare it against a v1 in the X-Drawbridge-Signature header; reject timestamps older than five minutes.',
6716
9473
  title: "Requests must be verified",
@@ -6797,6 +9554,77 @@ var attentive_default3 = {
6797
9554
  }
6798
9555
  };
6799
9556
 
9557
+ // lib/connections/icons/brightdata.js
9558
+ var brightdata_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
9559
+ <rect width="500" height="500" fill="#0F58FF"/>
9560
+ <circle cx="250" cy="250" r="52" fill="white"/>
9561
+ <rect x="234" y="70" width="32" height="96" rx="16" fill="white"/>
9562
+ <rect x="234" y="334" width="32" height="96" rx="16" fill="white"/>
9563
+ <rect x="70" y="234" width="96" height="32" rx="16" fill="white"/>
9564
+ <rect x="334" y="234" width="96" height="32" rx="16" fill="white"/>
9565
+ <rect x="117" y="140" width="32" height="96" rx="16" transform="rotate(-45 117 140)" fill="white"/>
9566
+ <rect x="304" y="327" width="32" height="96" rx="16" transform="rotate(-45 304 327)" fill="white"/>
9567
+ <rect x="360" y="117" width="32" height="96" rx="16" transform="rotate(45 360 117)" fill="white"/>
9568
+ <rect x="173" y="304" width="32" height="96" rx="16" transform="rotate(45 173 304)" fill="white"/>
9569
+ </svg>`;
9570
+
9571
+ // lib/connections/vendors/brightdata.js
9572
+ var brightdata_default2 = {
9573
+ fields: [
9574
+ {
9575
+ credential: "BRIGHTDATA_BROWSER_URI",
9576
+ input: "password",
9577
+ key: "browserUri",
9578
+ // A wss:// endpoint with the account's user and password in its
9579
+ // authority, which is why it is a password field rather than a url one:
9580
+ // the whole string is the credential.
9581
+ label: "Scraping Browser endpoint",
9582
+ message: "The wss:// Scraping Browser endpoint, carrying its own credentials. Used to render pages that need a real browser.",
9583
+ redact: true,
9584
+ required: true
9585
+ },
9586
+ {
9587
+ credential: "BRIGHTDATA_UNLOCKER_API_KEY",
9588
+ input: "password",
9589
+ key: "unlockerApiKey",
9590
+ label: "Web Unlocker API key",
9591
+ // NO EXPIRY FIELD, and that is a decision rather than an omission. Bright
9592
+ // Data offers an `Unlimited` expiry and recommends against it; Drawbridge
9593
+ // takes the unlimited key deliberately, because there is no way to rotate
9594
+ // this programmatically and a date nothing can act on is a date that only
9595
+ // surfaces after it has already broken scraping. If a fixed expiry is ever
9596
+ // taken instead, the field to add is a stored date and a warning ahead of
9597
+ // it — not a rotation, which the vendor cannot support.
9598
+ message: "Bright Data account settings \u2192 API keys. Taken with an unlimited expiry: their API offers no way to rotate a key, so a dated one can only ever break scraping silently.",
9599
+ redact: true,
9600
+ required: true
9601
+ },
9602
+ {
9603
+ credential: "BRIGHTDATA_UNLOCKER_ZONE",
9604
+ input: "text",
9605
+ key: "unlockerZone",
9606
+ label: "Web Unlocker zone",
9607
+ // Not secret — a zone is a label on the account, and it is shown rather
9608
+ // than redacted so an operator can confirm which one is in use without
9609
+ // clearing the field to read it.
9610
+ message: "The zone name the Unlocker requests run against.",
9611
+ required: true
9612
+ }
9613
+ ],
9614
+ icon: brightdata_default,
9615
+ name: "Bright Data",
9616
+ slug: "brightdata",
9617
+ // WHERE THE FACTS CAME FROM, read 2026-09-16.
9618
+ urls: {
9619
+ api: "https://docs.brightdata.com/api-reference/authentication",
9620
+ dashboard: "https://brightdata.com/cp/setting/users",
9621
+ // Bright Data has no scope model — a key carries the account's own access —
9622
+ // so there is nothing to link. `false` is the recorded answer rather than a
9623
+ // missing key.
9624
+ scopes: false
9625
+ }
9626
+ };
9627
+
6800
9628
  // lib/connections/vendors/hubspot.js
6801
9629
  var hubspot_default2 = {
6802
9630
  // WHAT AN ADMIN TYPES on the provider screen. `credential` names the env var a
@@ -7172,7 +10000,7 @@ var checkIcon = (owner, icon) => {
7172
10000
  }
7173
10001
  };
7174
10002
  var vendors = Object.freeze(Object.fromEntries(
7175
- [attentive_default3, hubspot_default2, klaviyo_default3, mailchimp_default3, sendgrid_default2, shopify_default3, twilio_default2].map((vendor) => [vendor.slug, vendor])
10003
+ [attentive_default3, brightdata_default2, hubspot_default2, klaviyo_default3, mailchimp_default3, sendgrid_default2, shopify_default3, twilio_default2].map((vendor) => [vendor.slug, vendor])
7176
10004
  ));
7177
10005
  var buildVendor = (vendor) => {
7178
10006
  if (!(vendor == null ? void 0 : vendor.slug)) throw new Error("A vendor needs a slug");
@@ -7199,7 +10027,7 @@ for (const [slug2, vendor] of Object.entries(vendors)) {
7199
10027
  buildVendor(vendor);
7200
10028
  }
7201
10029
  var build = (manifest) => {
7202
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
10030
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y;
7203
10031
  if (!(manifest == null ? void 0 : manifest.slug)) throw new Error("A connection needs a slug");
7204
10032
  if (!(manifest == null ? void 0 : manifest.title)) throw new Error(manifest.slug + " needs a title");
7205
10033
  if (manifest == null ? void 0 : manifest.private) throw new Error(manifest.slug + " declares private \u2014 that is feature : false now");
@@ -7465,11 +10293,22 @@ var build = (manifest) => {
7465
10293
  manifest.slug + " step " + type2 + " may be triggered by " + trigger + ", which is not a trigger \u2014 one of " + Object.keys(TRIGGERS).join(", ")
7466
10294
  );
7467
10295
  }
7468
- if (declared2.trigger) {
7469
- const known2 = TRIGGERS[Object.keys(TRIGGERS).find((key) => TRIGGERS[key].event === declared2.trigger.event && TRIGGERS[key].type === declared2.trigger.type)];
10296
+ if (declared2.workflow) {
10297
+ if (!declared2.workflow.key) {
10298
+ throw new Error(manifest.slug + " step " + type2 + " declares a workflow with no key \u2014 the title several steps share");
10299
+ }
10300
+ if (typeof declared2.workflow.order !== "number") {
10301
+ throw new Error(manifest.slug + " step " + type2 + " declares a workflow with no order \u2014 two steps in one row need a sequence");
10302
+ }
10303
+ if (declared2.trigger) {
10304
+ throw new Error(manifest.slug + " step " + type2 + " declares BOTH a trigger and a workflow \u2014 the workflow carries the trigger for every step in it");
10305
+ }
10306
+ }
10307
+ for (const candidate of [declared2.trigger, (_y = declared2.workflow) == null ? void 0 : _y.trigger].filter(Boolean)) {
10308
+ const known2 = TRIGGERS[Object.keys(TRIGGERS).find((key) => TRIGGERS[key].event === candidate.event && TRIGGERS[key].type === candidate.type)];
7470
10309
  if (!known2) {
7471
10310
  throw new Error(
7472
- manifest.slug + " step " + type2 + " declares trigger { event : " + declared2.trigger.event + ", type : " + declared2.trigger.type + " }, which nothing dispatches"
10311
+ manifest.slug + " step " + type2 + " declares trigger { event : " + candidate.event + ", type : " + candidate.type + " }, which nothing dispatches"
7473
10312
  );
7474
10313
  }
7475
10314
  }