@drawbridge/drawbridge-utils 0.0.176 → 0.0.177

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/admin-B9ZaLvan.d.cts +697 -0
  2. package/dist/admin-C3HtEM6h.d.ts +697 -0
  3. package/dist/billing-Bc4yo9XG.d.cts +175 -0
  4. package/dist/billing-mNsKflmQ.d.ts +175 -0
  5. package/dist/billing.d.cts +1 -1
  6. package/dist/billing.d.ts +1 -1
  7. package/dist/connections/index.cjs +3077 -228
  8. package/dist/connections/index.d.cts +13 -4
  9. package/dist/connections/index.d.ts +13 -4
  10. package/dist/connections/index.js +3107 -255
  11. package/dist/features.cjs +2940 -226
  12. package/dist/features.d.cts +13 -4
  13. package/dist/features.d.ts +13 -4
  14. package/dist/features.js +2980 -260
  15. package/dist/http.cjs +10 -1
  16. package/dist/http.d.cts +10 -1
  17. package/dist/http.d.ts +10 -1
  18. package/dist/http.js +10 -1
  19. package/dist/{index-B8JhYfvU.d.ts → index-B546oDNo.d.ts} +2837 -956
  20. package/dist/{index-qY18QITf.d.cts → index-C59xHago.d.cts} +2837 -956
  21. package/dist/oauth/index.d.cts +1 -1
  22. package/dist/oauth/index.d.ts +1 -1
  23. package/dist/oauth-BJDh0sdM.d.cts +527 -0
  24. package/dist/oauth-DveZMLHx.d.ts +527 -0
  25. package/dist/partner-BOZltuh2.d.ts +94 -0
  26. package/dist/partner-ed2OfW1J.d.cts +94 -0
  27. package/dist/plans.cjs +2939 -225
  28. package/dist/plans.d.cts +13 -4
  29. package/dist/plans.d.ts +13 -4
  30. package/dist/plans.js +2980 -260
  31. package/dist/pricing.cjs +2972 -258
  32. package/dist/pricing.d.cts +13 -4
  33. package/dist/pricing.d.ts +13 -4
  34. package/dist/pricing.js +2977 -257
  35. package/dist/providers.cjs +2942 -247
  36. package/dist/providers.d.cts +12 -3
  37. package/dist/providers.d.ts +12 -3
  38. package/dist/providers.js +2946 -245
  39. package/dist/sendgrid.cjs +10 -1
  40. package/dist/sendgrid.js +10 -1
  41. package/dist/shopify/admin.cjs +562 -0
  42. package/dist/shopify/admin.d.cts +3 -0
  43. package/dist/shopify/admin.d.ts +3 -0
  44. package/dist/shopify/admin.js +528 -0
  45. package/dist/shopify/billing.cjs +166 -0
  46. package/dist/shopify/billing.d.cts +3 -0
  47. package/dist/shopify/billing.d.ts +3 -0
  48. package/dist/shopify/billing.js +140 -0
  49. package/dist/shopify/constants.cjs +63 -0
  50. package/dist/shopify/constants.d.cts +58 -0
  51. package/dist/shopify/constants.d.ts +58 -0
  52. package/dist/shopify/constants.js +32 -0
  53. package/dist/shopify/oauth.cjs +509 -0
  54. package/dist/shopify/oauth.d.cts +7 -0
  55. package/dist/shopify/oauth.d.ts +7 -0
  56. package/dist/shopify/oauth.js +466 -0
  57. package/dist/shopify/partner.cjs +156 -0
  58. package/dist/shopify/partner.d.cts +3 -0
  59. package/dist/shopify/partner.d.ts +3 -0
  60. package/dist/shopify/partner.js +130 -0
  61. package/dist/shopify/storefront.cjs +611 -0
  62. package/dist/shopify/storefront.d.cts +3 -0
  63. package/dist/shopify/storefront.d.ts +3 -0
  64. package/dist/shopify/storefront.js +576 -0
  65. package/dist/storefront-C8FKOGeD.d.cts +659 -0
  66. package/dist/storefront-DJFGLqPl.d.ts +659 -0
  67. package/dist/twilio.cjs +10 -1
  68. package/dist/twilio.js +10 -1
  69. package/package.json +98 -68
package/dist/features.js CHANGED
@@ -1,3 +1,9 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
1
7
  // lib/connections/contract.js
2
8
  var HOOKS = Object.freeze({
3
9
  // Proving and holding the credential.
@@ -124,6 +130,10 @@ var HOOKS = Object.freeze({
124
130
  "code",
125
131
  // Create the buyer at the vendor, so an order can be attributed to them.
126
132
  "customer",
133
+ // HOW MANY OF THIS PRODUCT ARE LEFT, at the vendor. Read at the moment a
134
+ // campaign's product list is rendered rather than stored, because stock is
135
+ // the one product fact that is stale the instant it is written down.
136
+ "inventory",
127
137
  // An order arrived at the vendor: attribute it, record it, update totals.
128
138
  "order",
129
139
  // Pull product data across on a vendor update.
@@ -191,7 +201,19 @@ var HOOKS = Object.freeze({
191
201
  organizations: Object.freeze(["add", "list", "remove"]),
192
202
  // What the merchant pays the VENDOR. Pairs with auth.install.billing, which
193
203
  // declares the plan they are being charged on.
194
- plan: Object.freeze(["cancel", "reselect"]),
204
+ //
205
+ // `verify` is the odd one of the three: not something a merchant does, but
206
+ // the question "is this store's billing actually metered right now". It is
207
+ // here because it is the same subject — and because the answer was being
208
+ // derived in TWO places, the vendor's health check and drawbridge-sync's
209
+ // approval webhook, whose copy said in its own comment that it matched the
210
+ // other and did not.
211
+ // `charge` and `verify` are the two that are not merchant actions: one
212
+ // sends a usage charge to the vendor's meter, the other asks whether that
213
+ // meter is actually working. Both are here because both are the same
214
+ // subject — what the merchant pays the vendor — and both were being done
215
+ // from drawbridge-sync with a direct import of the vendor's client.
216
+ plan: Object.freeze(["cancel", "charge", "reselect", "verify"]),
195
217
  // The embedded app's own session, stored by us on the vendor's behalf.
196
218
  session: Object.freeze(["clear", "read", "save"]),
197
219
  // The one-time code that hands a merchant from the embedded app into
@@ -276,7 +298,7 @@ var ANSWER_KEYS = Object.freeze([
276
298
  "usage"
277
299
  ].sort());
278
300
  var WRITE_OPERATIONS = Object.freeze(["create", "delete", "update"]);
279
- var INSTALL_SIGNATURE = Object.freeze({ options: ["read", "request"], props: ["context"] });
301
+ var INSTALL_SIGNATURE = Object.freeze({ options: ["read"], props: ["context"] });
280
302
  var LIFECYCLE_SIGNATURE = Object.freeze({ options: ["dispatch"], props: ["context"] });
281
303
  var RESOURCE_SIGNATURE = Object.freeze({
282
304
  options: ["fetcher", "shopify"],
@@ -293,15 +315,30 @@ var HOOK_SLOT_PROPS = Object.freeze({
293
315
  // the second bag would be silently discarded, which is exactly the
294
316
  // stubbed-fetcher-reaches-production failure the split exists to prevent.
295
317
  "auth.token": false,
296
- // COMMERCE. `cart` is declared and unimplemented the Checkout Kit path in
297
- // api/route/subdomain.js writes nothing, which is why it never became a hook
298
- // so its signature mirrors `code`, its nearest sibling, and moving the
299
- // route here is a deliberate widening of this line rather than a silent one.
300
- "commerce.cart": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context", "step"] }),
318
+ // COMMERCE. `cart` is the odd one: it runs for a SHOPPER on a public page,
319
+ // not for an organization inside a workflow, so it takes no `connection` and
320
+ // no `step`. It reads the storefront with the store's own storefront token
321
+ // and mints a checkout token from DRAWBRIDGE'S app credentials, which is why
322
+ // `clientId`/`clientSecret` are here as props, the way auth.disconnect
323
+ // already carries them, because a credential is a fact of the run rather
324
+ // than a service.
325
+ "commerce.cart": Object.freeze({
326
+ options: ["fetcher", "shopify"],
327
+ props: ["clientId", "clientSecret", "context", "settings"]
328
+ }),
301
329
  "commerce.code": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context", "step"] }),
302
330
  "commerce.customer": Object.freeze({ options: ["adminToken", "read", "shopify"], props: ["connection", "context"] }),
331
+ "commerce.inventory": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context"] }),
303
332
  "commerce.order": Object.freeze({ options: ["conversionRate", "logger", "mintId", "read"], props: ["connection", "context"] }),
304
- "commerce.product": Object.freeze({ options: ["mintId", "read"], props: ["connection", "context", "workflow"] }),
333
+ // THREE OPERATIONS, one slot — record, sync, variants. `settings` and
334
+ // `adminToken` arrived with the pull half: the storefront read needs the
335
+ // store's storefront token and the product-feedback send needs its admin one,
336
+ // and both are resolved by the caller because minting either needs a
337
+ // controller.
338
+ "commerce.product": Object.freeze({
339
+ options: ["adminToken", "mintId", "read", "shopify"],
340
+ props: ["connection", "context", "settings", "workflow"]
341
+ }),
305
342
  // THE ADDRESS IS `contact` IN BOTH, and the shell already says why: it is the
306
343
  // person, not the lead document. `remove` called it `email` and `sync` called
307
344
  // it `doc` on one vendor and `lead` on three — three names for two facts.
@@ -314,19 +351,58 @@ var HOOK_SLOT_PROPS = Object.freeze({
314
351
  "inbound.process": Object.freeze({ options: ["dispatch"], props: ["context"] }),
315
352
  "inbound.receive": Object.freeze({ options: [], props: ["channel", "event", "headers", "payload"] }),
316
353
  "inbound.verify": Object.freeze({ options: [], props: ["body", "channel", "headers", "secret", "url"] }),
317
- // INSTALL — thirteen slots, none implemented yet. They are what the thirteen
318
- // routes in api/route/shopify-embedded.js become, and the signature is
319
- // deliberately narrow: `context` is the request's own body, `read` and
320
- // `request` are the only services an install surface has been shown to need.
321
- // A route that cannot be expressed inside this line is a finding to bring
322
- // back here, not a name to add at the call site.
354
+ // INSTALL — thirteen slots, and they are the thirteen routes that used to be
355
+ // api/route/shopify-embedded.js. `context` is the request's own body in all
356
+ // of them; the options are where they differ, and every difference below was
357
+ // forced by a line in those routes rather than chosen.
358
+ //
359
+ // SEVEN NEED NOTHING BUT `read`. The two session slots that write, the two
360
+ // token slots that write, the two clears, and both account slots answer from
361
+ // the shared install record alone.
362
+ //
363
+ // SIX TAKE MORE, and the widenings are worth naming because each is a fact
364
+ // Drawbridge owns that the manifest must not:
365
+ //
366
+ // conversionRate, planTitle what Drawbridge charges this organization.
367
+ // The org list renders both, and importing the
368
+ // plan catalogue here is the cycle
369
+ // features -> connections -> shopify -> plans
370
+ // -> features that was just broken.
371
+ // currencies which settlement currencies Drawbridge can
372
+ // bill. A store outside them fails the
373
+ // connection validator INSIDE the transaction,
374
+ // which surfaces as an opaque 500, so `add`
375
+ // checks first and says so.
376
+ // mintId the connection's id, known before the write
377
+ // that creates it, because the organization's
378
+ // own refs have to name it in the same
379
+ // transaction.
380
+ // shopify the vendor. Four slots call the store: two
381
+ // read the live plan, two release it.
382
+ // mark THE ONE WRITE A DESCRIPTION CANNOT CARRY, and
383
+ // `reselect` is the only slot with one. See its
384
+ // implementation for why the order is the point.
323
385
  "install.account.link": INSTALL_SIGNATURE,
324
386
  "install.account.unlink": INSTALL_SIGNATURE,
325
- "install.organizations.add": INSTALL_SIGNATURE,
326
- "install.organizations.list": INSTALL_SIGNATURE,
387
+ "install.organizations.add": Object.freeze({
388
+ options: ["currencies", "mintId", "read", "shopify"],
389
+ props: ["context"]
390
+ }),
391
+ "install.organizations.list": Object.freeze({
392
+ options: ["conversionRate", "planTitle", "read", "shopify"],
393
+ props: ["context"]
394
+ }),
327
395
  "install.organizations.remove": INSTALL_SIGNATURE,
328
- "install.plan.cancel": INSTALL_SIGNATURE,
329
- "install.plan.reselect": INSTALL_SIGNATURE,
396
+ "install.plan.cancel": Object.freeze({ options: ["read", "shopify"], props: ["context"] }),
397
+ // `manifest` because the handle this charge bills under is the vendor's own
398
+ // declaration (auth.install.billing.handle), and checking the job against the
399
+ // declaration is what the enqueuer-checks-itself version could not do.
400
+ "install.plan.charge": Object.freeze({
401
+ options: ["shopify"],
402
+ props: ["clientId", "clientSecret", "context", "manifest"]
403
+ }),
404
+ "install.plan.reselect": Object.freeze({ options: ["mark", "read", "shopify"], props: ["context"] }),
405
+ "install.plan.verify": Object.freeze({ options: ["adminToken", "read", "shopify"], props: ["context"] }),
330
406
  "install.session.clear": INSTALL_SIGNATURE,
331
407
  "install.session.read": INSTALL_SIGNATURE,
332
408
  "install.session.save": INSTALL_SIGNATURE,
@@ -485,6 +561,52 @@ var ERROR_SOURCES = Object.freeze({
485
561
  "shopify.register.webhooks": true
486
562
  });
487
563
 
564
+ // lib/encrypt.js
565
+ import crypto2 from "crypto";
566
+
567
+ // lib/token.js
568
+ import crypto from "crypto";
569
+ var generate = (bytes = 32, encoding = "base64url") => {
570
+ const buf = crypto.randomBytes(bytes);
571
+ return encoding ? buf.toString(encoding) : buf;
572
+ };
573
+ var hash = (value, key) => {
574
+ if (!value) return null;
575
+ if (key) {
576
+ return crypto.createHmac("sha256", key).update(String(value)).digest("base64url");
577
+ }
578
+ return crypto.createHash("sha256").update(String(value)).digest("base64url");
579
+ };
580
+
581
+ // lib/encrypt.js
582
+ var ALGORITHM = "aes-256-gcm";
583
+ var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
584
+ var encrypt = (value) => {
585
+ const iv = generate(12, null);
586
+ const cipher = crypto2.createCipheriv(ALGORITHM, getKey(), iv);
587
+ const data = Buffer.concat([
588
+ cipher.update(JSON.stringify(value), "utf8"),
589
+ cipher.final()
590
+ ]);
591
+ const tag = cipher.getAuthTag();
592
+ return [iv, tag, data].map((b) => b.toString("hex")).join(":");
593
+ };
594
+ var decrypt = (value) => {
595
+ if (typeof value !== "string") return value;
596
+ const [ivHex, tagHex, dataHex] = value.split(":");
597
+ const decipher = crypto2.createDecipheriv(
598
+ ALGORITHM,
599
+ getKey(),
600
+ Buffer.from(ivHex, "hex")
601
+ );
602
+ decipher.setAuthTag(Buffer.from(tagHex, "hex"));
603
+ const result = Buffer.concat([
604
+ decipher.update(Buffer.from(dataHex, "hex")),
605
+ decipher.final()
606
+ ]);
607
+ return JSON.parse(result.toString("utf8"));
608
+ };
609
+
488
610
  // lib/connections/oauth.js
489
611
  import { createHash, randomBytes } from "crypto";
490
612
  var credentials = ({ basic, clientId, clientSecret }) => basic ? {
@@ -511,10 +633,10 @@ var authToken = async ({
511
633
  const renewing = !code;
512
634
  if (renewing && !refreshToken) throw new Error("Nothing has been consented to yet, so there is no refresh token to spend");
513
635
  if (!renewing && descriptor.pkce && !verifier) throw new Error("This connection requires PKCE, so the code verifier is not optional");
514
- const client = credentials({ basic, clientId, clientSecret });
636
+ const client2 = credentials({ basic, clientId, clientSecret });
515
637
  const response = await fetcher(descriptor.endpoints.token, {
516
638
  body: new URLSearchParams({
517
- ...client.body,
639
+ ...client2.body,
518
640
  ...renewing ? { grant_type: "refresh_token", refresh_token: refreshToken } : {
519
641
  code: decodeURIComponent(String(code || "").trim()),
520
642
  grant_type: "authorization_code",
@@ -522,7 +644,7 @@ var authToken = async ({
522
644
  ...descriptor.pkce && { code_verifier: verifier }
523
645
  }
524
646
  }),
525
- headers: { "content-type": "application/x-www-form-urlencoded", ...client.headers },
647
+ headers: { "content-type": "application/x-www-form-urlencoded", ...client2.headers },
526
648
  method: "POST",
527
649
  signal: AbortSignal.timeout(15e3)
528
650
  });
@@ -917,9 +1039,18 @@ var scaffold_default = {
917
1039
  commerce: {
918
1040
  // NEW in phase 1 — the Checkout Kit cart path, which writes nothing and is
919
1041
  // the last api surface Shopify owns outside a hook.
920
- cart: async ({ connection: connection2, context }, { read } = {}) => ANSWER,
1042
+ // NO `connection` AND NO `step`: this one runs for a SHOPPER on a public
1043
+ // page, not for an organization inside a workflow. It reads the storefront
1044
+ // with the store's storefront token and mints a checkout token from
1045
+ // DRAWBRIDGE'S app credentials, which is why the credential pair rides in
1046
+ // as props — the way auth.disconnect already carries it.
1047
+ cart: async ({ clientId, clientSecret, context, settings }, { fetcher, shopify } = {}) => ANSWER,
921
1048
  code: async ({ connection: connection2, context, step }, { adminToken, shopify } = {}) => ANSWER,
922
1049
  customer: async ({ connection: connection2, context }, { adminToken, read, shopify } = {}) => ANSWER,
1050
+ // STOCK, READ AT RENDER TIME rather than stored. It is the one product
1051
+ // fact that is stale the instant it is written down, so the campaign
1052
+ // product list asks the vendor and caches the answer for a minute.
1053
+ inventory: async ({ connection: connection2, context }, { adminToken, shopify } = {}) => ANSWER,
923
1054
  order: async ({ connection: connection2, context }, { logger, mintId, read } = {}) => ANSWER,
924
1055
  // THIS IS WHERE `product.insert` LANDS.
925
1056
  //
@@ -941,7 +1072,7 @@ var scaffold_default = {
941
1072
  // nothing and shows up only as `workflow.dispatch.candidates matched : 0` in
942
1073
  // a log. Phase 1 closes it and build() checks every trigger against it.
943
1074
  product: {
944
- hook: async ({ connection: connection2, context, workflow }, { mintId, read } = {}) => ANSWER,
1075
+ hook: async ({ connection: connection2, context, settings, workflow }, { adminToken, mintId, read, shopify } = {}) => ANSWER,
945
1076
  step: () => ({
946
1077
  description: "Syncs product data from the vendor when a product changes.",
947
1078
  key: "Vendor Product Sync",
@@ -1089,8 +1220,19 @@ var scaffold_default = {
1089
1220
  // Vendor billing, the only group that is not generic. Pairs with
1090
1221
  // auth.install.billing, which declares what the merchant is being charged.
1091
1222
  plan: {
1092
- cancel: async ({ context }, { dispatch, read } = {}) => ANSWER,
1093
- reselect: async ({ context }, { dispatch, read } = {}) => ANSWER
1223
+ cancel: async ({ context }, { read, shopify } = {}) => ANSWER,
1224
+ // NOT A MERCHANT ACTION EITHER one attributed order's usage charge,
1225
+ // sent to the vendor's meter. The credential pair rides in as props
1226
+ // because the charge authenticates as the APP, not as the store.
1227
+ charge: async ({ clientId, clientSecret, context, manifest }, { shopify } = {}) => ANSWER,
1228
+ // `mark` is the one write a description cannot carry: the marker must
1229
+ // be persisted BEFORE the approval is released, and a described write
1230
+ // lands after the hook returns.
1231
+ reselect: async ({ context }, { mark, read, shopify } = {}) => ANSWER,
1232
+ // NOT A MERCHANT ACTION — the question "is this store's billing
1233
+ // actually metered right now", asked by the daily health check and by
1234
+ // the vendor's own approval webhook, which used to hand-copy it.
1235
+ verify: async ({ context }, { adminToken, read, shopify } = {}) => ANSWER
1094
1236
  },
1095
1237
  // The embedded app's own session, stored by us on the vendor's behalf.
1096
1238
  session: {
@@ -1576,16 +1718,19 @@ var attentive_default2 = {
1576
1718
  "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.",
1577
1719
  "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."
1578
1720
  ],
1579
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
1580
- // The dashboard already carries generic reasons for every way an
1581
- // authorization can fail — declined, expired state, a vendor we are not set
1582
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
1583
- // failures need saying differently. This one's do not.
1721
+ // WHAT THE MERCHANT READS WHEN A CONNECT FAILS. Two states, because the
1722
+ // consent screen has two ways to end: they said no, or something between
1723
+ // here and the vendor went wrong.
1584
1724
  //
1585
- // Answered rather than omitted, because `errors` existed on two of six
1586
- // manifests and there was no way to tell "nothing to add" from "nobody
1587
- // wrote it".
1588
- errors: false,
1725
+ // THE VENDOR IS NAMED IN BOTH. The dashboard's generic copy says "the
1726
+ // authorization"; a merchant connecting two accounts in one sitting needs
1727
+ // to know which one this was.
1728
+ errors: {
1729
+ connect: {
1730
+ denied: "The Attentive authorization was declined, so nothing was connected.",
1731
+ invalid: "We couldn't complete the Attentive connection. Try connecting again."
1732
+ }
1733
+ },
1589
1734
  excerpt: "Sync your Drawbridge contacts into an Attentive segment.",
1590
1735
  // NAMES THE SEGMENT STEP, because `status` below gates on it: a grant with
1591
1736
  // no segment chosen sits at Pending, and a guide that stops at the consent
@@ -2113,6 +2258,15 @@ var readEventHeader = ({ descriptor, headers }) => ({ result: { event: headers[d
2113
2258
  var DEFAULT_TIMEOUT_MS = 15e3;
2114
2259
  var request = async ({
2115
2260
  body,
2261
+ // THE TRANSPORT, injectable and defaulted to the real one.
2262
+ //
2263
+ // Every other vendor client in this package takes a `fetcher` — it is how
2264
+ // klaviyo, mailchimp and attentive are tested without a network, and it is a
2265
+ // declared HOOK_OPTION. The Shopify client had no seam at all, so the only way
2266
+ // to test a hook that used it was to inject the whole SDK namespace; that
2267
+ // injection existed to work around an import cycle, and when the cycle went
2268
+ // the tests lost their only hold. This is the seam they should have had.
2269
+ fetcher = fetch,
2116
2270
  headers = {},
2117
2271
  method = "GET",
2118
2272
  query,
@@ -2126,7 +2280,7 @@ var request = async ({
2126
2280
  }
2127
2281
  ;
2128
2282
  const isForm = type === "form";
2129
- const response = await fetch(fullUrl.toString(), {
2283
+ const response = await fetcher(fullUrl.toString(), {
2130
2284
  method,
2131
2285
  headers: {
2132
2286
  "Content-Type": isForm ? "application/x-www-form-urlencoded" : "application/json",
@@ -2583,15 +2737,12 @@ var drawbridge_default2 = {
2583
2737
  description: [
2584
2738
  "Drawbridge sends your notification emails and your entrants' emails, and recalculates segment membership on a schedule. It is always on and needs nothing connected."
2585
2739
  ],
2586
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
2587
- // The dashboard already carries generic reasons for every way an
2588
- // authorization can fail declined, expired state, a vendor we are not set
2589
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
2590
- // failures need saying differently. This one's do not.
2740
+ // NOTHING IS EVER CONNECTED, so no connect can fail. This is the platform's
2741
+ // own manifest always on, private, never in the catalogue — and it exists
2742
+ // to give Drawbridge's own steps a hook to point at. `denied` and `invalid`
2743
+ // describe a consent screen this connection does not have.
2591
2744
  //
2592
- // Answered rather than omitted, because `errors` existed on two of six
2593
- // manifests and there was no way to tell "nothing to add" from "nobody
2594
- // wrote it".
2745
+ // `false` is the recorded decision, not silence.
2595
2746
  errors: false,
2596
2747
  excerpt: "The steps Drawbridge runs itself.",
2597
2748
  guide: [
@@ -3351,10 +3502,10 @@ var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
3351
3502
 
3352
3503
  // lib/connections/scopes.js
3353
3504
  var list = (value) => (Array.isArray(value) ? value.flatMap((entry) => String(entry).split(/\s+/)) : String(value ?? "").split(/\s+/)).map((entry) => entry.trim()).filter(Boolean);
3354
- var missingScopes = ({ granted, required }) => {
3505
+ var missingScopes = ({ granted, required: required2 }) => {
3355
3506
  if (granted === null || granted === void 0 || granted === "") return null;
3356
3507
  const held = new Set(list(granted));
3357
- return list(required).filter((scope) => !held.has(scope));
3508
+ return list(required2).filter((scope) => !held.has(scope));
3358
3509
  };
3359
3510
 
3360
3511
  // lib/connections/manifests/klaviyo.js
@@ -4253,16 +4404,19 @@ var mailchimp_default2 = {
4253
4404
  "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.",
4254
4405
  "Someone who unsubscribed inside Mailchimp keeps that choice: a resync only sets the status of a subscriber Mailchimp has never seen before."
4255
4406
  ],
4256
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
4257
- // The dashboard already carries generic reasons for every way an
4258
- // authorization can fail — declined, expired state, a vendor we are not set
4259
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
4260
- // failures need saying differently. This one's do not.
4407
+ // WHAT THE MERCHANT READS WHEN A CONNECT FAILS. Two states, because the
4408
+ // consent screen has two ways to end: they said no, or something between
4409
+ // here and the vendor went wrong.
4261
4410
  //
4262
- // Answered rather than omitted, because `errors` existed on two of six
4263
- // manifests and there was no way to tell "nothing to add" from "nobody
4264
- // wrote it".
4265
- errors: false,
4411
+ // THE VENDOR IS NAMED IN BOTH. The dashboard's generic copy says "the
4412
+ // authorization"; a merchant connecting two accounts in one sitting needs
4413
+ // to know which one this was.
4414
+ errors: {
4415
+ connect: {
4416
+ denied: "The Mailchimp authorization was declined, so nothing was connected.",
4417
+ invalid: "We couldn't complete the Mailchimp connection. Try connecting again."
4418
+ }
4419
+ },
4266
4420
  excerpt: "Sync your Drawbridge contacts into a Mailchimp audience.",
4267
4421
  // NAMES THE AUDIENCE STEP, because `status` below gates on it: a grant with
4268
4422
  // no audience chosen sits at Pending, and a guide that stops at the consent
@@ -4361,7 +4515,7 @@ var mailchimp_default2 = {
4361
4515
  if (!audience) return { message: "No Mailchimp audience is chosen for this connection.", request: request2, skipped: true };
4362
4516
  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);
4363
4517
  if (!email) return { message: "That lead has no email address to sync.", request: request2, skipped: true };
4364
- const hash = subscriberHash(email);
4518
+ const hash2 = subscriberHash(email);
4365
4519
  const [firstName, ...restOfName] = String((lead == null ? void 0 : lead.name) || "").trim().split(/\s+/).filter(Boolean);
4366
4520
  const lastName = restOfName.join(" ");
4367
4521
  const phone = ((_e = lead == null ? void 0 : lead.phone) == null ? void 0 : _e.number) || null;
@@ -4370,7 +4524,7 @@ var mailchimp_default2 = {
4370
4524
  ...lastName && { LNAME: lastName },
4371
4525
  ...phone && { PHONE: phone }
4372
4526
  };
4373
- const member = await api3("/lists/" + audience + "/members/" + hash, {
4527
+ const member = await api3("/lists/" + audience + "/members/" + hash2, {
4374
4528
  dc: settings == null ? void 0 : settings.dc,
4375
4529
  fetcher,
4376
4530
  method: "PUT",
@@ -4411,7 +4565,7 @@ var mailchimp_default2 = {
4411
4565
  status: joined.has(entry.id) ? "active" : "inactive"
4412
4566
  }));
4413
4567
  if (tags.length > 0) {
4414
- await api3("/lists/" + audience + "/members/" + hash + "/tags", {
4568
+ await api3("/lists/" + audience + "/members/" + hash2 + "/tags", {
4415
4569
  dc: settings == null ? void 0 : settings.dc,
4416
4570
  fetcher,
4417
4571
  method: "POST",
@@ -4422,12 +4576,12 @@ var mailchimp_default2 = {
4422
4576
  }
4423
4577
  return {
4424
4578
  // Merged into `context` for later steps in this run.
4425
- context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash },
4579
+ context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash2 },
4426
4580
  message: suppressed ? "Synced to Mailchimp as unsubscribed \u2014 this contact has opted out." : "Synced to the Mailchimp audience.",
4427
4581
  request: request2,
4428
4582
  // Recorded on the run for support to read back, not a write
4429
4583
  // instruction — the hook has already written what it needed to.
4430
- response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash }
4584
+ response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash2 }
4431
4585
  };
4432
4586
  }
4433
4587
  },
@@ -4797,167 +4951,2058 @@ var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
4797
4951
  <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"/>
4798
4952
  </svg>`;
4799
4953
 
4800
- // lib/email.js
4801
- var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
4802
- var toCanonicalEmail = (value) => {
4803
- if (!value || typeof value !== "string") return null;
4804
- const email = value.trim().toLowerCase();
4805
- const at = email.lastIndexOf("@");
4806
- if (at < 1 || at === email.length - 1) return null;
4807
- let local = email.slice(0, at);
4808
- const domain = email.slice(at + 1);
4809
- const plus = local.indexOf("+");
4810
- if (plus > 0) local = local.slice(0, plus);
4811
- if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
4812
- if (!local) return null;
4813
- return local + "@" + domain;
4814
- };
4954
+ // lib/shopify/admin.js
4955
+ var admin_exports = {};
4956
+ __export(admin_exports, {
4957
+ adminFetch: () => adminFetch,
4958
+ createDiscountCode: () => createDiscountCode,
4959
+ createUsageRecord: () => createUsageRecord,
4960
+ createUsageSubscription: () => createUsageSubscription,
4961
+ getActiveAppSubscriptions: () => getActiveAppSubscriptions,
4962
+ getDiscounts: () => getDiscounts,
4963
+ getOrCreateCustomer: () => getOrCreateCustomer,
4964
+ getProductInventory: () => getProductInventory,
4965
+ sendProductResourceFeedback: () => sendProductResourceFeedback
4966
+ });
4815
4967
 
4816
- // lib/encrypt.js
4817
- import crypto from "crypto";
4818
- var ALGORITHM = "aes-256-gcm";
4819
- var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
4820
- var decrypt = (value) => {
4821
- if (typeof value !== "string") return value;
4822
- const [ivHex, tagHex, dataHex] = value.split(":");
4823
- const decipher = crypto.createDecipheriv(
4824
- ALGORITHM,
4825
- getKey(),
4826
- Buffer.from(ivHex, "hex")
4827
- );
4828
- decipher.setAuthTag(Buffer.from(tagHex, "hex"));
4829
- const result = Buffer.concat([
4830
- decipher.update(Buffer.from(dataHex, "hex")),
4831
- decipher.final()
4832
- ]);
4833
- return JSON.parse(result.toString("utf8"));
4834
- };
4968
+ // lib/shopify/constants.js
4969
+ var SHOPIFY_STOREFRONT_API_VERSION = "2025-01";
4970
+ var SHOPIFY_ADMIN_API_VERSION = "2026-04";
4971
+ var SHOPIFY_APP_API_VERSION = "unstable";
4972
+ var SHOPIFY_REQUIRED_SCOPES = [
4973
+ "read_customers",
4974
+ "write_customers",
4975
+ "read_discounts",
4976
+ "write_discounts",
4977
+ "read_orders",
4978
+ "read_products",
4979
+ "read_publications",
4980
+ "write_resource_feedbacks",
4981
+ "unauthenticated_read_checkouts",
4982
+ "unauthenticated_read_product_inventory",
4983
+ "unauthenticated_read_product_listings",
4984
+ "unauthenticated_write_checkouts"
4985
+ ];
4986
+ var REFRESH_TOKEN_LIFETIME_MS = 90 * 24 * 60 * 60 * 1e3;
4987
+ var ACCESS_TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1e3;
4988
+ var PARTNER_API_VERSION = process.env.SHOPIFY_PARTNER_API_VERSION || "2026-07";
4835
4989
 
4836
- // lib/slugify.js
4837
- import slug from "slugify";
4838
- var slugify = (value, nochars = false) => {
4839
- const remove = nochars ? /[-?*+~.()'"!:@#^_{}\[\];,/\\]/g : /[?*+~.()'"!:@#^_{}\[\];,/\\]/g;
4840
- const replacement = nochars ? "" : "-";
4841
- return slug(
4842
- value,
4843
- {
4844
- remove,
4845
- replacement,
4846
- lower: true,
4847
- trim: true
4990
+ // lib/shopify/admin.js
4991
+ var adminUrl = (domain) => `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}`;
4992
+ var adminFetch = async ({ adminAccessToken, domain, fetcher, query, variables }) => {
4993
+ var _a;
4994
+ const { data, errors } = await request({
4995
+ fetcher,
4996
+ method: "POST",
4997
+ url: adminUrl(domain) + "/graphql.json",
4998
+ headers: {
4999
+ "X-Shopify-Access-Token": adminAccessToken
5000
+ },
5001
+ body: {
5002
+ query,
5003
+ ...variables && { variables }
4848
5004
  }
4849
- );
5005
+ });
5006
+ if (errors) {
5007
+ throw new Error("Shopify GraphQL error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
5008
+ }
5009
+ ;
5010
+ return data;
4850
5011
  };
4851
-
4852
- // lib/connections/manifests/shopify.js
4853
- var toLine = ({
4854
- price,
4855
- product_id: productId,
4856
- quantity,
4857
- title,
4858
- variant_id: variantId,
4859
- variant_title: variantTitle
4860
- }) => ({
4861
- price: parseFloat(price) || 0,
4862
- productId: productId ? "gid://shopify/Product/" + productId : null,
4863
- quantity: quantity || 1,
4864
- title: title || null,
4865
- variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
4866
- variantTitle: variantTitle || null
4867
- });
4868
- var attributeLineItems = (lineItems = []) => lineItems.reduce(
4869
- (acc, item) => {
4870
- const attrs = (item.properties || []).reduce(
4871
- (map, { name, value }) => {
4872
- map[name] = value;
4873
- return map;
4874
- },
4875
- {}
4876
- );
4877
- if (!attrs["_drwbrdg_ca"]) return acc;
4878
- if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
4879
- const line = toLine(item);
4880
- acc.attributedGross += line.price * line.quantity;
4881
- acc.attributedLines.push(line);
4882
- return acc;
4883
- },
4884
- { attrMap: {}, attributedGross: 0, attributedLines: [] }
4885
- );
4886
- var generateDiscountCode = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
4887
- var blockedReason = (discount) => {
4888
- var _a;
4889
- if ((discount == null ? void 0 : discount.status) === "EXPIRED") return "This discount has expired.";
4890
- const buyers = (_a = discount == null ? void 0 : discount.context) == null ? void 0 : _a.__typename;
4891
- if (buyers && buyers !== "DiscountBuyerSelectionAll") {
4892
- 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.";
5012
+ var DISCOUNT_FIELDS = `
5013
+ title
5014
+ status
5015
+ startsAt
5016
+ endsAt
5017
+ usageLimit
5018
+ asyncUsageCount
5019
+ appliesOncePerCustomer
5020
+ context { __typename }
5021
+ `;
5022
+ var discountsQuery = (search, cursor, limit) => `{
5023
+ codeDiscountNodes(first: ${limit}${search ? `, query: "title:*${search}*"` : ""}${cursor ? `, after: "${cursor}"` : ""}) {
5024
+ edges {
5025
+ node {
5026
+ id
5027
+ codeDiscount {
5028
+ ... on DiscountCodeBasic { ${DISCOUNT_FIELDS} }
5029
+ ... on DiscountCodeBxgy { ${DISCOUNT_FIELDS} }
5030
+ ... on DiscountCodeFreeShipping { ${DISCOUNT_FIELDS} }
5031
+ ... on DiscountCodeApp { ${DISCOUNT_FIELDS} }
5032
+ }
5033
+ }
5034
+ }
5035
+ pageInfo {
5036
+ endCursor
5037
+ hasNextPage
5038
+ hasPreviousPage
5039
+ startCursor
5040
+ }
5041
+ }
5042
+ }`;
5043
+ var getDiscounts = async ({ fetcher, adminAccessToken, domain, search, cursor, limit }) => {
5044
+ const data = await adminFetch({
5045
+ fetcher,
5046
+ adminAccessToken,
5047
+ domain,
5048
+ query: discountsQuery(search, cursor, limit)
5049
+ });
5050
+ return data == null ? void 0 : data.codeDiscountNodes;
5051
+ };
5052
+ var discountGid = (id) => String(id).startsWith("gid://") ? String(id) : "gid://shopify/DiscountCodeNode/" + id;
5053
+ var createDiscountCode = async ({ fetcher, adminAccessToken, domain, discountId, code }) => {
5054
+ var _a, _b, _c, _d, _e, _f, _g, _h;
5055
+ const added = await adminFetch({
5056
+ fetcher,
5057
+ adminAccessToken,
5058
+ domain,
5059
+ query: `
5060
+ mutation DiscountRedeemCodeBulkAdd($discountId: ID!, $codes: [DiscountRedeemCodeInput!]!) {
5061
+ discountRedeemCodeBulkAdd(discountId: $discountId, codes: $codes) {
5062
+ bulkCreation {
5063
+ id
5064
+ }
5065
+ userErrors {
5066
+ field
5067
+ message
5068
+ }
5069
+ }
5070
+ }
5071
+ `,
5072
+ variables: {
5073
+ codes: [{ code }],
5074
+ discountId: discountGid(discountId)
5075
+ }
5076
+ });
5077
+ const addErrors = (_a = added == null ? void 0 : added.discountRedeemCodeBulkAdd) == null ? void 0 : _a.userErrors;
5078
+ if (addErrors == null ? void 0 : addErrors.length) {
5079
+ throw new Error("Shopify discount code create failed: " + addErrors[0].message);
4893
5080
  }
4894
5081
  ;
4895
- if (typeof (discount == null ? void 0 : discount.usageLimit) === "number" && discount.usageLimit > 0 && ((discount == null ? void 0 : discount.asyncUsageCount) || 0) >= discount.usageLimit) {
4896
- return "This discount has reached its total usage limit.";
5082
+ const bulkCreationId = (_c = (_b = added == null ? void 0 : added.discountRedeemCodeBulkAdd) == null ? void 0 : _b.bulkCreation) == null ? void 0 : _c.id;
5083
+ if (!bulkCreationId) {
5084
+ throw new Error("Shopify discount code create failed: no bulk creation id returned");
4897
5085
  }
4898
5086
  ;
4899
- return null;
5087
+ for (let attempt = 0; attempt < 15; attempt++) {
5088
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
5089
+ const polled = await adminFetch({
5090
+ fetcher,
5091
+ adminAccessToken,
5092
+ domain,
5093
+ query: `
5094
+ query DiscountRedeemCodeBulkCreationPoll($id: ID!) {
5095
+ discountRedeemCodeBulkCreation(id: $id) {
5096
+ done
5097
+ codes(first: 1) {
5098
+ nodes {
5099
+ code
5100
+ discountRedeemCode {
5101
+ id
5102
+ }
5103
+ errors {
5104
+ message
5105
+ }
5106
+ }
5107
+ }
5108
+ }
5109
+ }
5110
+ `,
5111
+ variables: {
5112
+ id: bulkCreationId
5113
+ }
5114
+ });
5115
+ const creation = polled == null ? void 0 : polled.discountRedeemCodeBulkCreation;
5116
+ if (!(creation == null ? void 0 : creation.done)) continue;
5117
+ const node = (_e = (_d = creation.codes) == null ? void 0 : _d.nodes) == null ? void 0 : _e[0];
5118
+ if (!((_f = node == null ? void 0 : node.discountRedeemCode) == null ? void 0 : _f.id)) {
5119
+ 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"));
5120
+ }
5121
+ ;
5122
+ return {
5123
+ code: node.code,
5124
+ // Numeric tail keeps the stored shopifyDiscountId in the shape the
5125
+ // legacy REST endpoint returned — it feeds a merchant-visible
5126
+ // workflow template variable, so no gid:// leakage.
5127
+ id: node.discountRedeemCode.id.split("/").pop()
5128
+ };
5129
+ }
5130
+ ;
5131
+ throw new Error("Shopify discount code create timed out waiting for bulk creation " + bulkCreationId);
4900
5132
  };
4901
- var discountWarning = (discount) => {
4902
- if ((discount == null ? void 0 : discount.status) === "SCHEDULED") {
4903
- return "This discount hasn't started yet, so codes issued before it does won't work until then.";
5133
+ var getOrCreateCustomer = async ({ fetcher, adminAccessToken, domain, email, firstName, lastName, source }) => {
5134
+ var _a, _b, _c, _d, _e, _f, _g, _h;
5135
+ const lookupQuery = `
5136
+ query customerByEmail( $query : String! ) {
5137
+ customers( first : 1, query : $query ) {
5138
+ edges {
5139
+ node {
5140
+ id
5141
+ }
5142
+ }
5143
+ }
5144
+ }
5145
+ `;
5146
+ const data = await adminFetch({
5147
+ fetcher,
5148
+ adminAccessToken,
5149
+ domain,
5150
+ query: lookupQuery,
5151
+ variables: { query: "email:" + email }
5152
+ });
5153
+ const existing = (_c = (_b = (_a = data == null ? void 0 : data.customers) == null ? void 0 : _a.edges) == null ? void 0 : _b[0]) == null ? void 0 : _c.node;
5154
+ if (existing) return existing;
5155
+ const input = { email };
5156
+ if (firstName) input.firstName = firstName;
5157
+ if (lastName) input.lastName = lastName;
5158
+ if (source) {
5159
+ input.metafields = [{
5160
+ namespace: "drwbrdg",
5161
+ key: "source",
5162
+ type: "single_line_text_field",
5163
+ value: source
5164
+ }];
4904
5165
  }
4905
5166
  ;
4906
- if (discount == null ? void 0 : discount.appliesOncePerCustomer) return "Each customer can use this discount only once.";
4907
- return null;
5167
+ const result = await adminFetch({
5168
+ fetcher,
5169
+ adminAccessToken,
5170
+ domain,
5171
+ query: `
5172
+ mutation customerCreate( $input : CustomerInput! ) {
5173
+ customerCreate( input : $input ) {
5174
+ customer {
5175
+ id
5176
+ }
5177
+ userErrors {
5178
+ field
5179
+ message
5180
+ }
5181
+ }
5182
+ }
5183
+ `,
5184
+ variables: { input }
5185
+ });
5186
+ const userErrors = (_d = result == null ? void 0 : result.customerCreate) == null ? void 0 : _d.userErrors;
5187
+ if (userErrors == null ? void 0 : userErrors.length) {
5188
+ const emailTaken = userErrors.some((e) => {
5189
+ var _a2;
5190
+ return (_a2 = e.message) == null ? void 0 : _a2.includes("Email has already been taken");
5191
+ });
5192
+ if (emailTaken) {
5193
+ const retry = await adminFetch({
5194
+ fetcher,
5195
+ adminAccessToken,
5196
+ domain,
5197
+ query: lookupQuery,
5198
+ variables: { query: "email:" + email }
5199
+ });
5200
+ 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;
5201
+ if (found) return found;
5202
+ }
5203
+ ;
5204
+ throw new Error("Shopify customer create failed: " + userErrors[0].message);
5205
+ }
5206
+ ;
5207
+ return (_h = result == null ? void 0 : result.customerCreate) == null ? void 0 : _h.customer;
4908
5208
  };
4909
- var ORDER_EVENT_HANDLE = slugify("drawbridge-orders");
4910
- var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
4911
- var OAUTH_ERROR_SOURCE = "oauth";
4912
- var BILLING_ERROR_SOURCE = "billing";
4913
- var BILLING_ERROR_MESSAGE = "Order billing isn't set up for this store \u2014 reselect and approve the plan from the Shopify connection page.";
4914
- var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
4915
- var inbound = {
4916
- headers: {
4917
- event: "x-shopify-topic",
4918
- id: "x-shopify-webhook-id",
4919
- shop: "x-shopify-shop-domain",
4920
- signature: "x-shopify-hmac-sha256"
4921
- },
4922
- signature: {
4923
- algorithm: "sha256",
4924
- encoding: "base64",
4925
- secret: "SHOPIFY_API_SECRET"
5209
+ var getActiveAppSubscriptions = async ({ fetcher, adminAccessToken, domain }) => {
5210
+ var _a, _b;
5211
+ const data = await adminFetch({
5212
+ fetcher,
5213
+ adminAccessToken,
5214
+ domain,
5215
+ query: `{
5216
+ currentAppInstallation {
5217
+ activeSubscriptions {
5218
+ id
5219
+ name
5220
+ status
5221
+ test
5222
+ lineItems {
5223
+ id
5224
+ plan {
5225
+ pricingDetails {
5226
+ __typename
5227
+ }
5228
+ }
5229
+ }
5230
+ }
5231
+ }
5232
+ shop {
5233
+ myshopifyDomain
5234
+ }
5235
+ }`
5236
+ });
5237
+ return {
5238
+ shopDomain: ((_a = data == null ? void 0 : data.shop) == null ? void 0 : _a.myshopifyDomain) || null,
5239
+ subscriptions: (((_b = data == null ? void 0 : data.currentAppInstallation) == null ? void 0 : _b.activeSubscriptions) || []).map((subscription) => {
5240
+ var _a2;
5241
+ return {
5242
+ ...subscription,
5243
+ metered: ((subscription == null ? void 0 : subscription.lineItems) || []).some(
5244
+ (item) => {
5245
+ var _a3, _b2;
5246
+ return ((_b2 = (_a3 = item == null ? void 0 : item.plan) == null ? void 0 : _a3.pricingDetails) == null ? void 0 : _b2.__typename) === "AppUsagePricing";
5247
+ }
5248
+ ),
5249
+ // The usage line's own id — the address appUsageRecordCreate charges
5250
+ // against. Null when the approval carries no usage component.
5251
+ usageLineItemId: ((_a2 = ((subscription == null ? void 0 : subscription.lineItems) || []).find(
5252
+ (item) => {
5253
+ var _a3, _b2;
5254
+ return ((_b2 = (_a3 = item == null ? void 0 : item.plan) == null ? void 0 : _a3.pricingDetails) == null ? void 0 : _b2.__typename) === "AppUsagePricing";
5255
+ }
5256
+ )) == null ? void 0 : _a2.id) || null
5257
+ };
5258
+ })
5259
+ };
5260
+ };
5261
+ var createUsageSubscription = async ({ fetcher, adminAccessToken, cappedAmount, currencyCode = "USD", domain, name, recurringPrice = 0, returnUrl, terms, test = false }) => {
5262
+ if (!name || !returnUrl || !terms || !(Number(cappedAmount) > 0)) {
5263
+ throw new Error("createUsageSubscription requires name, returnUrl, terms, and a positive cappedAmount");
5264
+ }
5265
+ ;
5266
+ const data = await adminFetch({
5267
+ fetcher,
5268
+ adminAccessToken,
5269
+ domain,
5270
+ query: `mutation createUsageSubscription( $lineItems : [AppSubscriptionLineItemInput!]!, $name : String!, $returnUrl : URL!, $test : Boolean ) {
5271
+ appSubscriptionCreate( lineItems : $lineItems, name : $name, returnUrl : $returnUrl, test : $test ) {
5272
+ appSubscription { id name status test lineItems { id plan { pricingDetails { __typename } } } }
5273
+ confirmationUrl
5274
+ userErrors { field message }
5275
+ }
5276
+ }`,
5277
+ variables: {
5278
+ lineItems: [
5279
+ {
5280
+ plan: {
5281
+ appRecurringPricingDetails: {
5282
+ interval: "EVERY_30_DAYS",
5283
+ price: { amount: Number(recurringPrice), currencyCode }
5284
+ }
5285
+ }
5286
+ },
5287
+ {
5288
+ plan: {
5289
+ appUsagePricingDetails: {
5290
+ cappedAmount: { amount: Number(cappedAmount), currencyCode },
5291
+ terms
5292
+ }
5293
+ }
5294
+ }
5295
+ ],
5296
+ name,
5297
+ returnUrl,
5298
+ test
5299
+ }
5300
+ });
5301
+ const payload = data == null ? void 0 : data.appSubscriptionCreate;
5302
+ const userErrors = (payload == null ? void 0 : payload.userErrors) || [];
5303
+ if (userErrors.length) {
5304
+ throw new Error("Shopify subscription create failed: " + userErrors.map((entry) => entry.message).join("; "));
5305
+ }
5306
+ ;
5307
+ if (!(payload == null ? void 0 : payload.confirmationUrl)) {
5308
+ throw new Error("Shopify subscription create failed: no confirmation url returned");
4926
5309
  }
5310
+ ;
5311
+ return {
5312
+ confirmationUrl: payload.confirmationUrl,
5313
+ subscription: payload.appSubscription
5314
+ };
4927
5315
  };
4928
- var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
4929
- "customers/data_request",
4930
- "customers/redact",
4931
- "shop/redact"
4932
- ]);
4933
- var shopify_default2 = {
4934
- // THE WORDS ON THE BUTTONS. `listing` was `content.redirect.title`, which put
4935
- // a BUTTON LABEL inside the copy object next to a url — the title and the
4936
- // address it belongs to sat at different levels and could drift apart.
4937
- //
4938
- // It names where the link GOES rather than what it does: installing happens on
4939
- // the App Store listing, and the dashboard must never imply a store can be
4940
- // linked from inside it.
4941
- actions: {
4942
- create: null,
4943
- listing: "View on the Shopify App Store",
4944
- manage: null,
4945
- update: null
4946
- },
4947
- // INSTALL, not oauth. The grant is an OAuth grant, but the merchant never
4948
- // sees a consent screen we sent them to -- they start at the App Store, and
4949
- // the install completes inside Shopify admin without redirecting back. A
4950
- // Connect button here would be lying about where connecting happens.
4951
- auth: {
4952
- // ONE STORE PER ORGANIZATION. A Shopify install IS a store, and a second
4953
- // one would give an organization two catalogues, two order streams and two
4954
- // usage meters with nothing to say which is authoritative.
4955
- //
4956
- // DECLARED AND ENFORCED BY NOTHING, measured 2026-09-13: no repo reads this
4957
- // key, and the connection collection's { organization, slug } index is not
4958
- // unique. So a second Shopify connection would be accepted today. The gate
4959
- // belongs at the connect route with a unique partial index behind it, and
4960
- // that is api work — this is the declaration it will read.
5316
+ var createUsageRecord = async ({ fetcher, adminAccessToken, amount, currencyCode = "USD", description, domain, idempotencyKey, subscriptionLineItemId }) => {
5317
+ var _a;
5318
+ if (!subscriptionLineItemId || !description || !(Number(amount) > 0)) {
5319
+ throw new Error("createUsageRecord requires subscriptionLineItemId, description, and a positive amount");
5320
+ }
5321
+ ;
5322
+ const data = await adminFetch({
5323
+ fetcher,
5324
+ adminAccessToken,
5325
+ domain,
5326
+ query: `mutation createUsageRecord( $description : String!, $idempotencyKey : String, $price : MoneyInput!, $subscriptionLineItemId : ID! ) {
5327
+ appUsageRecordCreate( description : $description, idempotencyKey : $idempotencyKey, price : $price, subscriptionLineItemId : $subscriptionLineItemId ) {
5328
+ appUsageRecord { id }
5329
+ userErrors { field message }
5330
+ }
5331
+ }`,
5332
+ variables: {
5333
+ description,
5334
+ idempotencyKey: idempotencyKey ? String(idempotencyKey) : null,
5335
+ price: { amount: Number(amount), currencyCode },
5336
+ subscriptionLineItemId
5337
+ }
5338
+ });
5339
+ const payload = data == null ? void 0 : data.appUsageRecordCreate;
5340
+ const userErrors = (payload == null ? void 0 : payload.userErrors) || [];
5341
+ if (userErrors.length || !((_a = payload == null ? void 0 : payload.appUsageRecord) == null ? void 0 : _a.id)) {
5342
+ throw new Error("Shopify usage record failed: " + (userErrors.map((entry) => entry.message).join("; ") || "no record returned"));
5343
+ }
5344
+ ;
5345
+ return { id: payload.appUsageRecord.id };
5346
+ };
5347
+ var getProductInventory = async ({ fetcher, adminAccessToken, domain, productId }) => {
5348
+ var _a, _b;
5349
+ const data = await adminFetch({
5350
+ fetcher,
5351
+ adminAccessToken,
5352
+ domain,
5353
+ query: `{
5354
+ product( id : "${productId}" ) {
5355
+ variants( first : 100 ) {
5356
+ edges {
5357
+ node {
5358
+ id
5359
+ inventoryQuantity
5360
+ }
5361
+ }
5362
+ }
5363
+ }
5364
+ }`
5365
+ });
5366
+ const edges = ((_b = (_a = data == null ? void 0 : data.product) == null ? void 0 : _a.variants) == null ? void 0 : _b.edges) || [];
5367
+ return edges.reduce((accumulator, edge) => {
5368
+ var _a2, _b2;
5369
+ const id = (_a2 = edge == null ? void 0 : edge.node) == null ? void 0 : _a2.id;
5370
+ const quantity = (_b2 = edge == null ? void 0 : edge.node) == null ? void 0 : _b2.inventoryQuantity;
5371
+ if (id) {
5372
+ accumulator[id] = Number.isFinite(quantity) ? quantity : 0;
5373
+ }
5374
+ ;
5375
+ return accumulator;
5376
+ }, {});
5377
+ };
5378
+ var getProductUpdatedAt = async ({ adminAccessToken, domain, fetcher, productId }) => {
5379
+ var _a;
5380
+ const data = await adminFetch({
5381
+ fetcher,
5382
+ adminAccessToken,
5383
+ domain,
5384
+ query: `
5385
+ query ProductUpdatedAt($id: ID!) {
5386
+ product(id: $id) {
5387
+ updatedAt
5388
+ }
5389
+ }
5390
+ `,
5391
+ variables: { id: productId }
5392
+ });
5393
+ return ((_a = data == null ? void 0 : data.product) == null ? void 0 : _a.updatedAt) || null;
5394
+ };
5395
+ var NOT_ON_CHANNEL = "not available to the channel";
5396
+ var OUTDATED_FEEDBACK = "later version";
5397
+ var sendProductResourceFeedback = async ({ fetcher, adminAccessToken, domain, productId, state, messages = [] }) => {
5398
+ var _a, _b, _c;
5399
+ const productUpdatedAt = await getProductUpdatedAt({ adminAccessToken, domain, fetcher, productId });
5400
+ if (!productUpdatedAt) return null;
5401
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5402
+ const submit = async (version) => {
5403
+ const data = await adminFetch({
5404
+ fetcher,
5405
+ adminAccessToken,
5406
+ domain,
5407
+ query: `
5408
+ mutation ProductFeedback($feedbackInput: [ProductResourceFeedbackInput!]!) {
5409
+ bulkProductResourceFeedbackCreate(feedbackInput: $feedbackInput) {
5410
+ feedback {
5411
+ productId
5412
+ state
5413
+ }
5414
+ userErrors {
5415
+ field
5416
+ message
5417
+ }
5418
+ }
5419
+ }
5420
+ `,
5421
+ variables: {
5422
+ feedbackInput: [
5423
+ {
5424
+ productId,
5425
+ state,
5426
+ feedbackGeneratedAt: now,
5427
+ productUpdatedAt: version,
5428
+ messages
5429
+ }
5430
+ ]
5431
+ }
5432
+ });
5433
+ return data == null ? void 0 : data.bulkProductResourceFeedbackCreate;
5434
+ };
5435
+ let result = await submit(productUpdatedAt);
5436
+ if ((((_b = (_a = result == null ? void 0 : result.userErrors) == null ? void 0 : _a[0]) == null ? void 0 : _b.message) || "").toLowerCase().includes(OUTDATED_FEEDBACK)) {
5437
+ result = await submit(now);
5438
+ }
5439
+ ;
5440
+ const feedbackErrors = result == null ? void 0 : result.userErrors;
5441
+ if (feedbackErrors == null ? void 0 : feedbackErrors.length) {
5442
+ const message = feedbackErrors[0].message || "";
5443
+ if (message.toLowerCase().includes(NOT_ON_CHANNEL)) return null;
5444
+ throw new Error("Shopify product feedback failed: " + message);
5445
+ }
5446
+ ;
5447
+ return ((_c = result == null ? void 0 : result.feedback) == null ? void 0 : _c[0]) || null;
5448
+ };
5449
+
5450
+ // lib/shopify/billing.js
5451
+ var billing_exports = {};
5452
+ __export(billing_exports, {
5453
+ sendAppEvent: () => sendAppEvent
5454
+ });
5455
+ var APP_API = "https://api.shopify.com";
5456
+ var APP_API_VERSION = process.env.SHOPIFY_APP_API_VERSION || SHOPIFY_APP_API_VERSION;
5457
+ var cachedTokens = {};
5458
+ var fetchAppToken = async ({ clientId, clientSecret, fetcher }) => {
5459
+ const data = await request({
5460
+ fetcher,
5461
+ method: "POST",
5462
+ url: APP_API + "/auth/access_token",
5463
+ body: {
5464
+ client_id: clientId,
5465
+ client_secret: clientSecret,
5466
+ grant_type: "client_credentials"
5467
+ }
5468
+ });
5469
+ if (!(data == null ? void 0 : data.access_token)) {
5470
+ throw new Error("Shopify app token request failed: no access token returned");
5471
+ }
5472
+ ;
5473
+ const ttl = data.expires_in ? data.expires_in * 1e3 : 60 * 60 * 1e3;
5474
+ cachedTokens[clientId] = {
5475
+ expiresAt: Date.now() + ttl - 60 * 1e3,
5476
+ token: data.access_token
5477
+ };
5478
+ return data.access_token;
5479
+ };
5480
+ var getAppToken = async ({ clientId, clientSecret, fetcher }) => {
5481
+ const cached = cachedTokens[clientId];
5482
+ if (cached && cached.expiresAt > Date.now()) {
5483
+ return cached.token;
5484
+ }
5485
+ ;
5486
+ return fetchAppToken({ clientId, clientSecret, fetcher });
5487
+ };
5488
+ var toShopGid = (shopId) => String(shopId).startsWith("gid://") ? String(shopId) : "gid://shopify/Shop/" + shopId;
5489
+ var sendAppEvent = async ({ fetcher, clientId, clientSecret, eventHandle, idempotencyKey, reference, revision, shopId, timestamp, value }) => {
5490
+ if (!shopId || !eventHandle || !(Number(value) > 0)) {
5491
+ throw new Error("sendAppEvent requires shopId, eventHandle, and a positive value");
5492
+ }
5493
+ ;
5494
+ if (!clientId || !clientSecret) {
5495
+ throw new Error("sendAppEvent requires clientId and clientSecret");
5496
+ }
5497
+ ;
5498
+ const suffix = revision ? ".r" + revision : "";
5499
+ const key = idempotencyKey && String(idempotencyKey).slice(0, Math.max(0, 64 - suffix.length)) + suffix;
5500
+ const body = {
5501
+ attributes: {
5502
+ value: Number(value),
5503
+ ...reference && {
5504
+ reference: String(reference).slice(0, 128)
5505
+ }
5506
+ },
5507
+ event_handle: eventHandle,
5508
+ shop_id: toShopGid(shopId),
5509
+ timestamp: timestamp || (/* @__PURE__ */ new Date()).toISOString(),
5510
+ ...key && {
5511
+ idempotency_key: key
5512
+ }
5513
+ };
5514
+ const send2 = async (token) => request({
5515
+ method: "POST",
5516
+ url: APP_API + "/app/" + APP_API_VERSION + "/events",
5517
+ headers: {
5518
+ "Authorization": "Bearer " + token
5519
+ },
5520
+ body
5521
+ });
5522
+ try {
5523
+ return await send2(await getAppToken({ clientId, clientSecret, fetcher }));
5524
+ } catch (error) {
5525
+ if ((error == null ? void 0 : error.status) === 401) {
5526
+ delete cachedTokens[clientId];
5527
+ return send2(await fetchAppToken({ clientId, clientSecret, fetcher }));
5528
+ }
5529
+ ;
5530
+ throw error;
5531
+ }
5532
+ };
5533
+
5534
+ // lib/shopify/oauth.js
5535
+ var oauth_exports = {};
5536
+ __export(oauth_exports, {
5537
+ SHOPIFY_REQUIRED_SCOPES: () => SHOPIFY_REQUIRED_SCOPES,
5538
+ createStorefrontToken: () => createStorefrontToken,
5539
+ getAdminToken: () => getAdminToken,
5540
+ getShop: () => getShop,
5541
+ missingScopes: () => missingScopes2,
5542
+ ping: () => ping,
5543
+ refreshAdminToken: () => refreshAdminToken,
5544
+ resolveConnectionSettings: () => resolveConnectionSettings
5545
+ });
5546
+ var required = (name, value) => {
5547
+ if (!value) {
5548
+ throw new Error("Shopify " + name + " is required");
5549
+ }
5550
+ ;
5551
+ return value;
5552
+ };
5553
+ var missingScopes2 = (granted) => {
5554
+ const grantedSet = new Set(
5555
+ (Array.isArray(granted) ? granted : String(granted || "").split(",")).map((scope) => scope.trim()).filter(Boolean)
5556
+ );
5557
+ const satisfied = (scope) => grantedSet.has(scope) || grantedSet.has(scope.replace(/(^|_)read_/, "$1write_"));
5558
+ return SHOPIFY_REQUIRED_SCOPES.filter((scope) => !satisfied(scope));
5559
+ };
5560
+ var ping = async ({ fetcher, adminAccessToken, domain }) => {
5561
+ var _a;
5562
+ const response = await fetch(
5563
+ `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}/graphql.json`,
5564
+ {
5565
+ body: JSON.stringify({ query: "{ shop { name } }" }),
5566
+ headers: {
5567
+ "Content-Type": "application/json",
5568
+ "X-Shopify-Access-Token": adminAccessToken
5569
+ },
5570
+ method: "POST"
5571
+ }
5572
+ );
5573
+ if (!response.ok) {
5574
+ const text = await response.text().catch(() => "");
5575
+ const error = new Error(response.status + ": " + text);
5576
+ error.status = response.status;
5577
+ throw error;
5578
+ }
5579
+ ;
5580
+ const { errors } = await response.json().catch(() => ({}));
5581
+ if (errors == null ? void 0 : errors.length) {
5582
+ throw new Error("GraphQL: " + (((_a = errors[0]) == null ? void 0 : _a.message) || "unknown error"));
5583
+ }
5584
+ ;
5585
+ };
5586
+ var OAUTH_ERROR_TITLE_PATTERN = /Oauth error (\w+)/i;
5587
+ var parseOAuthErrorCode = (text) => {
5588
+ var _a;
5589
+ try {
5590
+ const parsed = JSON.parse(text);
5591
+ if (parsed == null ? void 0 : parsed.error) return parsed.error;
5592
+ } catch {
5593
+ }
5594
+ ;
5595
+ return ((_a = text.match(OAUTH_ERROR_TITLE_PATTERN)) == null ? void 0 : _a[1]) || null;
5596
+ };
5597
+ var shopifyOAuthFetch = async (url, body) => {
5598
+ const response = await fetch(url, {
5599
+ method: "POST",
5600
+ headers: {
5601
+ "Content-Type": "application/json"
5602
+ },
5603
+ body: JSON.stringify(body)
5604
+ });
5605
+ if (!response.ok) {
5606
+ const text = await response.text().catch(() => "");
5607
+ const error = new Error(response.status + ": " + text);
5608
+ error.status = response.status;
5609
+ error.code = parseOAuthErrorCode(text);
5610
+ throw error;
5611
+ }
5612
+ ;
5613
+ return response.json();
5614
+ };
5615
+ var getShop = async ({ fetcher, adminAccessToken, shop }) => {
5616
+ const data = await adminFetch({
5617
+ fetcher,
5618
+ adminAccessToken,
5619
+ domain: shop,
5620
+ query: `{
5621
+ shop {
5622
+ currencyCode
5623
+ id
5624
+ myshopifyDomain
5625
+ name
5626
+ }
5627
+ }`
5628
+ });
5629
+ const shopData = data == null ? void 0 : data.shop;
5630
+ if (!(shopData == null ? void 0 : shopData.id)) {
5631
+ throw new Error("Shopify shop lookup failed: no shop returned");
5632
+ }
5633
+ ;
5634
+ return {
5635
+ currency: shopData.currencyCode || null,
5636
+ id: shopData.id.split("/").pop(),
5637
+ myshopifyDomain: shopData.myshopifyDomain,
5638
+ name: shopData.name
5639
+ };
5640
+ };
5641
+ var createStorefrontToken = async ({ fetcher, adminAccessToken, shop }) => {
5642
+ var _a, _b, _c, _d, _e;
5643
+ try {
5644
+ const listed = await adminFetch({
5645
+ fetcher,
5646
+ adminAccessToken,
5647
+ domain: shop,
5648
+ query: `{
5649
+ shop {
5650
+ storefrontAccessTokens(first: 100) {
5651
+ edges {
5652
+ node {
5653
+ id
5654
+ title
5655
+ }
5656
+ }
5657
+ }
5658
+ }
5659
+ }`
5660
+ });
5661
+ 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);
5662
+ const orphaned = existing.filter((token) => (token == null ? void 0 : token.title) === "Drawbridge");
5663
+ await Promise.allSettled(
5664
+ orphaned.map((token) => adminFetch({
5665
+ adminAccessToken,
5666
+ domain: shop,
5667
+ query: `
5668
+ mutation StorefrontAccessTokenDelete($input: StorefrontAccessTokenDeleteInput!) {
5669
+ storefrontAccessTokenDelete(input: $input) {
5670
+ deletedStorefrontAccessTokenId
5671
+ userErrors {
5672
+ field
5673
+ message
5674
+ }
5675
+ }
5676
+ }
5677
+ `,
5678
+ variables: {
5679
+ input: {
5680
+ id: token.id
5681
+ }
5682
+ }
5683
+ }))
5684
+ );
5685
+ } catch {
5686
+ }
5687
+ const created = await adminFetch({
5688
+ fetcher,
5689
+ adminAccessToken,
5690
+ domain: shop,
5691
+ query: `
5692
+ mutation StorefrontAccessTokenCreate($input: StorefrontAccessTokenInput!) {
5693
+ storefrontAccessTokenCreate(input: $input) {
5694
+ storefrontAccessToken {
5695
+ accessToken
5696
+ }
5697
+ userErrors {
5698
+ field
5699
+ message
5700
+ }
5701
+ }
5702
+ }
5703
+ `,
5704
+ variables: {
5705
+ input: {
5706
+ title: "Drawbridge"
5707
+ }
5708
+ }
5709
+ });
5710
+ const createErrors = (_c = created == null ? void 0 : created.storefrontAccessTokenCreate) == null ? void 0 : _c.userErrors;
5711
+ if (createErrors == null ? void 0 : createErrors.length) {
5712
+ throw new Error("Shopify storefront token create failed: " + createErrors[0].message);
5713
+ }
5714
+ ;
5715
+ return ((_e = (_d = created == null ? void 0 : created.storefrontAccessTokenCreate) == null ? void 0 : _d.storefrontAccessToken) == null ? void 0 : _e.accessToken) || null;
5716
+ };
5717
+ var resolveTokenContext = async ({ connection: connection2, controller }) => {
5718
+ const decrypted = (connection2 == null ? void 0 : connection2.settings) ? decrypt(connection2.settings) : {};
5719
+ if ((decrypted == null ? void 0 : decrypted.ref) !== "shop") {
5720
+ return {
5721
+ raw: (connection2 == null ? void 0 : connection2.settings) || null,
5722
+ session: null,
5723
+ settings: decrypted,
5724
+ shop: null,
5725
+ target: "connection"
5726
+ };
5727
+ }
5728
+ ;
5729
+ const shop = decrypted.shop;
5730
+ if (!controller || !shop) {
5731
+ return { raw: null, session: {}, settings: {}, shop, target: "shop" };
5732
+ }
5733
+ ;
5734
+ const record = await controller.get({ collection: "shop", query: { shop } });
5735
+ const session = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : {};
5736
+ const storefront = (record == null ? void 0 : record.storefront) ? decrypt(record.storefront) : null;
5737
+ return {
5738
+ raw: (record == null ? void 0 : record.settings) || null,
5739
+ session,
5740
+ settings: {
5741
+ adminAccessToken: session.accessToken || null,
5742
+ refreshToken: session.refreshToken || null,
5743
+ refreshTokenExpiresAt: session.refreshTokenExpires || null,
5744
+ storefrontAccessToken: (storefront == null ? void 0 : storefront.token) || null,
5745
+ tokenExpiresAt: session.expires || null
5746
+ },
5747
+ shop,
5748
+ target: "shop"
5749
+ };
5750
+ };
5751
+ var resolveConnectionSettings = async ({ fetcher, connection: connection2, controller }) => {
5752
+ const { settings } = await resolveTokenContext({ connection: connection2, controller });
5753
+ return settings;
5754
+ };
5755
+ var refreshAdminToken = async ({ fetcher, clientId, clientSecret, connection: connection2, controller }) => {
5756
+ var _a;
5757
+ const { raw, session, settings, shop, target } = await resolveTokenContext({ connection: connection2, controller });
5758
+ const domain = (connection2 == null ? void 0 : connection2.shop) || ((_a = settings.source) == null ? void 0 : _a.domain) || settings.domain || shop;
5759
+ const { refreshToken } = settings;
5760
+ const data = await shopifyOAuthFetch(
5761
+ `https://${domain}/admin/oauth/access_token`,
5762
+ {
5763
+ grant_type: "refresh_token",
5764
+ // Throw before the grant: rotation RETIRES the old pair the moment it
5765
+ // returns, so a credential-less call that Shopify rejects opaquely is
5766
+ // the one failure mode worth being loud about.
5767
+ client_id: required("clientId", clientId),
5768
+ client_secret: required("clientSecret", clientSecret),
5769
+ refresh_token: refreshToken
5770
+ }
5771
+ );
5772
+ const adminAccessToken = data.access_token;
5773
+ const newRefreshToken = data.refresh_token;
5774
+ const expiresIn = data.expires_in;
5775
+ const tokenExpiresAt = expiresIn ? new Date(Date.now() + expiresIn * 1e3) : null;
5776
+ const refreshTokenExpiresAt = new Date(Date.now() + REFRESH_TOKEN_LIFETIME_MS);
5777
+ let liveToken = adminAccessToken;
5778
+ if (target === "shop") {
5779
+ const written = await controller.update({
5780
+ collection: "shop",
5781
+ data: {
5782
+ $set: {
5783
+ settings: encrypt({
5784
+ ...session,
5785
+ accessToken: adminAccessToken,
5786
+ expires: tokenExpiresAt,
5787
+ refreshToken: newRefreshToken,
5788
+ refreshTokenExpires: refreshTokenExpiresAt
5789
+ })
5790
+ }
5791
+ },
5792
+ query: {
5793
+ shop,
5794
+ ...raw && { settings: raw }
5795
+ }
5796
+ });
5797
+ if (!written) {
5798
+ const current = await controller.get({ collection: "shop", query: { shop } });
5799
+ if (!(current == null ? void 0 : current.settings)) {
5800
+ throw new Error("Shopify token refresh write-back failed: shop record missing for " + shop);
5801
+ }
5802
+ ;
5803
+ const currentSession = decrypt(current.settings);
5804
+ if ((currentSession == null ? void 0 : currentSession.accessToken) && currentSession.accessToken !== settings.adminAccessToken) {
5805
+ liveToken = currentSession.accessToken;
5806
+ } else {
5807
+ throw new Error("Shopify token refresh write-back failed for " + shop);
5808
+ }
5809
+ ;
5810
+ }
5811
+ ;
5812
+ } else {
5813
+ const written = await controller.update({
5814
+ collection: "connection",
5815
+ data: {
5816
+ $set: {
5817
+ settings: encrypt({
5818
+ ...settings,
5819
+ adminAccessToken,
5820
+ refreshToken: newRefreshToken,
5821
+ refreshTokenExpiresAt,
5822
+ tokenExpiresAt
5823
+ })
5824
+ }
5825
+ },
5826
+ query: {
5827
+ id: connection2.id,
5828
+ ...raw && { settings: raw }
5829
+ }
5830
+ });
5831
+ if (!written) {
5832
+ const current = await controller.get({ collection: "connection", query: { id: connection2.id } });
5833
+ const currentSettings = (current == null ? void 0 : current.settings) ? decrypt(current.settings) : null;
5834
+ if ((currentSettings == null ? void 0 : currentSettings.adminAccessToken) && currentSettings.adminAccessToken !== settings.adminAccessToken) {
5835
+ liveToken = currentSettings.adminAccessToken;
5836
+ } else {
5837
+ throw new Error("Shopify token refresh write-back failed for connection " + (connection2 == null ? void 0 : connection2.id));
5838
+ }
5839
+ ;
5840
+ }
5841
+ ;
5842
+ }
5843
+ ;
5844
+ await ping({ adminAccessToken: liveToken, domain });
5845
+ return liveToken;
5846
+ };
5847
+ var getAdminToken = async ({ fetcher, clientId, clientSecret, connection: connection2, controller }) => {
5848
+ required("clientId", clientId);
5849
+ required("clientSecret", clientSecret);
5850
+ const settings = await resolveConnectionSettings({ connection: connection2, controller });
5851
+ const { adminAccessToken, refreshToken, tokenExpiresAt } = settings;
5852
+ if (!adminAccessToken) {
5853
+ return null;
5854
+ }
5855
+ ;
5856
+ if (!refreshToken) {
5857
+ return adminAccessToken;
5858
+ }
5859
+ ;
5860
+ const needsRefresh = !tokenExpiresAt || new Date(tokenExpiresAt) < new Date(Date.now() + ACCESS_TOKEN_REFRESH_BUFFER_MS);
5861
+ if (needsRefresh) {
5862
+ return refreshAdminToken({ clientId, clientSecret, connection: connection2, controller });
5863
+ }
5864
+ ;
5865
+ return adminAccessToken;
5866
+ };
5867
+
5868
+ // lib/shopify/partner.js
5869
+ var partner_exports = {};
5870
+ __export(partner_exports, {
5871
+ getUsageChargeEvents: () => getUsageChargeEvents
5872
+ });
5873
+ var PARTNER_API = "https://partners.shopify.com";
5874
+ var getUsageChargeEvents = async ({ fetcher, appId, first = 10, occurredAtMin, organizationId, partnerToken, shopId }) => {
5875
+ var _a, _b, _c;
5876
+ if (!partnerToken || !organizationId || !appId) {
5877
+ throw new Error("getUsageChargeEvents requires partnerToken, organizationId, and appId");
5878
+ }
5879
+ ;
5880
+ const data = await request({
5881
+ fetcher,
5882
+ method: "POST",
5883
+ url: PARTNER_API + "/" + organizationId + "/api/" + PARTNER_API_VERSION + "/graphql.json",
5884
+ headers: {
5885
+ "X-Shopify-Access-Token": partnerToken
5886
+ },
5887
+ body: {
5888
+ query: `query usageCharges( $filter : EventFilterInput!, $first : Int! ) {
5889
+ events( filter : $filter, orderBy : OCCURRED_AT_DESC, first : $first ) {
5890
+ edges {
5891
+ node {
5892
+ id
5893
+ occurredAt
5894
+ eventType
5895
+ shop { id myshopifyDomain }
5896
+ ... on Charge {
5897
+ chargeId
5898
+ chargeType
5899
+ amount { amount currencyCode }
5900
+ usageQuantity
5901
+ planHandle
5902
+ description
5903
+ }
5904
+ }
5905
+ }
5906
+ pageInfo { hasNextPage endCursor }
5907
+ }
5908
+ }`,
5909
+ variables: {
5910
+ filter: {
5911
+ eventTypes: ["CHARGE_USAGE"],
5912
+ subjectId: String(appId),
5913
+ ...occurredAtMin && { occurredAtMin },
5914
+ ...shopId && { shopId: String(shopId) }
5915
+ },
5916
+ first
5917
+ }
5918
+ }
5919
+ });
5920
+ if ((_a = data == null ? void 0 : data.errors) == null ? void 0 : _a.length) {
5921
+ throw new Error("Shopify partner events query failed: " + data.errors.map((entry) => entry.message).join("; "));
5922
+ }
5923
+ ;
5924
+ return (((_c = (_b = data == null ? void 0 : data.data) == null ? void 0 : _b.events) == null ? void 0 : _c.edges) || []).map((edge) => {
5925
+ var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j;
5926
+ return {
5927
+ amount: ((_a2 = edge.node) == null ? void 0 : _a2.amount) || null,
5928
+ chargeId: ((_b2 = edge.node) == null ? void 0 : _b2.chargeId) || null,
5929
+ // USAGE vs the recurring plan charge an approval emits — the
5930
+ // disambiguator callers filter on.
5931
+ chargeType: ((_c2 = edge.node) == null ? void 0 : _c2.chargeType) || null,
5932
+ description: ((_d = edge.node) == null ? void 0 : _d.description) || null,
5933
+ eventType: ((_e = edge.node) == null ? void 0 : _e.eventType) || null,
5934
+ id: ((_f = edge.node) == null ? void 0 : _f.id) || null,
5935
+ occurredAt: ((_g = edge.node) == null ? void 0 : _g.occurredAt) || null,
5936
+ planHandle: ((_h = edge.node) == null ? void 0 : _h.planHandle) || null,
5937
+ shop: ((_i = edge.node) == null ? void 0 : _i.shop) || null,
5938
+ usageQuantity: ((_j = edge.node) == null ? void 0 : _j.usageQuantity) ?? null
5939
+ };
5940
+ });
5941
+ };
5942
+
5943
+ // lib/shopify/storefront.js
5944
+ var storefront_exports = {};
5945
+ __export(storefront_exports, {
5946
+ cartCreate: () => cartCreate,
5947
+ cartGet: () => cartGet,
5948
+ cartLinesAdd: () => cartLinesAdd,
5949
+ cartLinesRemove: () => cartLinesRemove,
5950
+ cartLinesUpdate: () => cartLinesUpdate,
5951
+ createCheckoutToken: () => createCheckoutToken,
5952
+ getProduct: () => getProduct,
5953
+ getProductVariantsPage: () => getProductVariantsPage,
5954
+ getProducts: () => getProducts,
5955
+ probeVariantsOutOfStock: () => probeVariantsOutOfStock
5956
+ });
5957
+ var SORT_KEY_MAP = {
5958
+ bestSelling: "BEST_SELLING",
5959
+ createdAt: "CREATED_AT",
5960
+ id: "ID",
5961
+ price: "PRICE",
5962
+ productType: "PRODUCT_TYPE",
5963
+ title: "TITLE",
5964
+ updatedAt: "UPDATED_AT",
5965
+ vendor: "VENDOR"
5966
+ };
5967
+ var resolveProductSort = (sort) => {
5968
+ const entry = sort && Object.entries(sort)[0];
5969
+ if (!entry) return null;
5970
+ const [field2, direction] = entry;
5971
+ const sortKey = SORT_KEY_MAP[field2];
5972
+ if (!sortKey) return null;
5973
+ return {
5974
+ sortKey,
5975
+ reverse: Number(direction) < 0
5976
+ };
5977
+ };
5978
+ var storefrontUrl = (domain) => `https://${domain}/api/${SHOPIFY_STOREFRONT_API_VERSION}/graphql.json`;
5979
+ var storefrontFetch = async ({ fetcher, domain, storefrontAccessToken, query, variables }) => {
5980
+ return request({
5981
+ method: "POST",
5982
+ url: storefrontUrl(domain),
5983
+ headers: {
5984
+ "X-Shopify-Storefront-Access-Token": storefrontAccessToken
5985
+ },
5986
+ body: {
5987
+ query,
5988
+ ...variables && { variables }
5989
+ }
5990
+ });
5991
+ };
5992
+ var shopCountryCache = {};
5993
+ var getShopCountry = async ({ domain, fetcher, storefrontAccessToken }) => {
5994
+ var _a, _b;
5995
+ if (shopCountryCache[domain]) return shopCountryCache[domain];
5996
+ const { data } = await storefrontFetch({
5997
+ fetcher,
5998
+ domain,
5999
+ storefrontAccessToken,
6000
+ query: `{
6001
+ shop {
6002
+ paymentSettings {
6003
+ countryCode
6004
+ }
6005
+ }
6006
+ }`
6007
+ });
6008
+ const countryCode = ((_b = (_a = data == null ? void 0 : data.shop) == null ? void 0 : _a.paymentSettings) == null ? void 0 : _b.countryCode) || null;
6009
+ if (countryCode) shopCountryCache[domain] = countryCode;
6010
+ return countryCode;
6011
+ };
6012
+ var OUT_OF_STOCK_WARNING_CODES = [
6013
+ "MERCHANDISE_OUT_OF_STOCK",
6014
+ "MERCHANDISE_NOT_ENOUGH_STOCK"
6015
+ ];
6016
+ var probeVariantsOutOfStock = async ({ fetcher, domain, storefrontAccessToken, variantIds, countryCode }) => {
6017
+ var _a, _b;
6018
+ if (!(variantIds == null ? void 0 : variantIds.length)) return [];
6019
+ const resolvedCountry = countryCode || await getShopCountry({ domain, fetcher, storefrontAccessToken });
6020
+ const { data, errors } = await storefrontFetch({
6021
+ fetcher,
6022
+ domain,
6023
+ storefrontAccessToken,
6024
+ query: `
6025
+ mutation probe( $input : CartInput! ){
6026
+ cartCreate( input : $input ){
6027
+ cart {
6028
+ lines( first : 250 ){
6029
+ edges {
6030
+ node {
6031
+ id
6032
+ merchandise {
6033
+ ... on ProductVariant {
6034
+ id
6035
+ }
6036
+ }
6037
+ }
6038
+ }
6039
+ }
6040
+ }
6041
+ warnings {
6042
+ code
6043
+ message
6044
+ target
6045
+ }
6046
+ }
6047
+ }
6048
+ `,
6049
+ variables: {
6050
+ input: {
6051
+ lines: variantIds.map((merchandiseId) => ({
6052
+ merchandiseId,
6053
+ quantity: 1
6054
+ })),
6055
+ ...resolvedCountry && {
6056
+ buyerIdentity: {
6057
+ countryCode: resolvedCountry
6058
+ }
6059
+ }
6060
+ }
6061
+ }
6062
+ });
6063
+ if (errors) return [];
6064
+ const payload = data == null ? void 0 : data.cartCreate;
6065
+ const soldOut = new Set(
6066
+ ((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)
6067
+ );
6068
+ 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 }) => {
6069
+ var _a2;
6070
+ return (_a2 = node == null ? void 0 : node.merchandise) == null ? void 0 : _a2.id;
6071
+ }).filter(Boolean);
6072
+ };
6073
+ var productsQuery = (search, cursor, limit, sort) => {
6074
+ const resolved = resolveProductSort(sort);
6075
+ const sortArgs = resolved ? `, sortKey: ${resolved.sortKey}, reverse: ${resolved.reverse}` : "";
6076
+ return `{
6077
+ products(first: ${limit}${search ? `, query: "title:*${search}*"` : ""}${cursor ? `, after: "${cursor}"` : ""}${sortArgs}) {
6078
+ edges {
6079
+ node {
6080
+ id
6081
+ title
6082
+ description
6083
+ handle
6084
+ productType
6085
+ featuredImage {
6086
+ url
6087
+ }
6088
+ variants(first: 10) {
6089
+ edges {
6090
+ node {
6091
+ id
6092
+ title
6093
+ image {
6094
+ url
6095
+ }
6096
+ price {
6097
+ amount
6098
+ currencyCode
6099
+ }
6100
+ compareAtPrice {
6101
+ amount
6102
+ currencyCode
6103
+ }
6104
+ availableForSale
6105
+ requiresShipping
6106
+ }
6107
+ }
6108
+ }
6109
+ }
6110
+ }
6111
+ pageInfo {
6112
+ endCursor
6113
+ hasNextPage
6114
+ hasPreviousPage
6115
+ startCursor
6116
+ }
6117
+ }
6118
+ }`;
6119
+ };
6120
+ var productQuery = (productId) => `{
6121
+ product(id: "${productId}") {
6122
+ id
6123
+ title
6124
+ description
6125
+ handle
6126
+ productType
6127
+ featuredImage {
6128
+ url
6129
+ }
6130
+ variants(first: 10) {
6131
+ edges {
6132
+ node {
6133
+ id
6134
+ title
6135
+ image {
6136
+ url
6137
+ }
6138
+ price {
6139
+ amount
6140
+ currencyCode
6141
+ }
6142
+ compareAtPrice {
6143
+ amount
6144
+ currencyCode
6145
+ }
6146
+ availableForSale
6147
+ requiresShipping
6148
+ }
6149
+ }
6150
+ }
6151
+ }
6152
+ }`;
6153
+ var variantsQuery = (productId, cursor) => `{
6154
+ product(id: "${productId}") {
6155
+ variants(first: 250${cursor ? `, after: "${cursor}"` : ""}) {
6156
+ edges {
6157
+ node {
6158
+ id
6159
+ title
6160
+ image {
6161
+ url
6162
+ }
6163
+ price {
6164
+ amount
6165
+ currencyCode
6166
+ }
6167
+ compareAtPrice {
6168
+ amount
6169
+ currencyCode
6170
+ }
6171
+ availableForSale
6172
+ requiresShipping
6173
+ }
6174
+ }
6175
+ pageInfo {
6176
+ hasNextPage
6177
+ endCursor
6178
+ }
6179
+ }
6180
+ }
6181
+ }`;
6182
+ var getProducts = async ({ fetcher, domain, storefrontAccessToken, search, cursor, limit, sort }) => {
6183
+ const { data, errors } = await storefrontFetch({
6184
+ fetcher,
6185
+ domain,
6186
+ storefrontAccessToken,
6187
+ query: productsQuery(search, cursor, limit, sort)
6188
+ });
6189
+ if (errors) {
6190
+ throw new Error("Failed to fetch Shopify products");
6191
+ }
6192
+ ;
6193
+ return data == null ? void 0 : data.products;
6194
+ };
6195
+ var getProduct = async ({ fetcher, domain, storefrontAccessToken, productId }) => {
6196
+ var _a;
6197
+ const { data, errors } = await storefrontFetch({
6198
+ fetcher,
6199
+ domain,
6200
+ storefrontAccessToken,
6201
+ query: productQuery(productId)
6202
+ });
6203
+ if (errors) {
6204
+ throw new Error("Shopify storefront error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
6205
+ }
6206
+ ;
6207
+ if (!(data == null ? void 0 : data.product)) {
6208
+ throw new Error("Shopify product not found");
6209
+ }
6210
+ ;
6211
+ return data.product;
6212
+ };
6213
+ var getProductVariantsPage = async ({ fetcher, domain, storefrontAccessToken, productId, cursor }) => {
6214
+ var _a;
6215
+ const { data, errors } = await storefrontFetch({
6216
+ fetcher,
6217
+ domain,
6218
+ storefrontAccessToken,
6219
+ query: variantsQuery(productId, cursor)
6220
+ });
6221
+ if (errors) {
6222
+ throw new Error("Shopify storefront error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
6223
+ }
6224
+ ;
6225
+ if (!(data == null ? void 0 : data.product)) {
6226
+ throw new Error("Shopify product not found");
6227
+ }
6228
+ ;
6229
+ return data.product.variants;
6230
+ };
6231
+ var CART_FIELDS = `
6232
+ id
6233
+ checkoutUrl
6234
+ lines(first: 100) {
6235
+ edges {
6236
+ node {
6237
+ id
6238
+ quantity
6239
+ merchandise {
6240
+ ... on ProductVariant {
6241
+ id
6242
+ title
6243
+ availableForSale
6244
+ image {
6245
+ url
6246
+ }
6247
+ price {
6248
+ amount
6249
+ currencyCode
6250
+ }
6251
+ product {
6252
+ title
6253
+ }
6254
+ }
6255
+ }
6256
+ }
6257
+ }
6258
+ }
6259
+ `;
6260
+ var mapCart = (cart) => {
6261
+ var _a;
6262
+ if (!cart) return null;
6263
+ return {
6264
+ checkoutUrl: cart.checkoutUrl,
6265
+ id: cart.id,
6266
+ lines: (((_a = cart.lines) == null ? void 0 : _a.edges) || []).map(({ node }) => {
6267
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
6268
+ return {
6269
+ availableForSale: ((_a2 = node == null ? void 0 : node.merchandise) == null ? void 0 : _a2.availableForSale) ?? true,
6270
+ currency: ((_c = (_b = node == null ? void 0 : node.merchandise) == null ? void 0 : _b.price) == null ? void 0 : _c.currencyCode) || null,
6271
+ id: node.id,
6272
+ image: ((_e = (_d = node == null ? void 0 : node.merchandise) == null ? void 0 : _d.image) == null ? void 0 : _e.url) || null,
6273
+ price: ((_g = (_f = node == null ? void 0 : node.merchandise) == null ? void 0 : _f.price) == null ? void 0 : _g.amount) || null,
6274
+ productTitle: ((_i = (_h = node == null ? void 0 : node.merchandise) == null ? void 0 : _h.product) == null ? void 0 : _i.title) || null,
6275
+ quantity: node.quantity,
6276
+ variantId: (_j = node == null ? void 0 : node.merchandise) == null ? void 0 : _j.id,
6277
+ variantTitle: ((_k = node == null ? void 0 : node.merchandise) == null ? void 0 : _k.title) || null
6278
+ };
6279
+ })
6280
+ };
6281
+ };
6282
+ var firstUserError = (userErrors) => {
6283
+ const error = userErrors == null ? void 0 : userErrors[0];
6284
+ if (!error) return null;
6285
+ const message = new Error(error.message || "Shopify cart error");
6286
+ message.userError = true;
6287
+ return message;
6288
+ };
6289
+ var createCheckoutToken = async ({ fetcher, clientId, clientSecret } = {}) => {
6290
+ if (!clientId || !clientSecret) {
6291
+ throw new Error("createCheckoutToken requires clientId and clientSecret");
6292
+ }
6293
+ ;
6294
+ const response = await request({
6295
+ fetcher,
6296
+ method: "POST",
6297
+ url: "https://api.shopify.com/auth/access_token",
6298
+ body: {
6299
+ client_id: clientId,
6300
+ client_secret: clientSecret,
6301
+ grant_type: "client_credentials"
6302
+ }
6303
+ });
6304
+ const token = response == null ? void 0 : response.access_token;
6305
+ if (!token) {
6306
+ throw new Error("Failed to create Shopify checkout token");
6307
+ }
6308
+ ;
6309
+ return token;
6310
+ };
6311
+ var cartCreate = async ({ fetcher, domain, storefrontAccessToken, lines }) => {
6312
+ var _a, _b;
6313
+ const { data, errors } = await storefrontFetch({
6314
+ fetcher,
6315
+ domain,
6316
+ storefrontAccessToken,
6317
+ query: `
6318
+ mutation cartCreate($input: CartInput!) {
6319
+ cartCreate(input: $input) {
6320
+ cart {
6321
+ ${CART_FIELDS}
6322
+ }
6323
+ userErrors {
6324
+ field
6325
+ message
6326
+ }
6327
+ }
6328
+ }
6329
+ `,
6330
+ variables: {
6331
+ input: {
6332
+ lines
6333
+ }
6334
+ }
6335
+ });
6336
+ if (errors) {
6337
+ throw new Error("Failed to create Shopify cart");
6338
+ }
6339
+ ;
6340
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartCreate) == null ? void 0 : _a.userErrors);
6341
+ if (userError) throw userError;
6342
+ return mapCart((_b = data == null ? void 0 : data.cartCreate) == null ? void 0 : _b.cart);
6343
+ };
6344
+ var cartGet = async ({ fetcher, domain, storefrontAccessToken, cartId }) => {
6345
+ const { data, errors } = await storefrontFetch({
6346
+ fetcher,
6347
+ domain,
6348
+ storefrontAccessToken,
6349
+ query: `
6350
+ query cart($id: ID!) {
6351
+ cart(id: $id) {
6352
+ ${CART_FIELDS}
6353
+ }
6354
+ }
6355
+ `,
6356
+ variables: {
6357
+ id: cartId
6358
+ }
6359
+ });
6360
+ if (errors) {
6361
+ throw new Error("Failed to fetch Shopify cart");
6362
+ }
6363
+ ;
6364
+ return mapCart(data == null ? void 0 : data.cart);
6365
+ };
6366
+ var cartLinesAdd = async ({ fetcher, domain, storefrontAccessToken, cartId, lines }) => {
6367
+ var _a, _b;
6368
+ const { data, errors } = await storefrontFetch({
6369
+ fetcher,
6370
+ domain,
6371
+ storefrontAccessToken,
6372
+ query: `
6373
+ mutation cartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {
6374
+ cartLinesAdd(cartId: $cartId, lines: $lines) {
6375
+ cart {
6376
+ ${CART_FIELDS}
6377
+ }
6378
+ userErrors {
6379
+ field
6380
+ message
6381
+ }
6382
+ }
6383
+ }
6384
+ `,
6385
+ variables: {
6386
+ cartId,
6387
+ lines
6388
+ }
6389
+ });
6390
+ if (errors) {
6391
+ throw new Error("Failed to add Shopify cart lines");
6392
+ }
6393
+ ;
6394
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartLinesAdd) == null ? void 0 : _a.userErrors);
6395
+ if (userError) throw userError;
6396
+ return mapCart((_b = data == null ? void 0 : data.cartLinesAdd) == null ? void 0 : _b.cart);
6397
+ };
6398
+ var cartLinesRemove = async ({ fetcher, domain, storefrontAccessToken, cartId, lineIds }) => {
6399
+ var _a, _b;
6400
+ const { data, errors } = await storefrontFetch({
6401
+ fetcher,
6402
+ domain,
6403
+ storefrontAccessToken,
6404
+ query: `
6405
+ mutation cartLinesRemove($cartId: ID!, $lineIds: [ID!]!) {
6406
+ cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {
6407
+ cart {
6408
+ ${CART_FIELDS}
6409
+ }
6410
+ userErrors {
6411
+ field
6412
+ message
6413
+ }
6414
+ }
6415
+ }
6416
+ `,
6417
+ variables: {
6418
+ cartId,
6419
+ lineIds
6420
+ }
6421
+ });
6422
+ if (errors) {
6423
+ throw new Error("Failed to remove Shopify cart lines");
6424
+ }
6425
+ ;
6426
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartLinesRemove) == null ? void 0 : _a.userErrors);
6427
+ if (userError) throw userError;
6428
+ return mapCart((_b = data == null ? void 0 : data.cartLinesRemove) == null ? void 0 : _b.cart);
6429
+ };
6430
+ var cartLinesUpdate = async ({ fetcher, domain, storefrontAccessToken, cartId, lines }) => {
6431
+ var _a, _b;
6432
+ const { data, errors } = await storefrontFetch({
6433
+ fetcher,
6434
+ domain,
6435
+ storefrontAccessToken,
6436
+ query: `
6437
+ mutation cartLinesUpdate($cartId: ID!, $lines: [CartLineUpdateInput!]!) {
6438
+ cartLinesUpdate(cartId: $cartId, lines: $lines) {
6439
+ cart {
6440
+ ${CART_FIELDS}
6441
+ }
6442
+ userErrors {
6443
+ field
6444
+ message
6445
+ }
6446
+ }
6447
+ }
6448
+ `,
6449
+ variables: {
6450
+ cartId,
6451
+ lines
6452
+ }
6453
+ });
6454
+ if (errors) {
6455
+ throw new Error("Failed to update Shopify cart lines");
6456
+ }
6457
+ ;
6458
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartLinesUpdate) == null ? void 0 : _a.userErrors);
6459
+ if (userError) throw userError;
6460
+ return mapCart((_b = data == null ? void 0 : data.cartLinesUpdate) == null ? void 0 : _b.cart);
6461
+ };
6462
+
6463
+ // lib/email.js
6464
+ var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
6465
+ var toCanonicalEmail = (value) => {
6466
+ if (!value || typeof value !== "string") return null;
6467
+ const email = value.trim().toLowerCase();
6468
+ const at = email.lastIndexOf("@");
6469
+ if (at < 1 || at === email.length - 1) return null;
6470
+ let local = email.slice(0, at);
6471
+ const domain = email.slice(at + 1);
6472
+ const plus = local.indexOf("+");
6473
+ if (plus > 0) local = local.slice(0, plus);
6474
+ if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
6475
+ if (!local) return null;
6476
+ return local + "@" + domain;
6477
+ };
6478
+
6479
+ // lib/oauth/index.js
6480
+ var lifetimes = {
6481
+ access: 60 * 60 * 8,
6482
+ // 8 hours
6483
+ authorizationCode: 10 * 60,
6484
+ // 10 minutes
6485
+ code: 15 * 60,
6486
+ // 15 minutes (email OTC)
6487
+ refresh: 30 * 24 * 60 * 60
6488
+ // 30 days
6489
+ };
6490
+ var tokenTypes = {
6491
+ access: "access",
6492
+ oauthState: "oauth.state",
6493
+ pat: "pat",
6494
+ refresh: "refresh"
6495
+ };
6496
+ var scopes = [
6497
+ "profile:read",
6498
+ "profile:write",
6499
+ "organization:read",
6500
+ "organization:write",
6501
+ "campaigns:read",
6502
+ "campaigns:write",
6503
+ "contacts:read",
6504
+ "contacts:write",
6505
+ "workflows:read",
6506
+ "workflows:write",
6507
+ "connections:read",
6508
+ "connections:write",
6509
+ "billing:read",
6510
+ "billing:write",
6511
+ "admin"
6512
+ ];
6513
+ var developer = [
6514
+ "profile:read",
6515
+ "organization:read",
6516
+ "campaigns:read",
6517
+ "campaigns:write",
6518
+ "contacts:read",
6519
+ "contacts:write",
6520
+ "workflows:read",
6521
+ "workflows:write",
6522
+ "connections:read",
6523
+ "connections:write"
6524
+ ];
6525
+ var scopeLabels = {
6526
+ "profile:read": "Read own profile",
6527
+ "profile:write": "Update own profile",
6528
+ "organization:read": "Read organization info",
6529
+ "organization:write": "Manage organization",
6530
+ "campaigns:read": "Read campaigns",
6531
+ "campaigns:write": "Manage campaigns",
6532
+ "contacts:read": "Read contacts",
6533
+ "contacts:write": "Manage contacts",
6534
+ "workflows:read": "Read workflows",
6535
+ "workflows:write": "Manage workflows",
6536
+ "connections:read": "Read integrations",
6537
+ "connections:write": "Manage integrations",
6538
+ "billing:read": "Read billing",
6539
+ "billing:write": "Manage billing",
6540
+ admin: "Admin access"
6541
+ };
6542
+ var toOption = (scope) => ({
6543
+ key: scopeLabels[scope] || scope,
6544
+ value: scope
6545
+ });
6546
+ var developerOptions = developer.map(toOption);
6547
+ var scopeOptions = scopes.map(toOption);
6548
+ var hashToken = (raw) => hash(raw, process.env.HMAC_OAUTH_TOKEN_KEY);
6549
+
6550
+ // lib/sanitize.js
6551
+ import disposableDomains from "disposable-email-domains/index.js";
6552
+ var disposableBlacklist = new Set(disposableDomains.map((d) => d.toLowerCase()));
6553
+ var sanitizeDomain = (value, pattern) => {
6554
+ if (!value) return value;
6555
+ const cleaned = value.trim().toLowerCase().replace(/^https?:\/\//i, "").replace(/\/+$/, "");
6556
+ if (pattern) {
6557
+ const match = cleaned.match(pattern);
6558
+ return match ? match[0] : cleaned;
6559
+ }
6560
+ return cleaned;
6561
+ };
6562
+
6563
+ // lib/slugify.js
6564
+ import slug from "slugify";
6565
+ var slugify = (value, nochars = false) => {
6566
+ const remove = nochars ? /[-?*+~.()'"!:@#^_{}\[\];,/\\]/g : /[?*+~.()'"!:@#^_{}\[\];,/\\]/g;
6567
+ const replacement = nochars ? "" : "-";
6568
+ return slug(
6569
+ value,
6570
+ {
6571
+ remove,
6572
+ replacement,
6573
+ lower: true,
6574
+ trim: true
6575
+ }
6576
+ );
6577
+ };
6578
+
6579
+ // lib/connections/manifests/shopify.js
6580
+ var client = Object.freeze({
6581
+ admin: admin_exports,
6582
+ billing: billing_exports,
6583
+ oauth: oauth_exports,
6584
+ partner: partner_exports,
6585
+ storefront: storefront_exports
6586
+ });
6587
+ var toLine = ({
6588
+ price,
6589
+ product_id: productId,
6590
+ quantity,
6591
+ title,
6592
+ variant_id: variantId,
6593
+ variant_title: variantTitle
6594
+ }) => ({
6595
+ price: parseFloat(price) || 0,
6596
+ productId: productId ? "gid://shopify/Product/" + productId : null,
6597
+ quantity: quantity || 1,
6598
+ title: title || null,
6599
+ variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
6600
+ variantTitle: variantTitle || null
6601
+ });
6602
+ var attributeLineItems = (lineItems = []) => lineItems.reduce(
6603
+ (acc, item) => {
6604
+ const attrs = (item.properties || []).reduce(
6605
+ (map, { name, value }) => {
6606
+ map[name] = value;
6607
+ return map;
6608
+ },
6609
+ {}
6610
+ );
6611
+ if (!attrs["_drwbrdg_ca"]) return acc;
6612
+ if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
6613
+ const line = toLine(item);
6614
+ acc.attributedGross += line.price * line.quantity;
6615
+ acc.attributedLines.push(line);
6616
+ return acc;
6617
+ },
6618
+ { attrMap: {}, attributedGross: 0, attributedLines: [] }
6619
+ );
6620
+ var generateDiscountCode = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
6621
+ var blockedReason = (discount) => {
6622
+ var _a;
6623
+ if ((discount == null ? void 0 : discount.status) === "EXPIRED") return "This discount has expired.";
6624
+ const buyers = (_a = discount == null ? void 0 : discount.context) == null ? void 0 : _a.__typename;
6625
+ if (buyers && buyers !== "DiscountBuyerSelectionAll") {
6626
+ 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.";
6627
+ }
6628
+ ;
6629
+ if (typeof (discount == null ? void 0 : discount.usageLimit) === "number" && discount.usageLimit > 0 && ((discount == null ? void 0 : discount.asyncUsageCount) || 0) >= discount.usageLimit) {
6630
+ return "This discount has reached its total usage limit.";
6631
+ }
6632
+ ;
6633
+ return null;
6634
+ };
6635
+ var discountWarning = (discount) => {
6636
+ if ((discount == null ? void 0 : discount.status) === "SCHEDULED") {
6637
+ return "This discount hasn't started yet, so codes issued before it does won't work until then.";
6638
+ }
6639
+ ;
6640
+ if (discount == null ? void 0 : discount.appliesOncePerCustomer) return "Each customer can use this discount only once.";
6641
+ return null;
6642
+ };
6643
+ var ORDER_EVENT_HANDLE = slugify("drawbridge-orders");
6644
+ var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
6645
+ var OAUTH_ERROR_SOURCE = "oauth";
6646
+ var BILLING_ERROR_SOURCE = "billing";
6647
+ var BILLING_ERROR_MESSAGE = "Order billing isn't set up for this store \u2014 reselect and approve the plan from the Shopify connection page.";
6648
+ var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
6649
+ var inbound = {
6650
+ headers: {
6651
+ event: "x-shopify-topic",
6652
+ id: "x-shopify-webhook-id",
6653
+ shop: "x-shopify-shop-domain",
6654
+ signature: "x-shopify-hmac-sha256"
6655
+ },
6656
+ signature: {
6657
+ algorithm: "sha256",
6658
+ encoding: "base64",
6659
+ secret: "SHOPIFY_API_SECRET"
6660
+ }
6661
+ };
6662
+ var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
6663
+ "customers/data_request",
6664
+ "customers/redact",
6665
+ "shop/redact"
6666
+ ]);
6667
+ var refusal = (message, status) => Object.assign(new Error(message), { status });
6668
+ var LINK_TOKEN_TTL_MS = 30 * 60 * 1e3;
6669
+ var CONNECTABLE_STATUSES = ["active", "unsubscribed"];
6670
+ var merchantOrganizations = ({ read, user }) => read.aggregate({
6671
+ collection: "organization",
6672
+ pipeline: [
6673
+ // A member qualifies only at `manage`; an owner always qualifies.
6674
+ {
6675
+ $lookup: {
6676
+ as: "membership",
6677
+ from: "member",
6678
+ let: { organization: "$id" },
6679
+ pipeline: [
6680
+ {
6681
+ $match: {
6682
+ $expr: { $eq: ["$organization", "$$organization"] },
6683
+ "capabilities.connections": "manage",
6684
+ status: "accepted",
6685
+ user
6686
+ }
6687
+ },
6688
+ { $limit: 1 },
6689
+ { $project: { _id: 0, organization: 1 } }
6690
+ ]
6691
+ }
6692
+ },
6693
+ {
6694
+ $match: {
6695
+ status: { $ne: "canceled" },
6696
+ $or: [{ owner: user }, { "membership.0": { $exists: true } }]
6697
+ }
6698
+ },
6699
+ // `organization.subscription` is a subscription RECORD ID — resolved here so
6700
+ // the list can read the real plan and conversion rate. Without it every org
6701
+ // rendered as free tier.
6702
+ { $lookup: { as: "subscription", foreignField: "id", from: "subscription", localField: "subscription" } },
6703
+ { $unwind: { path: "$subscription", preserveNullAndEmptyArrays: true } },
6704
+ {
6705
+ $lookup: {
6706
+ as: "connection",
6707
+ foreignField: "organization",
6708
+ from: "connection",
6709
+ localField: "id",
6710
+ pipeline: [
6711
+ { $match: { slug: "shopify" } },
6712
+ { $limit: 1 },
6713
+ { $project: { _id: 0, id: 1, shop: 1, status: 1 } }
6714
+ ]
6715
+ }
6716
+ },
6717
+ { $unwind: { path: "$connection", preserveNullAndEmptyArrays: true } },
6718
+ { $project: { _id: 0, billingStatus: "$status", connection: 1, id: 1, name: "$title", subscription: 1 } },
6719
+ { $sort: { name: 1 } }
6720
+ ]
6721
+ });
6722
+ var storePlan = async ({ record, shopify }) => {
6723
+ var _a;
6724
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
6725
+ if (!(settings == null ? void 0 : settings.accessToken)) return { active: false, name: null };
6726
+ try {
6727
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
6728
+ adminAccessToken: settings.accessToken,
6729
+ domain: record.shop
6730
+ });
6731
+ const active = (subscriptions || []).length > 0;
6732
+ const metered = active && subscriptions.some((subscription) => subscription.metered === true) ? true : null;
6733
+ return { active, metered, name: active ? ((_a = subscriptions[0]) == null ? void 0 : _a.name) || null : null };
6734
+ } catch (_) {
6735
+ return { active: false, name: null, unavailable: true };
6736
+ }
6737
+ };
6738
+ var releaseApprovals = async ({ context, read, shopify }) => {
6739
+ var _a;
6740
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
6741
+ if (!shop) throw refusal("shop is required", 400);
6742
+ const record = await read.get({ collection: "shop", query: { shop } });
6743
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
6744
+ if (!(settings == null ? void 0 : settings.accessToken)) throw refusal("Store is not installed", 409);
6745
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
6746
+ adminAccessToken: settings.accessToken,
6747
+ domain: shop
6748
+ });
6749
+ for (const subscription of subscriptions || []) {
6750
+ const data = await shopify.admin.adminFetch({
6751
+ adminAccessToken: settings.accessToken,
6752
+ domain: shop,
6753
+ query: "mutation appSubscriptionCancel( $id : ID! ) { appSubscriptionCancel( id : $id ) { appSubscription { id status } userErrors { field message } } }",
6754
+ variables: { id: subscription.id }
6755
+ });
6756
+ const [userError] = ((_a = data == null ? void 0 : data.appSubscriptionCancel) == null ? void 0 : _a.userErrors) || [];
6757
+ if (userError) throw refusal(userError.message, 422);
6758
+ }
6759
+ return {
6760
+ message: "Released " + (subscriptions || []).length + " approval(s).",
6761
+ request: { shop },
6762
+ result: { ok: true }
6763
+ };
6764
+ };
6765
+ var LEDGER_WINDOW_MS = 30 * 24 * 60 * 60 * 1e3;
6766
+ var meterVerdict = async ({ adminAccessToken, ledgerFloor, partner, shop, shopId, shopify }) => {
6767
+ var _a;
6768
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({ adminAccessToken, domain: shop });
6769
+ let metered = (_a = subscriptions.find((subscription) => subscription.usageLineItemId)) == null ? void 0 : _a.usageLineItemId;
6770
+ if (!((partner == null ? void 0 : partner.partnerToken) && (partner == null ? void 0 : partner.partnerOrgId) && (partner == null ? void 0 : partner.partnerAppId) && shopId)) {
6771
+ return { boundaries: [], ledger: false, metered };
6772
+ }
6773
+ const accruals = await shopify.partner.getUsageChargeEvents({
6774
+ appId: "gid://shopify/App/" + partner.partnerAppId,
6775
+ first: 10,
6776
+ occurredAtMin: ledgerFloor.toISOString(),
6777
+ organizationId: partner.partnerOrgId,
6778
+ partnerToken: partner.partnerToken,
6779
+ shopId: "gid://shopify/Shop/" + shopId
6780
+ });
6781
+ const boundaries = (accruals || []).filter((event) => event.occurredAt).sort((a, b) => new Date(a.occurredAt) - new Date(b.occurredAt));
6782
+ const accrued = [...boundaries].reverse().find((event) => Number(event.usageQuantity) > 0);
6783
+ if (accrued) metered = String(accrued.chargeId || accrued.id);
6784
+ return { boundaries, ledger: true, metered };
6785
+ };
6786
+ var toVariant = (edge) => {
6787
+ var _a, _b, _c, _d;
6788
+ return {
6789
+ availableForSale: edge.node.availableForSale || false,
6790
+ currency: ((_a = edge.node.price) == null ? void 0 : _a.currencyCode) || null,
6791
+ id: edge.node.id,
6792
+ image: ((_b = edge.node.image) == null ? void 0 : _b.url) || null,
6793
+ price: parseFloat((_c = edge.node.price) == null ? void 0 : _c.amount) || null,
6794
+ requiresShipping: edge.node.requiresShipping || false,
6795
+ sale: parseFloat((_d = edge.node.compareAtPrice) == null ? void 0 : _d.amount) || null,
6796
+ title: edge.node.title !== "Default Title" ? edge.node.title : null
6797
+ };
6798
+ };
6799
+ var applyOutOfStock = async ({ domain, shopify, storefrontAccessToken, variants }) => {
6800
+ try {
6801
+ const outOfStock = new Set(await shopify.storefront.probeVariantsOutOfStock({
6802
+ domain,
6803
+ storefrontAccessToken,
6804
+ variantIds: variants.map((variant) => variant.id)
6805
+ }));
6806
+ return variants.map((variant) => ({
6807
+ ...variant,
6808
+ availableForSale: variant.availableForSale && !outOfStock.has(variant.id)
6809
+ }));
6810
+ } catch (_) {
6811
+ return variants;
6812
+ }
6813
+ };
6814
+ var sendFeedback = async ({ adminToken, connection: connection2, messages, productId, shopify, state }) => {
6815
+ try {
6816
+ await shopify.admin.sendProductResourceFeedback({
6817
+ adminAccessToken: await adminToken(),
6818
+ domain: connection2.shop,
6819
+ messages,
6820
+ productId,
6821
+ state
6822
+ });
6823
+ return null;
6824
+ } catch (error) {
6825
+ return error;
6826
+ }
6827
+ };
6828
+ var resolveProduct = async ({ connection: connection2, context, read }) => {
6829
+ const byId = (context == null ? void 0 : context.product) ? await read.get({ collection: "product", query: { id: context.product } }) : null;
6830
+ const row2 = byId || ((context == null ? void 0 : context.providerId) && ((context == null ? void 0 : context.shop) || (connection2 == null ? void 0 : connection2.shop)) ? await read.get({
6831
+ collection: "product",
6832
+ query: {
6833
+ "provider.id": context.providerId,
6834
+ "provider.slug": "shopify",
6835
+ "source.domain": context.shop || connection2.shop
6836
+ }
6837
+ }) : null);
6838
+ return row2;
6839
+ };
6840
+ var UNAVAILABLE_FEEDBACK = "Drawbridge can't display this product. Check it is active and available in the United States.";
6841
+ var NOT_FOUND = "Shopify product not found";
6842
+ var syncProduct = async ({ adminToken, connection: connection2, context, read, settings, shopify }) => {
6843
+ var _a, _b, _c;
6844
+ const row2 = await resolveProduct({ connection: connection2, context, read });
6845
+ if (!row2) return { message: "No product row to sync.", request: { product: (context == null ? void 0 : context.product) || null }, skipped: true };
6846
+ const domain = connection2.shop;
6847
+ const providerId = (_a = row2.provider) == null ? void 0 : _a.id;
6848
+ const request2 = { product: row2.id, providerId: providerId || null, shop: domain };
6849
+ let product;
6850
+ try {
6851
+ product = await shopify.storefront.getProduct({
6852
+ domain,
6853
+ productId: providerId,
6854
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
6855
+ });
6856
+ } catch (error) {
6857
+ if (error.message !== NOT_FOUND) throw error;
6858
+ const failed2 = await sendFeedback({
6859
+ adminToken,
6860
+ connection: connection2,
6861
+ messages: [UNAVAILABLE_FEEDBACK],
6862
+ productId: providerId,
6863
+ shopify,
6864
+ state: "REQUIRES_ACTION"
6865
+ });
6866
+ return {
6867
+ failed: failed2 ? [failed2.message] : void 0,
6868
+ message: "Storefront cannot see this product \u2014 deactivated.",
6869
+ request: request2,
6870
+ result: { status: "inactive" },
6871
+ writes: [
6872
+ {
6873
+ collection: "product",
6874
+ data: { $set: { status: "inactive" } },
6875
+ operation: "update",
6876
+ query: { id: row2.id }
6877
+ },
6878
+ {
6879
+ collection: "advertisement",
6880
+ data: { $set: { status: "drafted" } },
6881
+ multiple: true,
6882
+ operation: "update",
6883
+ query: { product: row2.id }
6884
+ }
6885
+ ]
6886
+ };
6887
+ }
6888
+ const variants = await applyOutOfStock({
6889
+ domain,
6890
+ shopify,
6891
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken,
6892
+ variants: (((_b = product == null ? void 0 : product.variants) == null ? void 0 : _b.edges) || []).map(toVariant)
6893
+ });
6894
+ const failed = await sendFeedback({
6895
+ adminToken,
6896
+ connection: connection2,
6897
+ messages: [],
6898
+ productId: providerId,
6899
+ shopify,
6900
+ state: "ACCEPTED"
6901
+ });
6902
+ return {
6903
+ // EVERYTHING PAST THE FIRST PAGE, filled in silently. The first page is
6904
+ // written above; a product with thousands of variants becomes N short
6905
+ // sequential jobs rather than one long loop that risks a BullMQ stall.
6906
+ enqueues: [{
6907
+ data: { operation: "variants", product: row2.id },
6908
+ name: "sync",
6909
+ options: { jobId: "product.shopify.variants." + row2.id + "." + Date.now() },
6910
+ queue: "product.shopify.variants"
6911
+ }],
6912
+ failed: failed ? [failed.message] : void 0,
6913
+ message: "Synced " + (product.title || "product") + ".",
6914
+ request: request2,
6915
+ result: { status: "active", variants: variants.length },
6916
+ writes: [{
6917
+ collection: "product",
6918
+ data: {
6919
+ $set: {
6920
+ description: product.description || null,
6921
+ image: ((_c = product.featuredImage) == null ? void 0 : _c.url) || null,
6922
+ // A successful sync PROVES channel visibility, which reverses the
6923
+ // deactivation above. Ads stay drafted.
6924
+ status: "active",
6925
+ title: product.title || null,
6926
+ type: product.productType || null,
6927
+ url: domain && product.handle ? "https://" + domain + "/products/" + product.handle : null,
6928
+ variants
6929
+ }
6930
+ },
6931
+ operation: "update",
6932
+ query: { id: row2.id }
6933
+ }]
6934
+ };
6935
+ };
6936
+ var syncVariants = async ({ connection: connection2, context, read, settings, shopify }) => {
6937
+ var _a, _b, _c;
6938
+ const row2 = await resolveProduct({ connection: connection2, context, read });
6939
+ if (!row2) return { message: "No product row to paginate.", request: { product: (context == null ? void 0 : context.product) || null }, skipped: true };
6940
+ const cursor = (context == null ? void 0 : context.cursor) || null;
6941
+ const request2 = { cursor, product: row2.id };
6942
+ let page2;
6943
+ try {
6944
+ page2 = await shopify.storefront.getProductVariantsPage({
6945
+ cursor,
6946
+ domain: connection2.shop,
6947
+ productId: (_a = row2.provider) == null ? void 0 : _a.id,
6948
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
6949
+ });
6950
+ } catch (error) {
6951
+ if (error.message !== NOT_FOUND) throw error;
6952
+ return { message: "Storefront lost this product mid-pagination \u2014 stopping.", request: request2, skipped: true };
6953
+ }
6954
+ const variants = await applyOutOfStock({
6955
+ domain: connection2.shop,
6956
+ shopify,
6957
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken,
6958
+ variants: (page2.edges || []).map(toVariant)
6959
+ });
6960
+ return {
6961
+ ...((_b = page2.pageInfo) == null ? void 0 : _b.hasNextPage) && { enqueues: [{
6962
+ data: { cursor: page2.pageInfo.endCursor, operation: "variants", product: row2.id },
6963
+ name: "page",
6964
+ options: { jobId: "product.shopify.variants." + row2.id + "." + Date.now() },
6965
+ queue: "product.shopify.variants"
6966
+ }] },
6967
+ message: variants.length + " variant(s) on this page.",
6968
+ request: request2,
6969
+ result: { hasNextPage: Boolean((_c = page2.pageInfo) == null ? void 0 : _c.hasNextPage), variants: variants.length },
6970
+ writes: [{
6971
+ collection: "product",
6972
+ data: cursor ? { $push: { variants: { $each: variants } } } : { $set: { variants } },
6973
+ operation: "update",
6974
+ query: { id: row2.id }
6975
+ }]
6976
+ };
6977
+ };
6978
+ var shopify_default2 = {
6979
+ // THE WORDS ON THE BUTTONS. `listing` was `content.redirect.title`, which put
6980
+ // a BUTTON LABEL inside the copy object next to a url — the title and the
6981
+ // address it belongs to sat at different levels and could drift apart.
6982
+ //
6983
+ // It names where the link GOES rather than what it does: installing happens on
6984
+ // the App Store listing, and the dashboard must never imply a store can be
6985
+ // linked from inside it.
6986
+ actions: {
6987
+ create: null,
6988
+ listing: "View on the Shopify App Store",
6989
+ manage: null,
6990
+ update: null
6991
+ },
6992
+ // INSTALL, not oauth. The grant is an OAuth grant, but the merchant never
6993
+ // sees a consent screen we sent them to -- they start at the App Store, and
6994
+ // the install completes inside Shopify admin without redirecting back. A
6995
+ // Connect button here would be lying about where connecting happens.
6996
+ auth: {
6997
+ // ONE STORE PER ORGANIZATION. A Shopify install IS a store, and a second
6998
+ // one would give an organization two catalogues, two order streams and two
6999
+ // usage meters with nothing to say which is authoritative.
7000
+ //
7001
+ // DECLARED AND ENFORCED BY NOTHING, measured 2026-09-13: no repo reads this
7002
+ // key, and the connection collection's { organization, slug } index is not
7003
+ // unique. So a second Shopify connection would be accepted today. The gate
7004
+ // belongs at the connect route with a unique partial index behind it, and
7005
+ // that is api work — this is the declaration it will read.
4961
7006
  exclusive: true,
4962
7007
  generated: false,
4963
7008
  // THE MERCHANT STARTS AT SHOPIFY, not here. They install the app from
@@ -5116,8 +7161,8 @@ var shopify_default2 = {
5116
7161
  // string; this answers what is missing from it.
5117
7162
  //
5118
7163
  // `shopify` is injected for the same reason it is everywhere else — this
5119
- // package cannot import @drawbridge/shopify, which depends on it.
5120
- scopes: ({ scope }, { shopify } = {}) => ({ result: { missing: scope ? shopify.oauth.missingScopes(scope) : null } }),
7164
+ // client is imported here and defaulted, never wired in by a caller.
7165
+ scopes: ({ scope }, { shopify = client } = {}) => ({ result: { missing: scope ? shopify.oauth.missingScopes(scope) : null } }),
5121
7166
  // Shopify's install grant is exchanged inside its own app flow, not
5122
7167
  // through the shared OAuth runner.
5123
7168
  token: false
@@ -5131,17 +7176,53 @@ var shopify_default2 = {
5131
7176
  // can reference another), `dispatch` (the caller's own coordinator table,
5132
7177
  // for the hooks that are dispatches).
5133
7178
  commerce: {
5134
- // NOT YET. The Checkout Kit cart path is `api/route/subdomain.js`, six direct
5135
- // calls into `@drawbridge/shopify/storefront` that write nothing — which is
5136
- // exactly why it never became a hook: a hook is reached to have its effects
5137
- // performed, and this one has none to perform. It moves here when the vendor
5138
- // client moves into the manifest and `subdomain.js` stops importing the
5139
- // package directly.
5140
- cart: false,
7179
+ // THE CHECKOUT KIT CART. Six operations that were six direct calls into
7180
+ // the storefront client from api/route/subdomain.js.
7181
+ //
7182
+ // IT WRITES NOTHING, which is exactly why it was the last surface to
7183
+ // become a hook a hook is usually reached to have its effects performed
7184
+ // and this one has none. That reasoning was wrong: a hook is also the one
7185
+ // place a vendor's client is allowed to be called from, and leaving the
7186
+ // cart out meant a public route importing a vendor SDK directly.
7187
+ //
7188
+ // ONE HOOK, OPERATION IN THE CONTEXT, the same shape `inbound.process`
7189
+ // uses for its topic table. Six slots would be six names in the closed
7190
+ // vocabulary for one question — what does this shopper's cart look like
7191
+ // now — asked six ways.
7192
+ //
7193
+ // A USER ERROR IS A 400 AND THE SHOPPER'S OWN WORDS. Shopify's cart
7194
+ // mutations answer "that variant is sold out" as a userError rather than a
7195
+ // transport failure, and the route it replaced already told the two apart.
7196
+ // runHook carries `status` off a thrown error, so it survives to the
7197
+ // caller; the rest of a thrown error's shape does not.
7198
+ cart: async ({ clientId, clientSecret, context, settings }, { fetcher, shopify = client } = {}) => {
7199
+ const { cartId, lineIds, lines, operation } = context || {};
7200
+ const { domain, storefrontAccessToken } = settings || {};
7201
+ if (operation === "checkout") {
7202
+ const token = await shopify.storefront.createCheckoutToken({ clientId, clientSecret, fetcher });
7203
+ return { message: "Checkout token minted.", result: { token } };
7204
+ }
7205
+ const storefront = { domain, fetcher, storefrontAccessToken };
7206
+ try {
7207
+ const cart = await ({
7208
+ create: () => shopify.storefront.cartCreate({ ...storefront, lines }),
7209
+ get: () => shopify.storefront.cartGet({ ...storefront, cartId }),
7210
+ linesAdd: () => shopify.storefront.cartLinesAdd({ ...storefront, cartId, lines }),
7211
+ linesRemove: () => shopify.storefront.cartLinesRemove({ ...storefront, cartId, lineIds }),
7212
+ linesUpdate: () => shopify.storefront.cartLinesUpdate({ ...storefront, cartId, lines })
7213
+ }[operation] || (() => {
7214
+ throw Object.assign(new Error("Unknown cart operation: " + operation), { status: 400 });
7215
+ }))();
7216
+ return { message: "Cart " + operation + ".", request: { cartId: cartId || null, operation }, result: cart };
7217
+ } catch (error) {
7218
+ if (error == null ? void 0 : error.userError) throw Object.assign(error, { status: 400 });
7219
+ throw error;
7220
+ }
7221
+ },
5141
7222
  // MINT A DISCOUNT CODE against the merchant's chosen discount, mapped to
5142
7223
  // one lead — which is what lets an order that redeems it be attributed
5143
7224
  // back.
5144
- code: async ({ connection: connection2, context, step }, { adminToken, shopify } = {}) => {
7225
+ code: async ({ connection: connection2, context, step }, { adminToken, shopify = client } = {}) => {
5145
7226
  var _a;
5146
7227
  const discount = (_a = step.settings) == null ? void 0 : _a.discount;
5147
7228
  const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
@@ -5187,7 +7268,7 @@ var shopify_default2 = {
5187
7268
  // customer at the store is a support ticket: the context may already
5188
7269
  // carry the id from an earlier step, the lead may already be linked from
5189
7270
  // an earlier run, and Shopify's own get-or-create settles the rest.
5190
- customer: async ({ connection: connection2, context }, { adminToken, read, shopify } = {}) => {
7271
+ customer: async ({ connection: connection2, context }, { adminToken, read, shopify = client } = {}) => {
5191
7272
  const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
5192
7273
  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 };
5193
7274
  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 };
@@ -5237,6 +7318,30 @@ var shopify_default2 = {
5237
7318
  }]
5238
7319
  };
5239
7320
  },
7321
+ // HOW MANY ARE LEFT. Read at the moment a campaign's product list is
7322
+ // rendered rather than stored on the product, because stock is the one
7323
+ // product fact that is stale the instant it is written down.
7324
+ //
7325
+ // SUMMED HERE, not by the caller. Shopify answers per variant and every
7326
+ // caller wanted the total; the one that existed summed it inline, and
7327
+ // summing `Object.values()` over the raw map is how a cache wrapper's own
7328
+ // bookkeeping key got counted as a quantity.
7329
+ inventory: async ({ connection: connection2, context }, { adminToken, shopify = client } = {}) => {
7330
+ const productId = context == null ? void 0 : context.product;
7331
+ const request2 = { product: productId || null, shop: connection2.shop };
7332
+ if (!productId) return { message: "No product id \u2014 nothing to count.", request: request2, result: { total: null }, skipped: true };
7333
+ const adminAccessToken = await adminToken();
7334
+ const byVariant = await shopify.admin.getProductInventory({
7335
+ adminAccessToken,
7336
+ domain: connection2.shop,
7337
+ productId
7338
+ });
7339
+ return {
7340
+ message: "Inventory read.",
7341
+ request: request2,
7342
+ result: { total: Object.values(byVariant || {}).reduce((sum, quantity) => sum + quantity, 0) }
7343
+ };
7344
+ },
5240
7345
  // AN ORDER ARRIVED AT THE STORE. The largest hook in the family, because
5241
7346
  // attribution genuinely is: an order can reach Drawbridge two ways and
5242
7347
  // they bill differently.
@@ -5596,10 +7701,28 @@ var shopify_default2 = {
5596
7701
  //
5597
7702
  // The shell has already refused a missing or inactive Shopify connection,
5598
7703
  // so what is left is the two things only this hook can know are wrong.
5599
- product: async ({ connection: connection2, context, workflow }, { mintId, read } = {}) => {
7704
+ // A PRODUCT, IN THREE MOVES. Nested by operation rather than by three
7705
+ // slots in the closed vocabulary, the same shape inbound.process uses
7706
+ // for its topic table — they are one subject, and a vendor that syncs
7707
+ // products has to answer all three or none.
7708
+ //
7709
+ // record a webhook said a product changed: upsert the row and
7710
+ // queue the pull
7711
+ // sync pull the product from the storefront and write what it
7712
+ // says, including what it says by NOT answering
7713
+ // variants one page of variants, self-chaining
7714
+ //
7715
+ // `sync` and `variants` were 443 lines of drawbridge-sync's
7716
+ // queue/product.js — a shadow implementation of the step this manifest
7717
+ // already declared, importing three of the vendor's client modules from
7718
+ // a worker file.
7719
+ product: async ({ connection: connection2, context, settings, workflow }, { adminToken, mintId, read, shopify = client } = {}) => {
7720
+ const operation = (context == null ? void 0 : context.operation) || "record";
7721
+ if (operation === "sync") return syncProduct({ adminToken, connection: connection2, context, read, settings, shopify });
7722
+ if (operation === "variants") return syncVariants({ connection: connection2, context, read, settings, shopify });
5600
7723
  const request2 = {
5601
7724
  numericId: (context == null ? void 0 : context.id) || null,
5602
- organizationId: workflow.organization,
7725
+ organizationId: (workflow == null ? void 0 : workflow.organization) || null,
5603
7726
  title: (context == null ? void 0 : context.title) || null
5604
7727
  };
5605
7728
  if (!(context == null ? void 0 : context.id)) return { message: "Skipped \u2014 product webhook payload had no id.", request: request2, response: { skipped: true }, skipped: true };
@@ -5649,9 +7772,612 @@ var shopify_default2 = {
5649
7772
  }
5650
7773
  },
5651
7774
  contacts: { remove: false, sync: false },
5652
- // The embedded-app surface. Only a vendor whose merchants arrive from its
5653
- // own app store has one.
5654
- install: false,
7775
+ // THE EMBEDDED-APP SURFACE. Only a vendor whose merchants arrive from its
7776
+ // own app store has one, and these thirteen slots are the thirteen routes
7777
+ // that used to live in api/route/shopify-embedded.js.
7778
+ //
7779
+ // A HOOK DESCRIBES ITS WRITES and the shell performs them, so none of these
7780
+ // holds a controller — `read` is the controller's read methods and nothing
7781
+ // else. Where one REFUSES it throws with a status, and the route answers
7782
+ // what it said. The helpers they share are above the manifest.
7783
+ install: {
7784
+ account: {
7785
+ // ESTABLISH THE DURABLE MERCHANT-TO-STORE LINK. The breakout
7786
+ // authenticates the merchant once, top-level, and stashes their user
7787
+ // token in `install.token.save`; App Bridge has already proven shop
7788
+ // control by the time this runs.
7789
+ //
7790
+ // THE STASHED TOKEN IS THE TRUST ANCHOR, not merely any valid user
7791
+ // token: the presented one must BE this shop's one-shot handoff token,
7792
+ // unexpired, and an access or pat record — a refresh or oauth-state
7793
+ // token that happens to resolve to a user must not qualify, which is
7794
+ // the rule a session is held to in drawbridge-api's middleware.
7795
+ link: async ({ context }, { read } = {}) => {
7796
+ var _a;
7797
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
7798
+ const token = context == null ? void 0 : context.token;
7799
+ if (!shop || !token) throw refusal("shop and token are required", 400);
7800
+ const now = /* @__PURE__ */ new Date();
7801
+ const record = await read.get({ collection: "shop", query: { shop } });
7802
+ const stashed = (record == null ? void 0 : record.linkToken) ? (_a = decrypt(record.linkToken)) == null ? void 0 : _a.token : null;
7803
+ const expired = !(record == null ? void 0 : record.linkTokenExpiresAt) || new Date(record.linkTokenExpiresAt) <= now;
7804
+ if (!stashed || expired || stashed !== token) throw refusal("Invalid or expired link token", 401);
7805
+ const granted = await read.get({
7806
+ collection: "token",
7807
+ query: {
7808
+ revoked: false,
7809
+ tokenHash: hashToken(token),
7810
+ type: { $in: [tokenTypes.access, tokenTypes.pat] }
7811
+ }
7812
+ });
7813
+ if (!(granted == null ? void 0 : granted.user) || granted.expiresAt && new Date(granted.expiresAt) <= now) {
7814
+ throw refusal("Invalid or expired link token", 401);
7815
+ }
7816
+ const switching = Boolean(record == null ? void 0 : record.user) && record.user !== granted.user;
7817
+ const connections2 = switching ? await read.aggregate({
7818
+ collection: "connection",
7819
+ pipeline: [
7820
+ { $match: { shop, slug: "shopify" } },
7821
+ { $project: { _id: 0, id: 1 } }
7822
+ ]
7823
+ }) : [];
7824
+ return {
7825
+ message: switching ? "Linked to a different Drawbridge account." : "Linked.",
7826
+ request: { shop },
7827
+ result: { connected: true, switched: switching },
7828
+ // ALL OR NONE. A half-done switch is a store linked to the new
7829
+ // account while the old account's connections still serve from it.
7830
+ transaction: true,
7831
+ writes: [
7832
+ ...(connections2 || []).map((connection2) => ({
7833
+ collection: "connection",
7834
+ operation: "delete",
7835
+ query: { id: connection2.id }
7836
+ })),
7837
+ {
7838
+ collection: "shop",
7839
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null, user: granted.user } },
7840
+ operation: "update",
7841
+ query: { shop }
7842
+ }
7843
+ ]
7844
+ };
7845
+ },
7846
+ // DISCONNECT THE ACCOUNT FROM THE STORE. Every org connection goes and
7847
+ // the durable link clears; the offline token and the shop record stay,
7848
+ // because the app is still installed and the merchant may link a
7849
+ // different account next.
7850
+ unlink: async ({ context }, { read } = {}) => {
7851
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
7852
+ if (!shop) throw refusal("shop is required", 400);
7853
+ const connections2 = await read.aggregate({
7854
+ collection: "connection",
7855
+ pipeline: [
7856
+ { $match: { shop, slug: "shopify" } },
7857
+ { $project: { _id: 0, id: 1 } }
7858
+ ]
7859
+ });
7860
+ return {
7861
+ message: "Unlinked " + (connections2 || []).length + " connection(s).",
7862
+ request: { shop },
7863
+ result: { ok: true },
7864
+ transaction: true,
7865
+ writes: [
7866
+ ...(connections2 || []).map((connection2) => ({
7867
+ collection: "connection",
7868
+ operation: "delete",
7869
+ query: { id: connection2.id }
7870
+ })),
7871
+ {
7872
+ collection: "shop",
7873
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null, user: null } },
7874
+ operation: "update",
7875
+ query: { shop }
7876
+ }
7877
+ ]
7878
+ };
7879
+ }
7880
+ },
7881
+ organizations: {
7882
+ // BIND ONE ORGANIZATION TO THIS STORE. The longest slot here, and every
7883
+ // gate in it came from a line in the route it replaces.
7884
+ add: async ({ context }, { currencies, mintId, read, shopify = client } = {}) => {
7885
+ var _a, _b;
7886
+ const organization2 = context == null ? void 0 : context.organization;
7887
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
7888
+ if (!shop) throw refusal("shop is required", 400);
7889
+ if (!organization2) throw refusal("organization is required", 400);
7890
+ const record = await read.get({ collection: "shop", query: { shop } });
7891
+ if (!(record == null ? void 0 : record.user)) throw refusal("Account is not connected for this store", 409);
7892
+ const owned = await merchantOrganizations({ read, user: record.user });
7893
+ const org = (owned || []).find((entry) => entry.id === organization2);
7894
+ if (!org) throw refusal("No access to this organization", 403);
7895
+ if (!CONNECTABLE_STATUSES.includes(org.billingStatus)) {
7896
+ throw refusal("This organization can't accept connections right now \u2014 check its billing status in the dashboard", 403);
7897
+ }
7898
+ if (org.connection && org.connection.shop !== shop) {
7899
+ throw refusal("This organization is already connected to another Shopify store", 409);
7900
+ }
7901
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
7902
+ if (!(settings == null ? void 0 : settings.accessToken)) {
7903
+ throw refusal("Store is not installed \u2014 open the app in the Shopify admin first", 409);
7904
+ }
7905
+ const plan = await storePlan({ record, shopify });
7906
+ if (plan.unavailable) throw refusal("Couldn't verify the store's plan \u2014 try again shortly", 502);
7907
+ if (!plan.active) throw refusal("Approve a plan before connecting organizations", 402);
7908
+ let storefront = null;
7909
+ if (!record.storefront) {
7910
+ try {
7911
+ const minted2 = await shopify.oauth.createStorefrontToken({
7912
+ adminAccessToken: settings.accessToken,
7913
+ shop
7914
+ });
7915
+ if (minted2) storefront = encrypt({ token: minted2 });
7916
+ } catch (_) {
7917
+ }
7918
+ }
7919
+ let currency = (record == null ? void 0 : record.currency) || null;
7920
+ let source = (record == null ? void 0 : record.source) || null;
7921
+ try {
7922
+ const shopData = await shopify.oauth.getShop({ adminAccessToken: settings.accessToken, shop });
7923
+ if (shopData) {
7924
+ currency = String(shopData.currency || "").toLowerCase() || null;
7925
+ source = { domain: shopData.myshopifyDomain, id: String(shopData.id), label: shopData.name };
7926
+ }
7927
+ } catch (_) {
7928
+ }
7929
+ if (currency && currencies && !currencies.includes(currency)) {
7930
+ throw refusal("This store settles in a currency we can't bill yet. Connect a store with a supported settlement currency.", 422);
7931
+ }
7932
+ const minted = ((_a = org.connection) == null ? void 0 : _a.id) ? null : mintId();
7933
+ const connectionId = ((_b = org.connection) == null ? void 0 : _b.id) || minted.id;
7934
+ return {
7935
+ message: "Connected " + org.name + " to " + shop + ".",
7936
+ request: { organization: organization2, shop },
7937
+ result: { ok: true },
7938
+ transaction: true,
7939
+ writes: [
7940
+ ...storefront ? [{
7941
+ collection: "shop",
7942
+ data: { $set: { storefront } },
7943
+ operation: "update",
7944
+ query: { shop }
7945
+ }] : [],
7946
+ {
7947
+ collection: "connection",
7948
+ data: {
7949
+ $set: {
7950
+ currency,
7951
+ errors: [],
7952
+ // The token of record lives on the shared `shop` row; this
7953
+ // is the pointer that satisfies the required `settings`
7954
+ // string, and `auth.install.shared` declares how to read it.
7955
+ settings: encrypt({ ref: "shop", shop }),
7956
+ shop,
7957
+ status: "pending",
7958
+ ...source && { source }
7959
+ },
7960
+ $setOnInsert: {
7961
+ ...minted && { _id: minted._id, id: minted.id },
7962
+ feature: "organization:connection:shopify",
7963
+ organization: organization2,
7964
+ slug: "shopify"
7965
+ }
7966
+ },
7967
+ operation: "update",
7968
+ options: { upsert: true },
7969
+ query: { organization: organization2, slug: "shopify" }
7970
+ },
7971
+ {
7972
+ collection: "organization",
7973
+ data: {
7974
+ // $addToSet UNCONDITIONALLY. The route this replaces only
7975
+ // registered the refs when the upsert INSERTED, which meant an
7976
+ // org whose refs had drifted stayed drifted through every
7977
+ // re-link. Adding a member that is already there is a no-op,
7978
+ // so doing it every time costs nothing and repairs the drift.
7979
+ $addToSet: {
7980
+ "connections.groups": "ecommerce",
7981
+ "connections.ids": connectionId,
7982
+ "connections.keys": "shopify"
7983
+ },
7984
+ $set: { billingProvider: "shopify" }
7985
+ },
7986
+ operation: "update",
7987
+ query: { id: organization2 }
7988
+ }
7989
+ ]
7990
+ };
7991
+ },
7992
+ // WHAT THIS STORE CAN SEE: the linked merchant's organizations, the
7993
+ // store's live plan, and the products the merchant has to act on.
7994
+ //
7995
+ // AN ORG CONNECTED TO A DIFFERENT STORE IS OMITTED ENTIRELY, because
7996
+ // `add` would refuse it — a list that offers what the next call rejects
7997
+ // is worse than a shorter one.
7998
+ list: async ({ context }, { conversionRate, planTitle, read, shopify = client } = {}) => {
7999
+ var _a;
8000
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8001
+ if (!shop) throw refusal("shop is required", 400);
8002
+ const record = await read.get({ collection: "shop", query: { shop } });
8003
+ if (!(record == null ? void 0 : record.user)) {
8004
+ return {
8005
+ message: "No account linked to this store.",
8006
+ request: { shop },
8007
+ result: {
8008
+ account: null,
8009
+ connected: false,
8010
+ organizations: [],
8011
+ plan: { active: false, name: null },
8012
+ unavailableProducts: [],
8013
+ unavailableProductsTotal: 0
8014
+ }
8015
+ };
8016
+ }
8017
+ const owned = await merchantOrganizations({ read, user: record.user });
8018
+ const organizations = (owned || []).filter((org) => !org.connection || org.connection.shop === shop).map((org) => {
8019
+ var _a2;
8020
+ return {
8021
+ // The org's OWN billing status decides whether `add` accepts it.
8022
+ // Sent up so the app can disable Connect and name the reason
8023
+ // rather than letting the merchant click into a 403 —
8024
+ // listed-but-blocked beats hidden, because an org vanishing from
8025
+ // the list is indistinguishable from a bug.
8026
+ billingStatus: org.billingStatus || null,
8027
+ connectable: CONNECTABLE_STATUSES.includes(org.billingStatus),
8028
+ connected: Boolean(org.connection),
8029
+ conversion: conversionRate(org.subscription),
8030
+ id: org.id,
8031
+ name: org.name,
8032
+ plan: planTitle(org.subscription),
8033
+ status: ((_a2 = org.connection) == null ? void 0 : _a2.status) || null
8034
+ };
8035
+ });
8036
+ const connections2 = (owned || []).filter((org) => {
8037
+ var _a2;
8038
+ return ((_a2 = org.connection) == null ? void 0 : _a2.shop) === shop && org.connection.id;
8039
+ }).map((org) => org.connection.id);
8040
+ const [account, plan, unavailable] = await Promise.all([
8041
+ read.get({ collection: "user", query: { id: record.user } }),
8042
+ storePlan({ record, shopify }),
8043
+ connections2.length ? read.aggregate({
8044
+ collection: "product",
8045
+ pipeline: [
8046
+ { $match: { connections: { $in: connections2 }, "source.domain": shop, status: "inactive" } },
8047
+ // $facet so the app can name the first 25 AND report a
8048
+ // truthful total: listing 25 of 40 under "25 products need
8049
+ // attention" would understate the problem.
8050
+ {
8051
+ $facet: {
8052
+ items: [{ $sort: { title: 1 } }, { $limit: 25 }, { $project: { _id: 0, id: 1, title: 1 } }],
8053
+ total: [{ $count: "count" }]
8054
+ }
8055
+ }
8056
+ ]
8057
+ }) : []
8058
+ ]);
8059
+ const facet = (unavailable || [])[0] || {};
8060
+ if (plan.active && plan.metered !== true) {
8061
+ const stamped = await read.aggregate({
8062
+ collection: "connection",
8063
+ pipeline: [
8064
+ { $match: { shop, slug: "shopify" } },
8065
+ { $project: { _id: 0, "source.metered": 1 } }
8066
+ ]
8067
+ });
8068
+ const verdicts = (stamped || []).map((row2) => {
8069
+ var _a2;
8070
+ return (_a2 = row2 == null ? void 0 : row2.source) == null ? void 0 : _a2.metered;
8071
+ });
8072
+ if (verdicts.some((verdict) => typeof verdict === "string")) plan.metered = true;
8073
+ else if (verdicts.some((verdict) => verdict === null)) plan.metered = false;
8074
+ }
8075
+ return {
8076
+ message: organizations.length + " organization(s) for this store.",
8077
+ request: { shop },
8078
+ result: {
8079
+ account: { email: (account == null ? void 0 : account.email) || null },
8080
+ connected: true,
8081
+ organizations,
8082
+ plan,
8083
+ unavailableProducts: (facet.items || []).map((product) => ({
8084
+ id: product.id,
8085
+ title: product.title || "Untitled product"
8086
+ })),
8087
+ // The total can exceed the 25 listed above, and has to.
8088
+ unavailableProductsTotal: ((_a = (facet.total || [])[0]) == null ? void 0 : _a.count) || 0
8089
+ }
8090
+ };
8091
+ },
8092
+ // DISCONNECT ONE ORGANIZATION. The connection is deleted and nothing
8093
+ // else: every dependent — products, ads, steps, workflows, and the org's
8094
+ // own connection refs — is torn down by drawbridge-sync's connection
8095
+ // change stream. The shared token and the other orgs are untouched.
8096
+ remove: async ({ context }, { read } = {}) => {
8097
+ const organization2 = context == null ? void 0 : context.organization;
8098
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8099
+ if (!shop) throw refusal("shop is required", 400);
8100
+ if (!organization2) throw refusal("organization is required", 400);
8101
+ const record = await read.get({ collection: "shop", query: { shop } });
8102
+ if (!(record == null ? void 0 : record.user)) throw refusal("Account is not connected for this store", 409);
8103
+ const owned = await merchantOrganizations({ read, user: record.user });
8104
+ if (!(owned || []).some((entry) => entry.id === organization2)) {
8105
+ throw refusal("No access to this organization", 403);
8106
+ }
8107
+ const connection2 = await read.get({
8108
+ collection: "connection",
8109
+ query: { organization: organization2, shop, slug: "shopify" }
8110
+ });
8111
+ if (!connection2) throw refusal("No connection to remove", 404);
8112
+ return {
8113
+ message: "Disconnected.",
8114
+ request: { organization: organization2, shop },
8115
+ result: { ok: true },
8116
+ writes: [{ collection: "connection", operation: "delete", query: { id: connection2.id } }]
8117
+ };
8118
+ }
8119
+ },
8120
+ plan: {
8121
+ // RELEASE EVERY ACTIVE APPROVAL. The App Home then re-checks the plan
8122
+ // and falls back to "Choose a plan".
8123
+ cancel: ({ context }, { read, shopify = client } = {}) => releaseApprovals({ context, read, shopify }),
8124
+ // ONE ATTRIBUTED ORDER'S USAGE CHARGE. Enqueued per conversion by the
8125
+ // order step and run on a retrying queue, so this may be called
8126
+ // several times for one order — which is safe because the idempotency
8127
+ // key is PERMANENT for billing events and Shopify settles the repeat.
8128
+ //
8129
+ // THE HANDLE IS CHECKED AGAINST THE MANIFEST'S OWN DECLARATION, which
8130
+ // is a real strengthening of what it replaced: drawbridge-sync compared
8131
+ // the job's `handle` against the job's `transaction` — two fields from
8132
+ // the same enqueuer, so a drifted enqueuer agreed with itself. The
8133
+ // handle is the one string that decides whether the event bills at all,
8134
+ // and this is the file that publishes it.
8135
+ //
8136
+ // REFUSE BEFORE SENDING, because sending burns the order's PERMANENT
8137
+ // idempotency key on an event that misclassifies or mistraces. The
8138
+ // throw rides the queue's normal retry path and the abandoned-job alert
8139
+ // pages on exhaustion.
8140
+ //
8141
+ // DELIBERATELY NO TIMESTAMP. sendAppEvent defaults to the SEND time,
8142
+ // which is always inside the merchant's current billing cycle at the
8143
+ // moment of sending and so can never hit PERIOD_CLOSED. Pinning the
8144
+ // purchase time reads more correct and is strictly worse: a retry
8145
+ // backoff crossing a cycle boundary would carry a closed-cycle
8146
+ // timestamp, Shopify would 202-accept, silently drop it, and the
8147
+ // commission would be lost. Send-time's worst case is benign — the
8148
+ // charge lands in the next cycle, but it lands.
8149
+ charge: async ({ clientId, clientSecret, context, manifest }, { shopify = client } = {}) => {
8150
+ const { idempotencyKey, order, orderId, rate, revision, shopId, timestamp, transaction, value } = context || {};
8151
+ const handle = (context == null ? void 0 : context.handle) || manifest.auth.install.billing.handle;
8152
+ if (!transaction || !String(transaction).startsWith(handle + ".")) {
8153
+ throw new Error("shopify.usage.billing.handle.mismatch on order " + orderId + ": transaction " + (transaction || "null") + " does not carry handle " + handle + " \u2014 refusing to send");
8154
+ }
8155
+ await shopify.billing.sendAppEvent({
8156
+ clientId,
8157
+ clientSecret,
8158
+ eventHandle: handle,
8159
+ idempotencyKey,
8160
+ // The Shopify-side event record names the order that produced it.
8161
+ reference: transaction,
8162
+ // OPERATOR-ONLY, BOTH OF THEM, and absent on every automatic
8163
+ // send. `revision` suffixes the idempotency key, which is what
8164
+ // makes a second attempt possible once a key has been consumed;
8165
+ // the encoding is owned by sendAppEvent so no caller builds keys
8166
+ // itself. `timestamp` pins the PURCHASE time, which the automatic
8167
+ // path must never do — see the note above — and the recovery
8168
+ // migration must, because it is resending orders from a closed
8169
+ // window and bounds its own run to the merchant's current cycle.
8170
+ ...revision && { revision },
8171
+ ...timestamp && { timestamp },
8172
+ shopId,
8173
+ value
8174
+ });
8175
+ return {
8176
+ message: "Usage charge sent for order " + orderId + ".",
8177
+ request: { order: order || null, orderId: orderId || null, shopId: shopId || null, value },
8178
+ result: { transaction: String(transaction) },
8179
+ // TRACEABILITY. The App Events API returns no event id, so the
8180
+ // trace key into Shopify's event logs is the transaction id the
8181
+ // commerce.order hook minted and this sent as `reference`.
8182
+ // `amount` is the per-order usage value in cents, mirroring the
8183
+ // Stripe path's marker.
8184
+ ...order && { writes: [{
8185
+ collection: "order",
8186
+ data: {
8187
+ $set: {
8188
+ billed: {
8189
+ amount: value,
8190
+ date: /* @__PURE__ */ new Date(),
8191
+ rate: rate || 0,
8192
+ transaction: String(transaction)
8193
+ }
8194
+ }
8195
+ },
8196
+ operation: "update",
8197
+ query: { id: order }
8198
+ }] }
8199
+ };
8200
+ },
8201
+ // RESELECT, NOT CANCEL. The same mechanics — the current approval has to
8202
+ // be released before the pricing page will offer the plan again — but
8203
+ // the intent is a thirty-second round trip rather than a departure.
8204
+ //
8205
+ // `mark` IS A DECLARED CAPABILITY, and this is the only slot here that
8206
+ // needs one. The marker has to be persisted BEFORE the approval is
8207
+ // released: it is what tells sync's CANCELLED handler to hold the pause
8208
+ // — no connection error, no owner email — and start a timed recheck that
8209
+ // pauses honestly if the merchant abandons. A described write lands
8210
+ // after the hook returns, which is after the cancel, and a marker
8211
+ // written then can race the very webhook it exists to soften. Same
8212
+ // precedent as `resolveContact`: the one write a description cannot
8213
+ // carry.
8214
+ reselect: async ({ context }, { mark, read, shopify = client } = {}) => {
8215
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8216
+ if (!shop) throw refusal("shop is required", 400);
8217
+ await mark({ shop });
8218
+ return releaseApprovals({ context, read, shopify });
8219
+ },
8220
+ // IS THIS STORE'S ORDER BILLING ACTUALLY METERED? Not a merchant
8221
+ // action — the other two slots here are — but the same subject, and
8222
+ // the reason it is a declared hook rather than a helper is that the
8223
+ // answer was being derived in two places: `lifecycle.health` below,
8224
+ // and drawbridge-sync's app_subscriptions/update handler, whose copy
8225
+ // stated in its own comment that it matched this one and did not.
8226
+ //
8227
+ // THREE ANSWERS, and the caller must keep them apart:
8228
+ //
8229
+ // a string PROVEN. The charge id or usage line id, stamped on
8230
+ // the connection as the evidence.
8231
+ // null PROBED, and nothing is accruing.
8232
+ // undefined NO VERDICT — the probe could not run. `probed` says
8233
+ // which, because undefined does not survive JSON.
8234
+ verify: async ({ context }, { adminToken, read, shopify = client } = {}) => {
8235
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8236
+ if (!shop) throw refusal("shop is required", 400);
8237
+ const adminAccessToken = await adminToken();
8238
+ if (!adminAccessToken) {
8239
+ return { message: "No admin token for this store \u2014 no verdict.", request: { shop }, result: { metered: null, probed: false }, skipped: true };
8240
+ }
8241
+ const partnerRow = (read == null ? void 0 : read.get) ? await read.get({ collection: "provider", query: { slug: "shopify" } }) : null;
8242
+ const partner = (partnerRow == null ? void 0 : partnerRow.settings) ? decrypt(partnerRow.settings) : {};
8243
+ const { ledger, metered } = await meterVerdict({
8244
+ adminAccessToken,
8245
+ ledgerFloor: new Date(Date.now() - LEDGER_WINDOW_MS),
8246
+ partner,
8247
+ shop,
8248
+ shopId: (context == null ? void 0 : context.shopId) || null,
8249
+ shopify
8250
+ });
8251
+ return {
8252
+ message: typeof metered === "string" ? "Billing is metered." : "No meter evidence for this store.",
8253
+ request: { shop },
8254
+ // `probed` is the LEDGER, not the call: a store whose Partner
8255
+ // credentials are absent was not asked, and reporting that as
8256
+ // "probed, nothing accruing" would stamp an unmetered verdict on
8257
+ // a store nobody looked at.
8258
+ result: { metered: metered ?? null, probed: ledger || typeof metered === "string" }
8259
+ };
8260
+ }
8261
+ },
8262
+ // THE EMBEDDED APP'S SESSION STORE. The @shopify/shopify-app library
8263
+ // persists the offline session on token exchange and refresh; it lives
8264
+ // encrypted on the shared `shop` record, which is the same row every
8265
+ // organization's connection to this store points at.
8266
+ session: {
8267
+ // SOFT-CLEAR, NEVER A DELETE. The library calls this on session
8268
+ // invalidation and not only on uninstall, so hard-deleting the record
8269
+ // would orphan every org connection pointing at it — token resolution
8270
+ // silently nulls — and destroy the durable account link and the
8271
+ // storefront token with it. The next embedded load re-runs token
8272
+ // exchange. The full record delete belongs to the uninstall webhook.
8273
+ clear: async ({ context }) => {
8274
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8275
+ if (!shop) throw refusal("shop is required", 400);
8276
+ return {
8277
+ message: "Session cleared.",
8278
+ request: { shop },
8279
+ result: { ok: true },
8280
+ writes: [{
8281
+ collection: "shop",
8282
+ data: { $set: { settings: null } },
8283
+ operation: "update",
8284
+ query: { shop }
8285
+ }]
8286
+ };
8287
+ },
8288
+ read: async ({ context }, { read } = {}) => {
8289
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8290
+ if (!shop) throw refusal("shop is required", 400);
8291
+ const record = await read.get({ collection: "shop", query: { shop } });
8292
+ if (!(record == null ? void 0 : record.settings)) throw refusal("No session for this store", 404);
8293
+ return {
8294
+ message: "Session read.",
8295
+ request: { shop },
8296
+ result: { session: decrypt(record.settings) }
8297
+ };
8298
+ },
8299
+ save: async ({ context }) => {
8300
+ const session = context == null ? void 0 : context.session;
8301
+ const shop = sanitizeDomain(session == null ? void 0 : session.shop);
8302
+ if (!shop || !(session == null ? void 0 : session.accessToken)) throw refusal("session.shop and session.accessToken are required", 400);
8303
+ return {
8304
+ message: "Session saved.",
8305
+ request: { shop },
8306
+ result: { ok: true },
8307
+ writes: [{
8308
+ collection: "shop",
8309
+ data: {
8310
+ $set: { settings: encrypt(session), shop },
8311
+ $setOnInsert: { status: "pending" }
8312
+ },
8313
+ operation: "update",
8314
+ options: { upsert: true },
8315
+ query: { shop }
8316
+ }]
8317
+ };
8318
+ }
8319
+ },
8320
+ // THE LINK-TOKEN HANDOFF. The breakout callback runs top-level and can set
8321
+ // a first-party cookie; the embedded App Home cannot read that cookie from
8322
+ // inside the Shopify admin iframe. So the callback stashes the merchant's
8323
+ // user token here keyed by shop, and App Home reads it once and clears it.
8324
+ //
8325
+ // DURABLE RATHER THAN IN REDIS: a restart must not strand a merchant
8326
+ // mid-handoff. Short-lived and encrypted.
8327
+ token: {
8328
+ clear: async ({ context }) => {
8329
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8330
+ if (!shop) throw refusal("shop is required", 400);
8331
+ return {
8332
+ message: "Link token cleared.",
8333
+ request: { shop },
8334
+ result: { ok: true },
8335
+ writes: [{
8336
+ collection: "shop",
8337
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null } },
8338
+ operation: "update",
8339
+ query: { shop }
8340
+ }]
8341
+ };
8342
+ },
8343
+ read: async ({ context }, { read } = {}) => {
8344
+ var _a;
8345
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8346
+ if (!shop) throw refusal("shop is required", 400);
8347
+ const record = await read.get({ collection: "shop", query: { shop } });
8348
+ const expiresAt = (record == null ? void 0 : record.linkTokenExpiresAt) ? new Date(record.linkTokenExpiresAt) : null;
8349
+ if (!(record == null ? void 0 : record.linkToken) || !expiresAt || expiresAt <= /* @__PURE__ */ new Date()) {
8350
+ throw refusal("No link token for this store", 404);
8351
+ }
8352
+ return {
8353
+ message: "Link token read.",
8354
+ request: { shop },
8355
+ result: { token: ((_a = decrypt(record.linkToken)) == null ? void 0 : _a.token) ?? null }
8356
+ };
8357
+ },
8358
+ save: async ({ context }) => {
8359
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8360
+ const token = context == null ? void 0 : context.token;
8361
+ if (!shop || !token) throw refusal("shop and token are required", 400);
8362
+ return {
8363
+ message: "Link token saved.",
8364
+ request: { shop },
8365
+ result: { ok: true },
8366
+ writes: [{
8367
+ collection: "shop",
8368
+ data: {
8369
+ $set: {
8370
+ linkToken: encrypt({ token }),
8371
+ linkTokenExpiresAt: new Date(Date.now() + LINK_TOKEN_TTL_MS)
8372
+ }
8373
+ },
8374
+ operation: "update",
8375
+ query: { shop }
8376
+ }]
8377
+ };
8378
+ }
8379
+ }
8380
+ },
5655
8381
  // Drawbridge sends its own notification email and SMS — see the private
5656
8382
  // `drawbridge` manifest. A vendor answering these would be a second sender,
5657
8383
  // which is the arrangement the platform sender replaced.
@@ -5713,8 +8439,8 @@ var shopify_default2 = {
5713
8439
  // access token still works, reconciles the scopes the store granted
5714
8440
  // against the ones the app now needs, and queues a webhook
5715
8441
  // reconciliation.
5716
- health: async ({ connection: connection2, workflow }, { adminToken, logger, read, reconcileScopes, resolveSettings, rotateToken, shopify } = {}) => {
5717
- var _a, _b, _c, _d, _e, _f;
8442
+ health: async ({ connection: connection2, workflow }, { adminToken, logger, read, reconcileScopes, resolveSettings, rotateToken, shopify = client } = {}) => {
8443
+ var _a, _b, _c, _d;
5718
8444
  const request2 = {
5719
8445
  connectionId: workflow.connection,
5720
8446
  organizationId: workflow.organization,
@@ -5751,33 +8477,26 @@ var shopify_default2 = {
5751
8477
  shopCurrency = String(shopData.currency || "").toLowerCase() || null;
5752
8478
  sourceRepaired = true;
5753
8479
  }
5754
- const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
5755
- adminAccessToken,
5756
- domain: connection2.shop
5757
- });
5758
- const usageLine = (_a = subscriptions.find((subscription) => subscription.usageLineItemId)) == null ? void 0 : _a.usageLineItemId;
5759
- if (usageLine) metered = usageLine;
5760
8480
  const partnerRow = (read == null ? void 0 : read.get) ? await read.get({ collection: "provider", query: { slug: "shopify" } }) : null;
5761
8481
  const partner = (partnerRow == null ? void 0 : partnerRow.settings) ? decrypt(partnerRow.settings) : {};
5762
- if (partner.partnerToken && partner.partnerOrgId && partner.partnerAppId && (source == null ? void 0 : source.id) && ((_b = shopify.partner) == null ? void 0 : _b.getUsageChargeEvents)) {
5763
- const ledgerFloor = new Date(Date.now() - 30 * 24 * 60 * 60 * 1e3);
5764
- const accruals = await shopify.partner.getUsageChargeEvents({
5765
- appId: "gid://shopify/App/" + partner.partnerAppId,
5766
- first: 10,
5767
- occurredAtMin: ledgerFloor.toISOString(),
5768
- organizationId: partner.partnerOrgId,
5769
- partnerToken: partner.partnerToken,
5770
- shopId: "gid://shopify/Shop/" + source.id
5771
- });
5772
- const boundaries = accruals.filter((event) => event.occurredAt).sort((a, b) => new Date(a.occurredAt) - new Date(b.occurredAt));
5773
- const accrued = [...boundaries].reverse().find((event) => Number(event.usageQuantity) > 0);
5774
- if (accrued) metered = String(accrued.chargeId || accrued.id);
5775
- const stampedAt = (_c = boundaries.find(
8482
+ const ledgerFloor = new Date(Date.now() - LEDGER_WINDOW_MS);
8483
+ const verdict = await meterVerdict({
8484
+ adminAccessToken,
8485
+ ledgerFloor,
8486
+ partner,
8487
+ shop: connection2.shop,
8488
+ shopId: source == null ? void 0 : source.id,
8489
+ shopify
8490
+ });
8491
+ if (verdict.metered !== void 0) metered = verdict.metered;
8492
+ const { boundaries } = verdict;
8493
+ if (boundaries.length) {
8494
+ const stampedAt = (_a = boundaries.find(
5776
8495
  (event) => {
5777
8496
  var _a2;
5778
8497
  return String(event.chargeId || event.id) === String(((_a2 = connection2.source) == null ? void 0 : _a2.metered) || "");
5779
8498
  }
5780
- )) == null ? void 0 : _c.occurredAt;
8499
+ )) == null ? void 0 : _a.occurredAt;
5781
8500
  reconciliation = [];
5782
8501
  let windowStart = ledgerFloor;
5783
8502
  for (const boundary of boundaries) {
@@ -5827,7 +8546,7 @@ var shopify_default2 = {
5827
8546
  }
5828
8547
  });
5829
8548
  } else {
5830
- (_d = logger == null ? void 0 : logger.error) == null ? void 0 : _d.call(logger, new Error(
8549
+ (_b = logger == null ? void 0 : logger.error) == null ? void 0 : _b.call(logger, new Error(
5831
8550
  "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"
5832
8551
  ), {
5833
8552
  extra: {
@@ -5846,13 +8565,13 @@ var shopify_default2 = {
5846
8565
  }
5847
8566
  } catch (probeError) {
5848
8567
  billingProbeFailed = true;
5849
- (_e = logger == null ? void 0 : logger.warn) == null ? void 0 : _e.call(logger, "shopify.health.billing.probe.failed", {
8568
+ (_c = logger == null ? void 0 : logger.warn) == null ? void 0 : _c.call(logger, "shopify.health.billing.probe.failed", {
5850
8569
  connectionId: connection2.id,
5851
8570
  message: probeError == null ? void 0 : probeError.message,
5852
8571
  shop: connection2.shop
5853
8572
  });
5854
8573
  }
5855
- if (sourceRepaired || metered !== void 0 && metered !== (((_f = connection2.source) == null ? void 0 : _f.metered) ?? void 0)) {
8574
+ if (sourceRepaired || metered !== void 0 && metered !== (((_d = connection2.source) == null ? void 0 : _d.metered) ?? void 0)) {
5856
8575
  writes.push({
5857
8576
  collection: "connection",
5858
8577
  data: {
@@ -5987,13 +8706,13 @@ var shopify_default2 = {
5987
8706
  // They are the same two questions every other vendor answers through
5988
8707
  // resources.*, so they answer them the same way now.
5989
8708
  //
5990
- // `shopify` is INJECTED: this package cannot import @drawbridge/shopify,
8709
+ // `shopify` DEFAULTS to the client this file imports; nothing injects it,
5991
8710
  // which depends on it. What arrives is the SDK's pure HTTP namespaces
5992
8711
  // and nothing else — no controller, no collection access. Resolving the
5993
8712
  // credential is the caller's job because it is Drawbridge's job: the
5994
8713
  // admin token refreshes and writes itself back, which is service work,
5995
8714
  // not vendor work.
5996
- products: async ({ cursor, limit = 100, search, settings, sort }, { shopify } = {}) => {
8715
+ products: async ({ cursor, limit = 100, search, settings, sort }, { shopify = client } = {}) => {
5997
8716
  var _a, _b, _c, _d;
5998
8717
  const products = await shopify.storefront.getProducts({
5999
8718
  cursor,
@@ -6015,7 +8734,7 @@ var shopify_default2 = {
6015
8734
  }
6016
8735
  };
6017
8736
  },
6018
- promotions: async ({ cursor, limit = 100, search, settings }, { shopify } = {}) => {
8737
+ promotions: async ({ cursor, limit = 100, search, settings }, { shopify = client } = {}) => {
6019
8738
  var _a, _b;
6020
8739
  const discounts = await shopify.admin.getDiscounts({
6021
8740
  adminAccessToken: settings == null ? void 0 : settings.adminAccessToken,
@@ -6302,7 +9021,7 @@ var shopify_default2 = {
6302
9021
  };
6303
9022
 
6304
9023
  // lib/connections/manifests/webhook.js
6305
- import crypto2 from "crypto";
9024
+ import crypto3 from "crypto";
6306
9025
 
6307
9026
  // lib/safe-http.js
6308
9027
  import dns2 from "dns";
@@ -6475,7 +9194,7 @@ var signature = ({ body, settings }) => {
6475
9194
  return [
6476
9195
  "t=" + timestamp,
6477
9196
  ...[settings.secret, ...previous].map(
6478
- (secret) => "v1=" + crypto2.createHmac(generated.algorithm, secret).update(payload).digest(generated.encoding)
9197
+ (secret) => "v1=" + crypto3.createHmac(generated.algorithm, secret).update(payload).digest(generated.encoding)
6479
9198
  )
6480
9199
  ].join(",");
6481
9200
  };
@@ -6520,14 +9239,15 @@ var webhook_default = {
6520
9239
  "Drawbridge can POST event payloads to your endpoint as activity happens in your account, so your own systems can react to it.",
6521
9240
  "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."
6522
9241
  ],
6523
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
6524
- // The dashboard already carries generic reasons for every way an
6525
- // authorization can fail declined, expired state, a vendor we are not set
6526
- // up for and a sentence here is an ADDITION to those, for a vendor whose
6527
- // failures need saying differently. This one's do not.
9242
+ // THERE IS NO CONSENT SCREEN TO FAIL. Connecting mints a signing secret;
9243
+ // nothing is authorized against a third party, so neither `denied` nor
9244
+ // `invalid` has a state it could describe. The failures this connection
9245
+ // really has are at DELIVERY a merchant's endpoint refusing a POST and
9246
+ // those reach them through the connection's own errors rather than through
9247
+ // connect copy.
6528
9248
  //
6529
- // Answered rather than omitted, because `errors` existed on two of six
6530
- // manifests and there was no way to tell "nothing to add" from "nobody
9249
+ // `false` is the recorded decision, not silence: `errors` existed on two of
9250
+ // six manifests and there was no way to tell "nothing to add" from "nobody
6531
9251
  // wrote it".
6532
9252
  errors: false,
6533
9253
  excerpt: "Sign outgoing webhook payloads with an HMAC secret to verify authenticity.",