@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
@@ -62,6 +62,7 @@ __export(connections_exports, {
62
62
  buildVendor: () => buildVendor,
63
63
  catalogConnections: () => catalogConnections,
64
64
  connectFields: () => connectFields,
65
+ connectionSettings: () => connectionSettings,
65
66
  connectionSteps: () => connectionSteps,
66
67
  connections: () => connections,
67
68
  consentUrl: () => consentUrl,
@@ -71,10 +72,12 @@ __export(connections_exports, {
71
72
  isStale: () => isStale,
72
73
  isStatus: () => isStatus,
73
74
  mergeSettings: () => mergeSettings,
75
+ perform: () => perform,
74
76
  pkcePair: () => pkcePair,
75
77
  projectConnection: () => projectConnection,
76
78
  publicConnectionKeys: () => publicConnectionKeys,
77
79
  publicSettingsBySlug: () => publicSettingsBySlug,
80
+ reconcileConnectionScopes: () => reconcileConnectionScopes,
78
81
  redactSettings: () => redactSettings,
79
82
  resolveConnection: () => resolveConnection,
80
83
  runHook: () => runHook,
@@ -215,6 +218,10 @@ var HOOKS = Object.freeze({
215
218
  "code",
216
219
  // Create the buyer at the vendor, so an order can be attributed to them.
217
220
  "customer",
221
+ // HOW MANY OF THIS PRODUCT ARE LEFT, at the vendor. Read at the moment a
222
+ // campaign's product list is rendered rather than stored, because stock is
223
+ // the one product fact that is stale the instant it is written down.
224
+ "inventory",
218
225
  // An order arrived at the vendor: attribute it, record it, update totals.
219
226
  "order",
220
227
  // Pull product data across on a vendor update.
@@ -282,7 +289,19 @@ var HOOKS = Object.freeze({
282
289
  organizations: Object.freeze(["add", "list", "remove"]),
283
290
  // What the merchant pays the VENDOR. Pairs with auth.install.billing, which
284
291
  // declares the plan they are being charged on.
285
- plan: Object.freeze(["cancel", "reselect"]),
292
+ //
293
+ // `verify` is the odd one of the three: not something a merchant does, but
294
+ // the question "is this store's billing actually metered right now". It is
295
+ // here because it is the same subject — and because the answer was being
296
+ // derived in TWO places, the vendor's health check and drawbridge-sync's
297
+ // approval webhook, whose copy said in its own comment that it matched the
298
+ // other and did not.
299
+ // `charge` and `verify` are the two that are not merchant actions: one
300
+ // sends a usage charge to the vendor's meter, the other asks whether that
301
+ // meter is actually working. Both are here because both are the same
302
+ // subject — what the merchant pays the vendor — and both were being done
303
+ // from drawbridge-sync with a direct import of the vendor's client.
304
+ plan: Object.freeze(["cancel", "charge", "reselect", "verify"]),
286
305
  // The embedded app's own session, stored by us on the vendor's behalf.
287
306
  session: Object.freeze(["clear", "read", "save"]),
288
307
  // The one-time code that hands a merchant from the embedded app into
@@ -379,7 +398,7 @@ var answerOf = (answer) => {
379
398
  return effectsOf(answer);
380
399
  };
381
400
  var WRITE_OPERATIONS = Object.freeze(["create", "delete", "update"]);
382
- var INSTALL_SIGNATURE = Object.freeze({ options: ["read", "request"], props: ["context"] });
401
+ var INSTALL_SIGNATURE = Object.freeze({ options: ["read"], props: ["context"] });
383
402
  var LIFECYCLE_SIGNATURE = Object.freeze({ options: ["dispatch"], props: ["context"] });
384
403
  var RESOURCE_SIGNATURE = Object.freeze({
385
404
  options: ["fetcher", "shopify"],
@@ -396,15 +415,30 @@ var HOOK_SLOT_PROPS = Object.freeze({
396
415
  // the second bag would be silently discarded, which is exactly the
397
416
  // stubbed-fetcher-reaches-production failure the split exists to prevent.
398
417
  "auth.token": false,
399
- // COMMERCE. `cart` is declared and unimplemented the Checkout Kit path in
400
- // api/route/subdomain.js writes nothing, which is why it never became a hook
401
- // so its signature mirrors `code`, its nearest sibling, and moving the
402
- // route here is a deliberate widening of this line rather than a silent one.
403
- "commerce.cart": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context", "step"] }),
418
+ // COMMERCE. `cart` is the odd one: it runs for a SHOPPER on a public page,
419
+ // not for an organization inside a workflow, so it takes no `connection` and
420
+ // no `step`. It reads the storefront with the store's own storefront token
421
+ // and mints a checkout token from DRAWBRIDGE'S app credentials, which is why
422
+ // `clientId`/`clientSecret` are here as props, the way auth.disconnect
423
+ // already carries them, because a credential is a fact of the run rather
424
+ // than a service.
425
+ "commerce.cart": Object.freeze({
426
+ options: ["fetcher", "shopify"],
427
+ props: ["clientId", "clientSecret", "context", "settings"]
428
+ }),
404
429
  "commerce.code": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context", "step"] }),
405
430
  "commerce.customer": Object.freeze({ options: ["adminToken", "read", "shopify"], props: ["connection", "context"] }),
431
+ "commerce.inventory": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context"] }),
406
432
  "commerce.order": Object.freeze({ options: ["conversionRate", "logger", "mintId", "read"], props: ["connection", "context"] }),
407
- "commerce.product": Object.freeze({ options: ["mintId", "read"], props: ["connection", "context", "workflow"] }),
433
+ // THREE OPERATIONS, one slot — record, sync, variants. `settings` and
434
+ // `adminToken` arrived with the pull half: the storefront read needs the
435
+ // store's storefront token and the product-feedback send needs its admin one,
436
+ // and both are resolved by the caller because minting either needs a
437
+ // controller.
438
+ "commerce.product": Object.freeze({
439
+ options: ["adminToken", "mintId", "read", "shopify"],
440
+ props: ["connection", "context", "settings", "workflow"]
441
+ }),
408
442
  // THE ADDRESS IS `contact` IN BOTH, and the shell already says why: it is the
409
443
  // person, not the lead document. `remove` called it `email` and `sync` called
410
444
  // it `doc` on one vendor and `lead` on three — three names for two facts.
@@ -417,19 +451,58 @@ var HOOK_SLOT_PROPS = Object.freeze({
417
451
  "inbound.process": Object.freeze({ options: ["dispatch"], props: ["context"] }),
418
452
  "inbound.receive": Object.freeze({ options: [], props: ["channel", "event", "headers", "payload"] }),
419
453
  "inbound.verify": Object.freeze({ options: [], props: ["body", "channel", "headers", "secret", "url"] }),
420
- // INSTALL — thirteen slots, none implemented yet. They are what the thirteen
421
- // routes in api/route/shopify-embedded.js become, and the signature is
422
- // deliberately narrow: `context` is the request's own body, `read` and
423
- // `request` are the only services an install surface has been shown to need.
424
- // A route that cannot be expressed inside this line is a finding to bring
425
- // back here, not a name to add at the call site.
454
+ // INSTALL — thirteen slots, and they are the thirteen routes that used to be
455
+ // api/route/shopify-embedded.js. `context` is the request's own body in all
456
+ // of them; the options are where they differ, and every difference below was
457
+ // forced by a line in those routes rather than chosen.
458
+ //
459
+ // SEVEN NEED NOTHING BUT `read`. The two session slots that write, the two
460
+ // token slots that write, the two clears, and both account slots answer from
461
+ // the shared install record alone.
462
+ //
463
+ // SIX TAKE MORE, and the widenings are worth naming because each is a fact
464
+ // Drawbridge owns that the manifest must not:
465
+ //
466
+ // conversionRate, planTitle what Drawbridge charges this organization.
467
+ // The org list renders both, and importing the
468
+ // plan catalogue here is the cycle
469
+ // features -> connections -> shopify -> plans
470
+ // -> features that was just broken.
471
+ // currencies which settlement currencies Drawbridge can
472
+ // bill. A store outside them fails the
473
+ // connection validator INSIDE the transaction,
474
+ // which surfaces as an opaque 500, so `add`
475
+ // checks first and says so.
476
+ // mintId the connection's id, known before the write
477
+ // that creates it, because the organization's
478
+ // own refs have to name it in the same
479
+ // transaction.
480
+ // shopify the vendor. Four slots call the store: two
481
+ // read the live plan, two release it.
482
+ // mark THE ONE WRITE A DESCRIPTION CANNOT CARRY, and
483
+ // `reselect` is the only slot with one. See its
484
+ // implementation for why the order is the point.
426
485
  "install.account.link": INSTALL_SIGNATURE,
427
486
  "install.account.unlink": INSTALL_SIGNATURE,
428
- "install.organizations.add": INSTALL_SIGNATURE,
429
- "install.organizations.list": INSTALL_SIGNATURE,
487
+ "install.organizations.add": Object.freeze({
488
+ options: ["currencies", "mintId", "read", "shopify"],
489
+ props: ["context"]
490
+ }),
491
+ "install.organizations.list": Object.freeze({
492
+ options: ["conversionRate", "planTitle", "read", "shopify"],
493
+ props: ["context"]
494
+ }),
430
495
  "install.organizations.remove": INSTALL_SIGNATURE,
431
- "install.plan.cancel": INSTALL_SIGNATURE,
432
- "install.plan.reselect": INSTALL_SIGNATURE,
496
+ "install.plan.cancel": Object.freeze({ options: ["read", "shopify"], props: ["context"] }),
497
+ // `manifest` because the handle this charge bills under is the vendor's own
498
+ // declaration (auth.install.billing.handle), and checking the job against the
499
+ // declaration is what the enqueuer-checks-itself version could not do.
500
+ "install.plan.charge": Object.freeze({
501
+ options: ["shopify"],
502
+ props: ["clientId", "clientSecret", "context", "manifest"]
503
+ }),
504
+ "install.plan.reselect": Object.freeze({ options: ["mark", "read", "shopify"], props: ["context"] }),
505
+ "install.plan.verify": Object.freeze({ options: ["adminToken", "read", "shopify"], props: ["context"] }),
433
506
  "install.session.clear": INSTALL_SIGNATURE,
434
507
  "install.session.read": INSTALL_SIGNATURE,
435
508
  "install.session.save": INSTALL_SIGNATURE,
@@ -635,6 +708,181 @@ var isStatus = (status) => STATUSES.includes(status);
635
708
  // lib/usage.js
636
709
  var isDuplicateKey = (error) => (error == null ? void 0 : error.code) === 11e3 || (error == null ? void 0 : error.code) === "11000" || /E11000|duplicate key/i.test((error == null ? void 0 : error.message) || "");
637
710
 
711
+ // lib/connections/perform.js
712
+ var perform = async ({ answer, controller, emit, enqueue }) => {
713
+ const { enqueues, events, transaction, writes } = answerOf(answer) || {};
714
+ const write = async ({ collection, data, ignoreDuplicate, multiple, operation, options, query }, session) => {
715
+ try {
716
+ await controller[operation]({
717
+ collection,
718
+ data,
719
+ // The controller takes `multiple` beside options — an update that
720
+ // means every matching document must say so explicitly.
721
+ ...multiple && { multiple: true },
722
+ ...(options || session) && { options: { ...options, ...session && { session } } },
723
+ ...query && { query }
724
+ });
725
+ } catch (error) {
726
+ if (!(ignoreDuplicate && isDuplicateKey(error))) throw error;
727
+ }
728
+ };
729
+ if (transaction) {
730
+ await controller.transaction(async (session) => {
731
+ for (const descriptor of writes) await write(descriptor, session);
732
+ });
733
+ } else {
734
+ for (const descriptor of writes) await write(descriptor);
735
+ }
736
+ for (const { data, name, options, queue: target } of enqueues) {
737
+ if (!enqueue) throw new Error("A hook described an enqueue and this caller supplied no enqueuer");
738
+ await enqueue({ data, name, options, queue: target });
739
+ }
740
+ for (const descriptor of events) {
741
+ if (!emit) throw new Error("A hook described a socket event and this caller supplied no emitter");
742
+ emit(descriptor);
743
+ }
744
+ };
745
+
746
+ // lib/encrypt.js
747
+ var import_crypto2 = __toESM(require("crypto"), 1);
748
+
749
+ // lib/token.js
750
+ var import_crypto = __toESM(require("crypto"), 1);
751
+ var generate = (bytes = 32, encoding = "base64url") => {
752
+ const buf = import_crypto.default.randomBytes(bytes);
753
+ return encoding ? buf.toString(encoding) : buf;
754
+ };
755
+ var hash = (value, key) => {
756
+ if (!value) return null;
757
+ if (key) {
758
+ return import_crypto.default.createHmac("sha256", key).update(String(value)).digest("base64url");
759
+ }
760
+ return import_crypto.default.createHash("sha256").update(String(value)).digest("base64url");
761
+ };
762
+
763
+ // lib/encrypt.js
764
+ var ALGORITHM = "aes-256-gcm";
765
+ var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
766
+ var encrypt = (value) => {
767
+ const iv = generate(12, null);
768
+ const cipher = import_crypto2.default.createCipheriv(ALGORITHM, getKey(), iv);
769
+ const data = Buffer.concat([
770
+ cipher.update(JSON.stringify(value), "utf8"),
771
+ cipher.final()
772
+ ]);
773
+ const tag = cipher.getAuthTag();
774
+ return [iv, tag, data].map((b) => b.toString("hex")).join(":");
775
+ };
776
+ var decrypt = (value) => {
777
+ if (typeof value !== "string") return value;
778
+ const [ivHex, tagHex, dataHex] = value.split(":");
779
+ const decipher = import_crypto2.default.createDecipheriv(
780
+ ALGORITHM,
781
+ getKey(),
782
+ Buffer.from(ivHex, "hex")
783
+ );
784
+ decipher.setAuthTag(Buffer.from(tagHex, "hex"));
785
+ const result = Buffer.concat([
786
+ decipher.update(Buffer.from(dataHex, "hex")),
787
+ decipher.final()
788
+ ]);
789
+ return JSON.parse(result.toString("utf8"));
790
+ };
791
+
792
+ // lib/connections/reconcile.js
793
+ var connectionSettings = async ({ controller, query }) => {
794
+ const connection = await controller.get({ collection: "connection", query });
795
+ if (!connection) return { connection: null, settings: null };
796
+ return { connection, settings: decrypt(connection.settings) };
797
+ };
798
+ var SCOPES_ERROR_SOURCE = "scopes";
799
+ var SCOPES_ERROR_MESSAGE = "Shopify permissions are out of date. Open the Drawbridge app in your Shopify admin to approve the updated permissions.";
800
+ var reconcileConnectionScopes = async ({
801
+ controller,
802
+ enqueue,
803
+ granted = null,
804
+ logger,
805
+ shop,
806
+ slug: slug2 = "shopify"
807
+ }) => {
808
+ var _a, _b, _c;
809
+ if (granted === null) {
810
+ const record = await controller.get({ collection: "shop", query: { shop } });
811
+ const session = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
812
+ granted = (session == null ? void 0 : session.scope) || null;
813
+ }
814
+ if (!granted) return null;
815
+ const answered = await runHook(slug2, "auth.scopes", { scope: granted });
816
+ const missing2 = answered.outcome === "answered" ? (_a = answered.answer.result) == null ? void 0 : _a.missing : null;
817
+ if (!Array.isArray(missing2)) {
818
+ (_b = logger == null ? void 0 : logger.warn) == null ? void 0 : _b.call(logger, "connection.scopes.unreadable", { shop, slug: slug2 });
819
+ return null;
820
+ }
821
+ const connections2 = await controller.aggregate({
822
+ collection: "connection",
823
+ pipeline: [{ $match: { shop, slug: slug2 } }]
824
+ });
825
+ let hadScopesError = false;
826
+ for (const connection of connections2) {
827
+ const others = (connection.errors || []).filter((entry) => entry.source !== SCOPES_ERROR_SOURCE);
828
+ const hasScopesError = others.length !== (connection.errors || []).length;
829
+ hadScopesError = hadScopesError || hasScopesError;
830
+ if (missing2.length) {
831
+ await controller.update({
832
+ collection: "connection",
833
+ data: {
834
+ $set: {
835
+ errors: [...others, { message: SCOPES_ERROR_MESSAGE, source: SCOPES_ERROR_SOURCE }],
836
+ status: "error"
837
+ }
838
+ },
839
+ query: { id: connection.id }
840
+ });
841
+ } else if (hasScopesError) {
842
+ await controller.update({
843
+ collection: "connection",
844
+ data: {
845
+ $set: {
846
+ errors: others,
847
+ ...connection.status === "error" && !others.length && { status: "active" }
848
+ }
849
+ },
850
+ query: { id: connection.id }
851
+ });
852
+ }
853
+ }
854
+ const products = connections2.length ? await controller.aggregate({
855
+ collection: "product",
856
+ pipeline: [{ $match: { "provider.slug": slug2, "source.domain": shop } }]
857
+ }) : [];
858
+ if (missing2.length && products.length) {
859
+ const productIds = products.map((product) => product.id);
860
+ await controller.update({
861
+ collection: "product",
862
+ data: { $set: { status: "inactive" } },
863
+ multiple: true,
864
+ query: { id: { $in: productIds } }
865
+ });
866
+ await controller.update({
867
+ collection: "advertisement",
868
+ data: { $set: { status: "drafted" } },
869
+ multiple: true,
870
+ query: { product: { $in: productIds } }
871
+ });
872
+ } else if (!missing2.length && hadScopesError && enqueue) {
873
+ for (const product of products) {
874
+ await enqueue({
875
+ data: { product: product.id },
876
+ name: "sync",
877
+ options: { jobId: "product." + slug2 + "." + product.id + "." + Date.now() },
878
+ queue: "product." + slug2
879
+ });
880
+ }
881
+ }
882
+ (_c = logger == null ? void 0 : logger.info) == null ? void 0 : _c.call(logger, "connection.scopes.reconciled", { connections: connections2.length, missing: missing2, shop });
883
+ return missing2;
884
+ };
885
+
638
886
  // lib/connections/workflows.js
639
887
  var systemSteps = (node, path = []) => Object.entries(node || {}).flatMap(
640
888
  ([key, value]) => {
@@ -748,10 +996,10 @@ var authToken = async ({
748
996
  const renewing = !code;
749
997
  if (renewing && !refreshToken) throw new Error("Nothing has been consented to yet, so there is no refresh token to spend");
750
998
  if (!renewing && descriptor.pkce && !verifier) throw new Error("This connection requires PKCE, so the code verifier is not optional");
751
- const client = credentials({ basic, clientId, clientSecret });
999
+ const client2 = credentials({ basic, clientId, clientSecret });
752
1000
  const response = await fetcher(descriptor.endpoints.token, {
753
1001
  body: new URLSearchParams({
754
- ...client.body,
1002
+ ...client2.body,
755
1003
  ...renewing ? { grant_type: "refresh_token", refresh_token: refreshToken } : {
756
1004
  code: decodeURIComponent(String(code || "").trim()),
757
1005
  grant_type: "authorization_code",
@@ -759,7 +1007,7 @@ var authToken = async ({
759
1007
  ...descriptor.pkce && { code_verifier: verifier }
760
1008
  }
761
1009
  }),
762
- headers: { "content-type": "application/x-www-form-urlencoded", ...client.headers },
1010
+ headers: { "content-type": "application/x-www-form-urlencoded", ...client2.headers },
763
1011
  method: "POST",
764
1012
  signal: AbortSignal.timeout(15e3)
765
1013
  });
@@ -1215,9 +1463,18 @@ var scaffold_default = {
1215
1463
  commerce: {
1216
1464
  // NEW in phase 1 — the Checkout Kit cart path, which writes nothing and is
1217
1465
  // the last api surface Shopify owns outside a hook.
1218
- cart: async ({ connection, context }, { read } = {}) => ANSWER,
1466
+ // NO `connection` AND NO `step`: this one runs for a SHOPPER on a public
1467
+ // page, not for an organization inside a workflow. It reads the storefront
1468
+ // with the store's storefront token and mints a checkout token from
1469
+ // DRAWBRIDGE'S app credentials, which is why the credential pair rides in
1470
+ // as props — the way auth.disconnect already carries it.
1471
+ cart: async ({ clientId, clientSecret, context, settings }, { fetcher, shopify } = {}) => ANSWER,
1219
1472
  code: async ({ connection, context, step }, { adminToken, shopify } = {}) => ANSWER,
1220
1473
  customer: async ({ connection, context }, { adminToken, read, shopify } = {}) => ANSWER,
1474
+ // STOCK, READ AT RENDER TIME rather than stored. It is the one product
1475
+ // fact that is stale the instant it is written down, so the campaign
1476
+ // product list asks the vendor and caches the answer for a minute.
1477
+ inventory: async ({ connection, context }, { adminToken, shopify } = {}) => ANSWER,
1221
1478
  order: async ({ connection, context }, { logger, mintId, read } = {}) => ANSWER,
1222
1479
  // THIS IS WHERE `product.insert` LANDS.
1223
1480
  //
@@ -1239,7 +1496,7 @@ var scaffold_default = {
1239
1496
  // nothing and shows up only as `workflow.dispatch.candidates matched : 0` in
1240
1497
  // a log. Phase 1 closes it and build() checks every trigger against it.
1241
1498
  product: {
1242
- hook: async ({ connection, context, workflow }, { mintId, read } = {}) => ANSWER,
1499
+ hook: async ({ connection, context, settings, workflow }, { adminToken, mintId, read, shopify } = {}) => ANSWER,
1243
1500
  step: () => ({
1244
1501
  description: "Syncs product data from the vendor when a product changes.",
1245
1502
  key: "Vendor Product Sync",
@@ -1387,8 +1644,19 @@ var scaffold_default = {
1387
1644
  // Vendor billing, the only group that is not generic. Pairs with
1388
1645
  // auth.install.billing, which declares what the merchant is being charged.
1389
1646
  plan: {
1390
- cancel: async ({ context }, { dispatch, read } = {}) => ANSWER,
1391
- reselect: async ({ context }, { dispatch, read } = {}) => ANSWER
1647
+ cancel: async ({ context }, { read, shopify } = {}) => ANSWER,
1648
+ // NOT A MERCHANT ACTION EITHER one attributed order's usage charge,
1649
+ // sent to the vendor's meter. The credential pair rides in as props
1650
+ // because the charge authenticates as the APP, not as the store.
1651
+ charge: async ({ clientId, clientSecret, context, manifest }, { shopify } = {}) => ANSWER,
1652
+ // `mark` is the one write a description cannot carry: the marker must
1653
+ // be persisted BEFORE the approval is released, and a described write
1654
+ // lands after the hook returns.
1655
+ reselect: async ({ context }, { mark, read, shopify } = {}) => ANSWER,
1656
+ // NOT A MERCHANT ACTION — the question "is this store's billing
1657
+ // actually metered right now", asked by the daily health check and by
1658
+ // the vendor's own approval webhook, which used to hand-copy it.
1659
+ verify: async ({ context }, { adminToken, read, shopify } = {}) => ANSWER
1392
1660
  },
1393
1661
  // The embedded app's own session, stored by us on the vendor's behalf.
1394
1662
  session: {
@@ -1874,16 +2142,19 @@ var attentive_default2 = {
1874
2142
  "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.",
1875
2143
  "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."
1876
2144
  ],
1877
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
1878
- // The dashboard already carries generic reasons for every way an
1879
- // authorization can fail — declined, expired state, a vendor we are not set
1880
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
1881
- // failures need saying differently. This one's do not.
2145
+ // WHAT THE MERCHANT READS WHEN A CONNECT FAILS. Two states, because the
2146
+ // consent screen has two ways to end: they said no, or something between
2147
+ // here and the vendor went wrong.
1882
2148
  //
1883
- // Answered rather than omitted, because `errors` existed on two of six
1884
- // manifests and there was no way to tell "nothing to add" from "nobody
1885
- // wrote it".
1886
- errors: false,
2149
+ // THE VENDOR IS NAMED IN BOTH. The dashboard's generic copy says "the
2150
+ // authorization"; a merchant connecting two accounts in one sitting needs
2151
+ // to know which one this was.
2152
+ errors: {
2153
+ connect: {
2154
+ denied: "The Attentive authorization was declined, so nothing was connected.",
2155
+ invalid: "We couldn't complete the Attentive connection. Try connecting again."
2156
+ }
2157
+ },
1887
2158
  excerpt: "Sync your Drawbridge contacts into an Attentive segment.",
1888
2159
  // NAMES THE SEGMENT STEP, because `status` below gates on it: a grant with
1889
2160
  // no segment chosen sits at Pending, and a guide that stops at the consent
@@ -2411,6 +2682,15 @@ var readEventHeader = ({ descriptor, headers }) => ({ result: { event: headers[d
2411
2682
  var DEFAULT_TIMEOUT_MS = 15e3;
2412
2683
  var request = async ({
2413
2684
  body,
2685
+ // THE TRANSPORT, injectable and defaulted to the real one.
2686
+ //
2687
+ // Every other vendor client in this package takes a `fetcher` — it is how
2688
+ // klaviyo, mailchimp and attentive are tested without a network, and it is a
2689
+ // declared HOOK_OPTION. The Shopify client had no seam at all, so the only way
2690
+ // to test a hook that used it was to inject the whole SDK namespace; that
2691
+ // injection existed to work around an import cycle, and when the cycle went
2692
+ // the tests lost their only hold. This is the seam they should have had.
2693
+ fetcher = fetch,
2414
2694
  headers = {},
2415
2695
  method = "GET",
2416
2696
  query,
@@ -2424,7 +2704,7 @@ var request = async ({
2424
2704
  }
2425
2705
  ;
2426
2706
  const isForm = type === "form";
2427
- const response = await fetch(fullUrl.toString(), {
2707
+ const response = await fetcher(fullUrl.toString(), {
2428
2708
  method,
2429
2709
  headers: {
2430
2710
  "Content-Type": isForm ? "application/x-www-form-urlencoded" : "application/json",
@@ -2881,15 +3161,12 @@ var drawbridge_default2 = {
2881
3161
  description: [
2882
3162
  "Drawbridge sends your notification emails and your entrants' emails, and recalculates segment membership on a schedule. It is always on and needs nothing connected."
2883
3163
  ],
2884
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
2885
- // The dashboard already carries generic reasons for every way an
2886
- // authorization can fail declined, expired state, a vendor we are not set
2887
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
2888
- // failures need saying differently. This one's do not.
3164
+ // NOTHING IS EVER CONNECTED, so no connect can fail. This is the platform's
3165
+ // own manifest always on, private, never in the catalogue — and it exists
3166
+ // to give Drawbridge's own steps a hook to point at. `denied` and `invalid`
3167
+ // describe a consent screen this connection does not have.
2889
3168
  //
2890
- // Answered rather than omitted, because `errors` existed on two of six
2891
- // manifests and there was no way to tell "nothing to add" from "nobody
2892
- // wrote it".
3169
+ // `false` is the recorded decision, not silence.
2893
3170
  errors: false,
2894
3171
  excerpt: "The steps Drawbridge runs itself.",
2895
3172
  guide: [
@@ -3649,10 +3926,10 @@ var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
3649
3926
 
3650
3927
  // lib/connections/scopes.js
3651
3928
  var list = (value) => (Array.isArray(value) ? value.flatMap((entry) => String(entry).split(/\s+/)) : String(value ?? "").split(/\s+/)).map((entry) => entry.trim()).filter(Boolean);
3652
- var missingScopes = ({ granted, required }) => {
3929
+ var missingScopes = ({ granted, required: required2 }) => {
3653
3930
  if (granted === null || granted === void 0 || granted === "") return null;
3654
3931
  const held = new Set(list(granted));
3655
- return list(required).filter((scope) => !held.has(scope));
3932
+ return list(required2).filter((scope) => !held.has(scope));
3656
3933
  };
3657
3934
 
3658
3935
  // lib/connections/manifests/klaviyo.js
@@ -4551,16 +4828,19 @@ var mailchimp_default2 = {
4551
4828
  "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.",
4552
4829
  "Someone who unsubscribed inside Mailchimp keeps that choice: a resync only sets the status of a subscriber Mailchimp has never seen before."
4553
4830
  ],
4554
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
4555
- // The dashboard already carries generic reasons for every way an
4556
- // authorization can fail — declined, expired state, a vendor we are not set
4557
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
4558
- // failures need saying differently. This one's do not.
4831
+ // WHAT THE MERCHANT READS WHEN A CONNECT FAILS. Two states, because the
4832
+ // consent screen has two ways to end: they said no, or something between
4833
+ // here and the vendor went wrong.
4559
4834
  //
4560
- // Answered rather than omitted, because `errors` existed on two of six
4561
- // manifests and there was no way to tell "nothing to add" from "nobody
4562
- // wrote it".
4563
- errors: false,
4835
+ // THE VENDOR IS NAMED IN BOTH. The dashboard's generic copy says "the
4836
+ // authorization"; a merchant connecting two accounts in one sitting needs
4837
+ // to know which one this was.
4838
+ errors: {
4839
+ connect: {
4840
+ denied: "The Mailchimp authorization was declined, so nothing was connected.",
4841
+ invalid: "We couldn't complete the Mailchimp connection. Try connecting again."
4842
+ }
4843
+ },
4564
4844
  excerpt: "Sync your Drawbridge contacts into a Mailchimp audience.",
4565
4845
  // NAMES THE AUDIENCE STEP, because `status` below gates on it: a grant with
4566
4846
  // no audience chosen sits at Pending, and a guide that stops at the consent
@@ -4659,7 +4939,7 @@ var mailchimp_default2 = {
4659
4939
  if (!audience) return { message: "No Mailchimp audience is chosen for this connection.", request: request2, skipped: true };
4660
4940
  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);
4661
4941
  if (!email) return { message: "That lead has no email address to sync.", request: request2, skipped: true };
4662
- const hash = subscriberHash(email);
4942
+ const hash2 = subscriberHash(email);
4663
4943
  const [firstName, ...restOfName] = String((lead == null ? void 0 : lead.name) || "").trim().split(/\s+/).filter(Boolean);
4664
4944
  const lastName = restOfName.join(" ");
4665
4945
  const phone = ((_e = lead == null ? void 0 : lead.phone) == null ? void 0 : _e.number) || null;
@@ -4668,7 +4948,7 @@ var mailchimp_default2 = {
4668
4948
  ...lastName && { LNAME: lastName },
4669
4949
  ...phone && { PHONE: phone }
4670
4950
  };
4671
- const member = await api3("/lists/" + audience + "/members/" + hash, {
4951
+ const member = await api3("/lists/" + audience + "/members/" + hash2, {
4672
4952
  dc: settings == null ? void 0 : settings.dc,
4673
4953
  fetcher,
4674
4954
  method: "PUT",
@@ -4709,7 +4989,7 @@ var mailchimp_default2 = {
4709
4989
  status: joined.has(entry.id) ? "active" : "inactive"
4710
4990
  }));
4711
4991
  if (tags.length > 0) {
4712
- await api3("/lists/" + audience + "/members/" + hash + "/tags", {
4992
+ await api3("/lists/" + audience + "/members/" + hash2 + "/tags", {
4713
4993
  dc: settings == null ? void 0 : settings.dc,
4714
4994
  fetcher,
4715
4995
  method: "POST",
@@ -4720,12 +5000,12 @@ var mailchimp_default2 = {
4720
5000
  }
4721
5001
  return {
4722
5002
  // Merged into `context` for later steps in this run.
4723
- context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash },
5003
+ context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash2 },
4724
5004
  message: suppressed ? "Synced to Mailchimp as unsubscribed \u2014 this contact has opted out." : "Synced to the Mailchimp audience.",
4725
5005
  request: request2,
4726
5006
  // Recorded on the run for support to read back, not a write
4727
5007
  // instruction — the hook has already written what it needed to.
4728
- response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash }
5008
+ response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash2 }
4729
5009
  };
4730
5010
  }
4731
5011
  },
@@ -5095,139 +5375,2030 @@ var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
5095
5375
  <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"/>
5096
5376
  </svg>`;
5097
5377
 
5098
- // lib/email.js
5099
- var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
5100
- var toCanonicalEmail = (value) => {
5101
- if (!value || typeof value !== "string") return null;
5102
- const email = value.trim().toLowerCase();
5103
- const at = email.lastIndexOf("@");
5104
- if (at < 1 || at === email.length - 1) return null;
5105
- let local = email.slice(0, at);
5106
- const domain = email.slice(at + 1);
5107
- const plus = local.indexOf("+");
5108
- if (plus > 0) local = local.slice(0, plus);
5109
- if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
5110
- if (!local) return null;
5111
- return local + "@" + domain;
5112
- };
5378
+ // lib/shopify/admin.js
5379
+ var admin_exports = {};
5380
+ __export(admin_exports, {
5381
+ adminFetch: () => adminFetch,
5382
+ createDiscountCode: () => createDiscountCode,
5383
+ createUsageRecord: () => createUsageRecord,
5384
+ createUsageSubscription: () => createUsageSubscription,
5385
+ getActiveAppSubscriptions: () => getActiveAppSubscriptions,
5386
+ getDiscounts: () => getDiscounts,
5387
+ getOrCreateCustomer: () => getOrCreateCustomer,
5388
+ getProductInventory: () => getProductInventory,
5389
+ sendProductResourceFeedback: () => sendProductResourceFeedback
5390
+ });
5113
5391
 
5114
- // lib/encrypt.js
5115
- var import_crypto = __toESM(require("crypto"), 1);
5116
- var ALGORITHM = "aes-256-gcm";
5117
- var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
5118
- var decrypt = (value) => {
5119
- if (typeof value !== "string") return value;
5120
- const [ivHex, tagHex, dataHex] = value.split(":");
5121
- const decipher = import_crypto.default.createDecipheriv(
5122
- ALGORITHM,
5123
- getKey(),
5124
- Buffer.from(ivHex, "hex")
5125
- );
5126
- decipher.setAuthTag(Buffer.from(tagHex, "hex"));
5127
- const result = Buffer.concat([
5128
- decipher.update(Buffer.from(dataHex, "hex")),
5129
- decipher.final()
5130
- ]);
5131
- return JSON.parse(result.toString("utf8"));
5132
- };
5392
+ // lib/shopify/constants.js
5393
+ var SHOPIFY_STOREFRONT_API_VERSION = "2025-01";
5394
+ var SHOPIFY_ADMIN_API_VERSION = "2026-04";
5395
+ var SHOPIFY_APP_API_VERSION = "unstable";
5396
+ var SHOPIFY_REQUIRED_SCOPES = [
5397
+ "read_customers",
5398
+ "write_customers",
5399
+ "read_discounts",
5400
+ "write_discounts",
5401
+ "read_orders",
5402
+ "read_products",
5403
+ "read_publications",
5404
+ "write_resource_feedbacks",
5405
+ "unauthenticated_read_checkouts",
5406
+ "unauthenticated_read_product_inventory",
5407
+ "unauthenticated_read_product_listings",
5408
+ "unauthenticated_write_checkouts"
5409
+ ];
5410
+ var REFRESH_TOKEN_LIFETIME_MS = 90 * 24 * 60 * 60 * 1e3;
5411
+ var ACCESS_TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1e3;
5412
+ var PARTNER_API_VERSION = process.env.SHOPIFY_PARTNER_API_VERSION || "2026-07";
5133
5413
 
5134
- // lib/slugify.js
5135
- var import_slugify = __toESM(require("slugify"), 1);
5136
- var slugify = (value, nochars = false) => {
5137
- const remove = nochars ? /[-?*+~.()'"!:@#^_{}\[\];,/\\]/g : /[?*+~.()'"!:@#^_{}\[\];,/\\]/g;
5138
- const replacement = nochars ? "" : "-";
5139
- return (0, import_slugify.default)(
5140
- value,
5141
- {
5142
- remove,
5143
- replacement,
5144
- lower: true,
5145
- trim: true
5414
+ // lib/shopify/admin.js
5415
+ var adminUrl = (domain) => `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}`;
5416
+ var adminFetch = async ({ adminAccessToken, domain, fetcher, query, variables }) => {
5417
+ var _a;
5418
+ const { data, errors } = await request({
5419
+ fetcher,
5420
+ method: "POST",
5421
+ url: adminUrl(domain) + "/graphql.json",
5422
+ headers: {
5423
+ "X-Shopify-Access-Token": adminAccessToken
5424
+ },
5425
+ body: {
5426
+ query,
5427
+ ...variables && { variables }
5146
5428
  }
5147
- );
5429
+ });
5430
+ if (errors) {
5431
+ throw new Error("Shopify GraphQL error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
5432
+ }
5433
+ ;
5434
+ return data;
5148
5435
  };
5149
-
5150
- // lib/connections/manifests/shopify.js
5151
- var toLine = ({
5152
- price,
5153
- product_id: productId,
5154
- quantity,
5155
- title,
5156
- variant_id: variantId,
5157
- variant_title: variantTitle
5158
- }) => ({
5159
- price: parseFloat(price) || 0,
5160
- productId: productId ? "gid://shopify/Product/" + productId : null,
5161
- quantity: quantity || 1,
5162
- title: title || null,
5163
- variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
5164
- variantTitle: variantTitle || null
5165
- });
5166
- var attributeLineItems = (lineItems = []) => lineItems.reduce(
5167
- (acc, item) => {
5168
- const attrs = (item.properties || []).reduce(
5169
- (map, { name, value }) => {
5170
- map[name] = value;
5171
- return map;
5172
- },
5173
- {}
5174
- );
5175
- if (!attrs["_drwbrdg_ca"]) return acc;
5176
- if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
5177
- const line = toLine(item);
5178
- acc.attributedGross += line.price * line.quantity;
5179
- acc.attributedLines.push(line);
5180
- return acc;
5181
- },
5182
- { attrMap: {}, attributedGross: 0, attributedLines: [] }
5183
- );
5184
- var generateDiscountCode = (0, import_nanoid.customAlphabet)("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
5185
- var blockedReason = (discount) => {
5186
- var _a;
5187
- if ((discount == null ? void 0 : discount.status) === "EXPIRED") return "This discount has expired.";
5188
- const buyers = (_a = discount == null ? void 0 : discount.context) == null ? void 0 : _a.__typename;
5189
- if (buyers && buyers !== "DiscountBuyerSelectionAll") {
5190
- 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.";
5436
+ var DISCOUNT_FIELDS = `
5437
+ title
5438
+ status
5439
+ startsAt
5440
+ endsAt
5441
+ usageLimit
5442
+ asyncUsageCount
5443
+ appliesOncePerCustomer
5444
+ context { __typename }
5445
+ `;
5446
+ var discountsQuery = (search, cursor, limit) => `{
5447
+ codeDiscountNodes(first: ${limit}${search ? `, query: "title:*${search}*"` : ""}${cursor ? `, after: "${cursor}"` : ""}) {
5448
+ edges {
5449
+ node {
5450
+ id
5451
+ codeDiscount {
5452
+ ... on DiscountCodeBasic { ${DISCOUNT_FIELDS} }
5453
+ ... on DiscountCodeBxgy { ${DISCOUNT_FIELDS} }
5454
+ ... on DiscountCodeFreeShipping { ${DISCOUNT_FIELDS} }
5455
+ ... on DiscountCodeApp { ${DISCOUNT_FIELDS} }
5456
+ }
5457
+ }
5458
+ }
5459
+ pageInfo {
5460
+ endCursor
5461
+ hasNextPage
5462
+ hasPreviousPage
5463
+ startCursor
5464
+ }
5465
+ }
5466
+ }`;
5467
+ var getDiscounts = async ({ fetcher, adminAccessToken, domain, search, cursor, limit }) => {
5468
+ const data = await adminFetch({
5469
+ fetcher,
5470
+ adminAccessToken,
5471
+ domain,
5472
+ query: discountsQuery(search, cursor, limit)
5473
+ });
5474
+ return data == null ? void 0 : data.codeDiscountNodes;
5475
+ };
5476
+ var discountGid = (id) => String(id).startsWith("gid://") ? String(id) : "gid://shopify/DiscountCodeNode/" + id;
5477
+ var createDiscountCode = async ({ fetcher, adminAccessToken, domain, discountId, code }) => {
5478
+ var _a, _b, _c, _d, _e, _f, _g, _h;
5479
+ const added = await adminFetch({
5480
+ fetcher,
5481
+ adminAccessToken,
5482
+ domain,
5483
+ query: `
5484
+ mutation DiscountRedeemCodeBulkAdd($discountId: ID!, $codes: [DiscountRedeemCodeInput!]!) {
5485
+ discountRedeemCodeBulkAdd(discountId: $discountId, codes: $codes) {
5486
+ bulkCreation {
5487
+ id
5488
+ }
5489
+ userErrors {
5490
+ field
5491
+ message
5492
+ }
5493
+ }
5494
+ }
5495
+ `,
5496
+ variables: {
5497
+ codes: [{ code }],
5498
+ discountId: discountGid(discountId)
5499
+ }
5500
+ });
5501
+ const addErrors = (_a = added == null ? void 0 : added.discountRedeemCodeBulkAdd) == null ? void 0 : _a.userErrors;
5502
+ if (addErrors == null ? void 0 : addErrors.length) {
5503
+ throw new Error("Shopify discount code create failed: " + addErrors[0].message);
5191
5504
  }
5192
5505
  ;
5193
- if (typeof (discount == null ? void 0 : discount.usageLimit) === "number" && discount.usageLimit > 0 && ((discount == null ? void 0 : discount.asyncUsageCount) || 0) >= discount.usageLimit) {
5194
- return "This discount has reached its total usage limit.";
5506
+ const bulkCreationId = (_c = (_b = added == null ? void 0 : added.discountRedeemCodeBulkAdd) == null ? void 0 : _b.bulkCreation) == null ? void 0 : _c.id;
5507
+ if (!bulkCreationId) {
5508
+ throw new Error("Shopify discount code create failed: no bulk creation id returned");
5195
5509
  }
5196
5510
  ;
5197
- return null;
5511
+ for (let attempt = 0; attempt < 15; attempt++) {
5512
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
5513
+ const polled = await adminFetch({
5514
+ fetcher,
5515
+ adminAccessToken,
5516
+ domain,
5517
+ query: `
5518
+ query DiscountRedeemCodeBulkCreationPoll($id: ID!) {
5519
+ discountRedeemCodeBulkCreation(id: $id) {
5520
+ done
5521
+ codes(first: 1) {
5522
+ nodes {
5523
+ code
5524
+ discountRedeemCode {
5525
+ id
5526
+ }
5527
+ errors {
5528
+ message
5529
+ }
5530
+ }
5531
+ }
5532
+ }
5533
+ }
5534
+ `,
5535
+ variables: {
5536
+ id: bulkCreationId
5537
+ }
5538
+ });
5539
+ const creation = polled == null ? void 0 : polled.discountRedeemCodeBulkCreation;
5540
+ if (!(creation == null ? void 0 : creation.done)) continue;
5541
+ const node = (_e = (_d = creation.codes) == null ? void 0 : _d.nodes) == null ? void 0 : _e[0];
5542
+ if (!((_f = node == null ? void 0 : node.discountRedeemCode) == null ? void 0 : _f.id)) {
5543
+ 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"));
5544
+ }
5545
+ ;
5546
+ return {
5547
+ code: node.code,
5548
+ // Numeric tail keeps the stored shopifyDiscountId in the shape the
5549
+ // legacy REST endpoint returned — it feeds a merchant-visible
5550
+ // workflow template variable, so no gid:// leakage.
5551
+ id: node.discountRedeemCode.id.split("/").pop()
5552
+ };
5553
+ }
5554
+ ;
5555
+ throw new Error("Shopify discount code create timed out waiting for bulk creation " + bulkCreationId);
5198
5556
  };
5199
- var discountWarning = (discount) => {
5200
- if ((discount == null ? void 0 : discount.status) === "SCHEDULED") {
5201
- return "This discount hasn't started yet, so codes issued before it does won't work until then.";
5557
+ var getOrCreateCustomer = async ({ fetcher, adminAccessToken, domain, email, firstName, lastName, source }) => {
5558
+ var _a, _b, _c, _d, _e, _f, _g, _h;
5559
+ const lookupQuery = `
5560
+ query customerByEmail( $query : String! ) {
5561
+ customers( first : 1, query : $query ) {
5562
+ edges {
5563
+ node {
5564
+ id
5565
+ }
5566
+ }
5567
+ }
5568
+ }
5569
+ `;
5570
+ const data = await adminFetch({
5571
+ fetcher,
5572
+ adminAccessToken,
5573
+ domain,
5574
+ query: lookupQuery,
5575
+ variables: { query: "email:" + email }
5576
+ });
5577
+ 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;
5578
+ if (existing) return existing;
5579
+ const input = { email };
5580
+ if (firstName) input.firstName = firstName;
5581
+ if (lastName) input.lastName = lastName;
5582
+ if (source) {
5583
+ input.metafields = [{
5584
+ namespace: "drwbrdg",
5585
+ key: "source",
5586
+ type: "single_line_text_field",
5587
+ value: source
5588
+ }];
5202
5589
  }
5203
5590
  ;
5204
- if (discount == null ? void 0 : discount.appliesOncePerCustomer) return "Each customer can use this discount only once.";
5205
- return null;
5591
+ const result = await adminFetch({
5592
+ fetcher,
5593
+ adminAccessToken,
5594
+ domain,
5595
+ query: `
5596
+ mutation customerCreate( $input : CustomerInput! ) {
5597
+ customerCreate( input : $input ) {
5598
+ customer {
5599
+ id
5600
+ }
5601
+ userErrors {
5602
+ field
5603
+ message
5604
+ }
5605
+ }
5606
+ }
5607
+ `,
5608
+ variables: { input }
5609
+ });
5610
+ const userErrors = (_d = result == null ? void 0 : result.customerCreate) == null ? void 0 : _d.userErrors;
5611
+ if (userErrors == null ? void 0 : userErrors.length) {
5612
+ const emailTaken = userErrors.some((e) => {
5613
+ var _a2;
5614
+ return (_a2 = e.message) == null ? void 0 : _a2.includes("Email has already been taken");
5615
+ });
5616
+ if (emailTaken) {
5617
+ const retry = await adminFetch({
5618
+ fetcher,
5619
+ adminAccessToken,
5620
+ domain,
5621
+ query: lookupQuery,
5622
+ variables: { query: "email:" + email }
5623
+ });
5624
+ 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;
5625
+ if (found) return found;
5626
+ }
5627
+ ;
5628
+ throw new Error("Shopify customer create failed: " + userErrors[0].message);
5629
+ }
5630
+ ;
5631
+ return (_h = result == null ? void 0 : result.customerCreate) == null ? void 0 : _h.customer;
5206
5632
  };
5207
- var ORDER_EVENT_HANDLE = slugify("drawbridge-orders");
5208
- var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
5209
- var OAUTH_ERROR_SOURCE = "oauth";
5210
- var BILLING_ERROR_SOURCE = "billing";
5211
- var BILLING_ERROR_MESSAGE = "Order billing isn't set up for this store \u2014 reselect and approve the plan from the Shopify connection page.";
5212
- var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
5213
- var inbound = {
5214
- headers: {
5215
- event: "x-shopify-topic",
5216
- id: "x-shopify-webhook-id",
5217
- shop: "x-shopify-shop-domain",
5218
- signature: "x-shopify-hmac-sha256"
5219
- },
5220
- signature: {
5221
- algorithm: "sha256",
5222
- encoding: "base64",
5223
- secret: "SHOPIFY_API_SECRET"
5633
+ var getActiveAppSubscriptions = async ({ fetcher, adminAccessToken, domain }) => {
5634
+ var _a, _b;
5635
+ const data = await adminFetch({
5636
+ fetcher,
5637
+ adminAccessToken,
5638
+ domain,
5639
+ query: `{
5640
+ currentAppInstallation {
5641
+ activeSubscriptions {
5642
+ id
5643
+ name
5644
+ status
5645
+ test
5646
+ lineItems {
5647
+ id
5648
+ plan {
5649
+ pricingDetails {
5650
+ __typename
5651
+ }
5652
+ }
5653
+ }
5654
+ }
5655
+ }
5656
+ shop {
5657
+ myshopifyDomain
5658
+ }
5659
+ }`
5660
+ });
5661
+ return {
5662
+ shopDomain: ((_a = data == null ? void 0 : data.shop) == null ? void 0 : _a.myshopifyDomain) || null,
5663
+ subscriptions: (((_b = data == null ? void 0 : data.currentAppInstallation) == null ? void 0 : _b.activeSubscriptions) || []).map((subscription) => {
5664
+ var _a2;
5665
+ return {
5666
+ ...subscription,
5667
+ metered: ((subscription == null ? void 0 : subscription.lineItems) || []).some(
5668
+ (item) => {
5669
+ var _a3, _b2;
5670
+ return ((_b2 = (_a3 = item == null ? void 0 : item.plan) == null ? void 0 : _a3.pricingDetails) == null ? void 0 : _b2.__typename) === "AppUsagePricing";
5671
+ }
5672
+ ),
5673
+ // The usage line's own id — the address appUsageRecordCreate charges
5674
+ // against. Null when the approval carries no usage component.
5675
+ usageLineItemId: ((_a2 = ((subscription == null ? void 0 : subscription.lineItems) || []).find(
5676
+ (item) => {
5677
+ var _a3, _b2;
5678
+ return ((_b2 = (_a3 = item == null ? void 0 : item.plan) == null ? void 0 : _a3.pricingDetails) == null ? void 0 : _b2.__typename) === "AppUsagePricing";
5679
+ }
5680
+ )) == null ? void 0 : _a2.id) || null
5681
+ };
5682
+ })
5683
+ };
5684
+ };
5685
+ var createUsageSubscription = async ({ fetcher, adminAccessToken, cappedAmount, currencyCode = "USD", domain, name, recurringPrice = 0, returnUrl, terms, test = false }) => {
5686
+ if (!name || !returnUrl || !terms || !(Number(cappedAmount) > 0)) {
5687
+ throw new Error("createUsageSubscription requires name, returnUrl, terms, and a positive cappedAmount");
5688
+ }
5689
+ ;
5690
+ const data = await adminFetch({
5691
+ fetcher,
5692
+ adminAccessToken,
5693
+ domain,
5694
+ query: `mutation createUsageSubscription( $lineItems : [AppSubscriptionLineItemInput!]!, $name : String!, $returnUrl : URL!, $test : Boolean ) {
5695
+ appSubscriptionCreate( lineItems : $lineItems, name : $name, returnUrl : $returnUrl, test : $test ) {
5696
+ appSubscription { id name status test lineItems { id plan { pricingDetails { __typename } } } }
5697
+ confirmationUrl
5698
+ userErrors { field message }
5699
+ }
5700
+ }`,
5701
+ variables: {
5702
+ lineItems: [
5703
+ {
5704
+ plan: {
5705
+ appRecurringPricingDetails: {
5706
+ interval: "EVERY_30_DAYS",
5707
+ price: { amount: Number(recurringPrice), currencyCode }
5708
+ }
5709
+ }
5710
+ },
5711
+ {
5712
+ plan: {
5713
+ appUsagePricingDetails: {
5714
+ cappedAmount: { amount: Number(cappedAmount), currencyCode },
5715
+ terms
5716
+ }
5717
+ }
5718
+ }
5719
+ ],
5720
+ name,
5721
+ returnUrl,
5722
+ test
5723
+ }
5724
+ });
5725
+ const payload = data == null ? void 0 : data.appSubscriptionCreate;
5726
+ const userErrors = (payload == null ? void 0 : payload.userErrors) || [];
5727
+ if (userErrors.length) {
5728
+ throw new Error("Shopify subscription create failed: " + userErrors.map((entry) => entry.message).join("; "));
5729
+ }
5730
+ ;
5731
+ if (!(payload == null ? void 0 : payload.confirmationUrl)) {
5732
+ throw new Error("Shopify subscription create failed: no confirmation url returned");
5224
5733
  }
5734
+ ;
5735
+ return {
5736
+ confirmationUrl: payload.confirmationUrl,
5737
+ subscription: payload.appSubscription
5738
+ };
5225
5739
  };
5226
- var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
5740
+ var createUsageRecord = async ({ fetcher, adminAccessToken, amount, currencyCode = "USD", description, domain, idempotencyKey, subscriptionLineItemId }) => {
5741
+ var _a;
5742
+ if (!subscriptionLineItemId || !description || !(Number(amount) > 0)) {
5743
+ throw new Error("createUsageRecord requires subscriptionLineItemId, description, and a positive amount");
5744
+ }
5745
+ ;
5746
+ const data = await adminFetch({
5747
+ fetcher,
5748
+ adminAccessToken,
5749
+ domain,
5750
+ query: `mutation createUsageRecord( $description : String!, $idempotencyKey : String, $price : MoneyInput!, $subscriptionLineItemId : ID! ) {
5751
+ appUsageRecordCreate( description : $description, idempotencyKey : $idempotencyKey, price : $price, subscriptionLineItemId : $subscriptionLineItemId ) {
5752
+ appUsageRecord { id }
5753
+ userErrors { field message }
5754
+ }
5755
+ }`,
5756
+ variables: {
5757
+ description,
5758
+ idempotencyKey: idempotencyKey ? String(idempotencyKey) : null,
5759
+ price: { amount: Number(amount), currencyCode },
5760
+ subscriptionLineItemId
5761
+ }
5762
+ });
5763
+ const payload = data == null ? void 0 : data.appUsageRecordCreate;
5764
+ const userErrors = (payload == null ? void 0 : payload.userErrors) || [];
5765
+ if (userErrors.length || !((_a = payload == null ? void 0 : payload.appUsageRecord) == null ? void 0 : _a.id)) {
5766
+ throw new Error("Shopify usage record failed: " + (userErrors.map((entry) => entry.message).join("; ") || "no record returned"));
5767
+ }
5768
+ ;
5769
+ return { id: payload.appUsageRecord.id };
5770
+ };
5771
+ var getProductInventory = async ({ fetcher, adminAccessToken, domain, productId }) => {
5772
+ var _a, _b;
5773
+ const data = await adminFetch({
5774
+ fetcher,
5775
+ adminAccessToken,
5776
+ domain,
5777
+ query: `{
5778
+ product( id : "${productId}" ) {
5779
+ variants( first : 100 ) {
5780
+ edges {
5781
+ node {
5782
+ id
5783
+ inventoryQuantity
5784
+ }
5785
+ }
5786
+ }
5787
+ }
5788
+ }`
5789
+ });
5790
+ const edges = ((_b = (_a = data == null ? void 0 : data.product) == null ? void 0 : _a.variants) == null ? void 0 : _b.edges) || [];
5791
+ return edges.reduce((accumulator, edge) => {
5792
+ var _a2, _b2;
5793
+ const id = (_a2 = edge == null ? void 0 : edge.node) == null ? void 0 : _a2.id;
5794
+ const quantity = (_b2 = edge == null ? void 0 : edge.node) == null ? void 0 : _b2.inventoryQuantity;
5795
+ if (id) {
5796
+ accumulator[id] = Number.isFinite(quantity) ? quantity : 0;
5797
+ }
5798
+ ;
5799
+ return accumulator;
5800
+ }, {});
5801
+ };
5802
+ var getProductUpdatedAt = async ({ adminAccessToken, domain, fetcher, productId }) => {
5803
+ var _a;
5804
+ const data = await adminFetch({
5805
+ fetcher,
5806
+ adminAccessToken,
5807
+ domain,
5808
+ query: `
5809
+ query ProductUpdatedAt($id: ID!) {
5810
+ product(id: $id) {
5811
+ updatedAt
5812
+ }
5813
+ }
5814
+ `,
5815
+ variables: { id: productId }
5816
+ });
5817
+ return ((_a = data == null ? void 0 : data.product) == null ? void 0 : _a.updatedAt) || null;
5818
+ };
5819
+ var NOT_ON_CHANNEL = "not available to the channel";
5820
+ var OUTDATED_FEEDBACK = "later version";
5821
+ var sendProductResourceFeedback = async ({ fetcher, adminAccessToken, domain, productId, state, messages = [] }) => {
5822
+ var _a, _b, _c;
5823
+ const productUpdatedAt = await getProductUpdatedAt({ adminAccessToken, domain, fetcher, productId });
5824
+ if (!productUpdatedAt) return null;
5825
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5826
+ const submit = async (version) => {
5827
+ const data = await adminFetch({
5828
+ fetcher,
5829
+ adminAccessToken,
5830
+ domain,
5831
+ query: `
5832
+ mutation ProductFeedback($feedbackInput: [ProductResourceFeedbackInput!]!) {
5833
+ bulkProductResourceFeedbackCreate(feedbackInput: $feedbackInput) {
5834
+ feedback {
5835
+ productId
5836
+ state
5837
+ }
5838
+ userErrors {
5839
+ field
5840
+ message
5841
+ }
5842
+ }
5843
+ }
5844
+ `,
5845
+ variables: {
5846
+ feedbackInput: [
5847
+ {
5848
+ productId,
5849
+ state,
5850
+ feedbackGeneratedAt: now,
5851
+ productUpdatedAt: version,
5852
+ messages
5853
+ }
5854
+ ]
5855
+ }
5856
+ });
5857
+ return data == null ? void 0 : data.bulkProductResourceFeedbackCreate;
5858
+ };
5859
+ let result = await submit(productUpdatedAt);
5860
+ if ((((_b = (_a = result == null ? void 0 : result.userErrors) == null ? void 0 : _a[0]) == null ? void 0 : _b.message) || "").toLowerCase().includes(OUTDATED_FEEDBACK)) {
5861
+ result = await submit(now);
5862
+ }
5863
+ ;
5864
+ const feedbackErrors = result == null ? void 0 : result.userErrors;
5865
+ if (feedbackErrors == null ? void 0 : feedbackErrors.length) {
5866
+ const message = feedbackErrors[0].message || "";
5867
+ if (message.toLowerCase().includes(NOT_ON_CHANNEL)) return null;
5868
+ throw new Error("Shopify product feedback failed: " + message);
5869
+ }
5870
+ ;
5871
+ return ((_c = result == null ? void 0 : result.feedback) == null ? void 0 : _c[0]) || null;
5872
+ };
5873
+
5874
+ // lib/shopify/billing.js
5875
+ var billing_exports = {};
5876
+ __export(billing_exports, {
5877
+ sendAppEvent: () => sendAppEvent
5878
+ });
5879
+ var APP_API = "https://api.shopify.com";
5880
+ var APP_API_VERSION = process.env.SHOPIFY_APP_API_VERSION || SHOPIFY_APP_API_VERSION;
5881
+ var cachedTokens = {};
5882
+ var fetchAppToken = async ({ clientId, clientSecret, fetcher }) => {
5883
+ const data = await request({
5884
+ fetcher,
5885
+ method: "POST",
5886
+ url: APP_API + "/auth/access_token",
5887
+ body: {
5888
+ client_id: clientId,
5889
+ client_secret: clientSecret,
5890
+ grant_type: "client_credentials"
5891
+ }
5892
+ });
5893
+ if (!(data == null ? void 0 : data.access_token)) {
5894
+ throw new Error("Shopify app token request failed: no access token returned");
5895
+ }
5896
+ ;
5897
+ const ttl = data.expires_in ? data.expires_in * 1e3 : 60 * 60 * 1e3;
5898
+ cachedTokens[clientId] = {
5899
+ expiresAt: Date.now() + ttl - 60 * 1e3,
5900
+ token: data.access_token
5901
+ };
5902
+ return data.access_token;
5903
+ };
5904
+ var getAppToken = async ({ clientId, clientSecret, fetcher }) => {
5905
+ const cached = cachedTokens[clientId];
5906
+ if (cached && cached.expiresAt > Date.now()) {
5907
+ return cached.token;
5908
+ }
5909
+ ;
5910
+ return fetchAppToken({ clientId, clientSecret, fetcher });
5911
+ };
5912
+ var toShopGid = (shopId) => String(shopId).startsWith("gid://") ? String(shopId) : "gid://shopify/Shop/" + shopId;
5913
+ var sendAppEvent = async ({ fetcher, clientId, clientSecret, eventHandle, idempotencyKey, reference, revision, shopId, timestamp, value }) => {
5914
+ if (!shopId || !eventHandle || !(Number(value) > 0)) {
5915
+ throw new Error("sendAppEvent requires shopId, eventHandle, and a positive value");
5916
+ }
5917
+ ;
5918
+ if (!clientId || !clientSecret) {
5919
+ throw new Error("sendAppEvent requires clientId and clientSecret");
5920
+ }
5921
+ ;
5922
+ const suffix = revision ? ".r" + revision : "";
5923
+ const key = idempotencyKey && String(idempotencyKey).slice(0, Math.max(0, 64 - suffix.length)) + suffix;
5924
+ const body = {
5925
+ attributes: {
5926
+ value: Number(value),
5927
+ ...reference && {
5928
+ reference: String(reference).slice(0, 128)
5929
+ }
5930
+ },
5931
+ event_handle: eventHandle,
5932
+ shop_id: toShopGid(shopId),
5933
+ timestamp: timestamp || (/* @__PURE__ */ new Date()).toISOString(),
5934
+ ...key && {
5935
+ idempotency_key: key
5936
+ }
5937
+ };
5938
+ const send2 = async (token) => request({
5939
+ method: "POST",
5940
+ url: APP_API + "/app/" + APP_API_VERSION + "/events",
5941
+ headers: {
5942
+ "Authorization": "Bearer " + token
5943
+ },
5944
+ body
5945
+ });
5946
+ try {
5947
+ return await send2(await getAppToken({ clientId, clientSecret, fetcher }));
5948
+ } catch (error) {
5949
+ if ((error == null ? void 0 : error.status) === 401) {
5950
+ delete cachedTokens[clientId];
5951
+ return send2(await fetchAppToken({ clientId, clientSecret, fetcher }));
5952
+ }
5953
+ ;
5954
+ throw error;
5955
+ }
5956
+ };
5957
+
5958
+ // lib/shopify/oauth.js
5959
+ var oauth_exports = {};
5960
+ __export(oauth_exports, {
5961
+ SHOPIFY_REQUIRED_SCOPES: () => SHOPIFY_REQUIRED_SCOPES,
5962
+ createStorefrontToken: () => createStorefrontToken,
5963
+ getAdminToken: () => getAdminToken,
5964
+ getShop: () => getShop,
5965
+ missingScopes: () => missingScopes2,
5966
+ ping: () => ping,
5967
+ refreshAdminToken: () => refreshAdminToken,
5968
+ resolveConnectionSettings: () => resolveConnectionSettings
5969
+ });
5970
+ var required = (name, value) => {
5971
+ if (!value) {
5972
+ throw new Error("Shopify " + name + " is required");
5973
+ }
5974
+ ;
5975
+ return value;
5976
+ };
5977
+ var missingScopes2 = (granted) => {
5978
+ const grantedSet = new Set(
5979
+ (Array.isArray(granted) ? granted : String(granted || "").split(",")).map((scope) => scope.trim()).filter(Boolean)
5980
+ );
5981
+ const satisfied = (scope) => grantedSet.has(scope) || grantedSet.has(scope.replace(/(^|_)read_/, "$1write_"));
5982
+ return SHOPIFY_REQUIRED_SCOPES.filter((scope) => !satisfied(scope));
5983
+ };
5984
+ var ping = async ({ fetcher, adminAccessToken, domain }) => {
5985
+ var _a;
5986
+ const response = await fetch(
5987
+ `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}/graphql.json`,
5988
+ {
5989
+ body: JSON.stringify({ query: "{ shop { name } }" }),
5990
+ headers: {
5991
+ "Content-Type": "application/json",
5992
+ "X-Shopify-Access-Token": adminAccessToken
5993
+ },
5994
+ method: "POST"
5995
+ }
5996
+ );
5997
+ if (!response.ok) {
5998
+ const text = await response.text().catch(() => "");
5999
+ const error = new Error(response.status + ": " + text);
6000
+ error.status = response.status;
6001
+ throw error;
6002
+ }
6003
+ ;
6004
+ const { errors } = await response.json().catch(() => ({}));
6005
+ if (errors == null ? void 0 : errors.length) {
6006
+ throw new Error("GraphQL: " + (((_a = errors[0]) == null ? void 0 : _a.message) || "unknown error"));
6007
+ }
6008
+ ;
6009
+ };
6010
+ var OAUTH_ERROR_TITLE_PATTERN = /Oauth error (\w+)/i;
6011
+ var parseOAuthErrorCode = (text) => {
6012
+ var _a;
6013
+ try {
6014
+ const parsed = JSON.parse(text);
6015
+ if (parsed == null ? void 0 : parsed.error) return parsed.error;
6016
+ } catch {
6017
+ }
6018
+ ;
6019
+ return ((_a = text.match(OAUTH_ERROR_TITLE_PATTERN)) == null ? void 0 : _a[1]) || null;
6020
+ };
6021
+ var shopifyOAuthFetch = async (url, body) => {
6022
+ const response = await fetch(url, {
6023
+ method: "POST",
6024
+ headers: {
6025
+ "Content-Type": "application/json"
6026
+ },
6027
+ body: JSON.stringify(body)
6028
+ });
6029
+ if (!response.ok) {
6030
+ const text = await response.text().catch(() => "");
6031
+ const error = new Error(response.status + ": " + text);
6032
+ error.status = response.status;
6033
+ error.code = parseOAuthErrorCode(text);
6034
+ throw error;
6035
+ }
6036
+ ;
6037
+ return response.json();
6038
+ };
6039
+ var getShop = async ({ fetcher, adminAccessToken, shop }) => {
6040
+ const data = await adminFetch({
6041
+ fetcher,
6042
+ adminAccessToken,
6043
+ domain: shop,
6044
+ query: `{
6045
+ shop {
6046
+ currencyCode
6047
+ id
6048
+ myshopifyDomain
6049
+ name
6050
+ }
6051
+ }`
6052
+ });
6053
+ const shopData = data == null ? void 0 : data.shop;
6054
+ if (!(shopData == null ? void 0 : shopData.id)) {
6055
+ throw new Error("Shopify shop lookup failed: no shop returned");
6056
+ }
6057
+ ;
6058
+ return {
6059
+ currency: shopData.currencyCode || null,
6060
+ id: shopData.id.split("/").pop(),
6061
+ myshopifyDomain: shopData.myshopifyDomain,
6062
+ name: shopData.name
6063
+ };
6064
+ };
6065
+ var createStorefrontToken = async ({ fetcher, adminAccessToken, shop }) => {
6066
+ var _a, _b, _c, _d, _e;
6067
+ try {
6068
+ const listed = await adminFetch({
6069
+ fetcher,
6070
+ adminAccessToken,
6071
+ domain: shop,
6072
+ query: `{
6073
+ shop {
6074
+ storefrontAccessTokens(first: 100) {
6075
+ edges {
6076
+ node {
6077
+ id
6078
+ title
6079
+ }
6080
+ }
6081
+ }
6082
+ }
6083
+ }`
6084
+ });
6085
+ 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);
6086
+ const orphaned = existing.filter((token) => (token == null ? void 0 : token.title) === "Drawbridge");
6087
+ await Promise.allSettled(
6088
+ orphaned.map((token) => adminFetch({
6089
+ adminAccessToken,
6090
+ domain: shop,
6091
+ query: `
6092
+ mutation StorefrontAccessTokenDelete($input: StorefrontAccessTokenDeleteInput!) {
6093
+ storefrontAccessTokenDelete(input: $input) {
6094
+ deletedStorefrontAccessTokenId
6095
+ userErrors {
6096
+ field
6097
+ message
6098
+ }
6099
+ }
6100
+ }
6101
+ `,
6102
+ variables: {
6103
+ input: {
6104
+ id: token.id
6105
+ }
6106
+ }
6107
+ }))
6108
+ );
6109
+ } catch {
6110
+ }
6111
+ const created = await adminFetch({
6112
+ fetcher,
6113
+ adminAccessToken,
6114
+ domain: shop,
6115
+ query: `
6116
+ mutation StorefrontAccessTokenCreate($input: StorefrontAccessTokenInput!) {
6117
+ storefrontAccessTokenCreate(input: $input) {
6118
+ storefrontAccessToken {
6119
+ accessToken
6120
+ }
6121
+ userErrors {
6122
+ field
6123
+ message
6124
+ }
6125
+ }
6126
+ }
6127
+ `,
6128
+ variables: {
6129
+ input: {
6130
+ title: "Drawbridge"
6131
+ }
6132
+ }
6133
+ });
6134
+ const createErrors = (_c = created == null ? void 0 : created.storefrontAccessTokenCreate) == null ? void 0 : _c.userErrors;
6135
+ if (createErrors == null ? void 0 : createErrors.length) {
6136
+ throw new Error("Shopify storefront token create failed: " + createErrors[0].message);
6137
+ }
6138
+ ;
6139
+ return ((_e = (_d = created == null ? void 0 : created.storefrontAccessTokenCreate) == null ? void 0 : _d.storefrontAccessToken) == null ? void 0 : _e.accessToken) || null;
6140
+ };
6141
+ var resolveTokenContext = async ({ connection, controller }) => {
6142
+ const decrypted = (connection == null ? void 0 : connection.settings) ? decrypt(connection.settings) : {};
6143
+ if ((decrypted == null ? void 0 : decrypted.ref) !== "shop") {
6144
+ return {
6145
+ raw: (connection == null ? void 0 : connection.settings) || null,
6146
+ session: null,
6147
+ settings: decrypted,
6148
+ shop: null,
6149
+ target: "connection"
6150
+ };
6151
+ }
6152
+ ;
6153
+ const shop = decrypted.shop;
6154
+ if (!controller || !shop) {
6155
+ return { raw: null, session: {}, settings: {}, shop, target: "shop" };
6156
+ }
6157
+ ;
6158
+ const record = await controller.get({ collection: "shop", query: { shop } });
6159
+ const session = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : {};
6160
+ const storefront = (record == null ? void 0 : record.storefront) ? decrypt(record.storefront) : null;
6161
+ return {
6162
+ raw: (record == null ? void 0 : record.settings) || null,
6163
+ session,
6164
+ settings: {
6165
+ adminAccessToken: session.accessToken || null,
6166
+ refreshToken: session.refreshToken || null,
6167
+ refreshTokenExpiresAt: session.refreshTokenExpires || null,
6168
+ storefrontAccessToken: (storefront == null ? void 0 : storefront.token) || null,
6169
+ tokenExpiresAt: session.expires || null
6170
+ },
6171
+ shop,
6172
+ target: "shop"
6173
+ };
6174
+ };
6175
+ var resolveConnectionSettings = async ({ fetcher, connection, controller }) => {
6176
+ const { settings } = await resolveTokenContext({ connection, controller });
6177
+ return settings;
6178
+ };
6179
+ var refreshAdminToken = async ({ fetcher, clientId, clientSecret, connection, controller }) => {
6180
+ var _a;
6181
+ const { raw, session, settings, shop, target } = await resolveTokenContext({ connection, controller });
6182
+ const domain = (connection == null ? void 0 : connection.shop) || ((_a = settings.source) == null ? void 0 : _a.domain) || settings.domain || shop;
6183
+ const { refreshToken } = settings;
6184
+ const data = await shopifyOAuthFetch(
6185
+ `https://${domain}/admin/oauth/access_token`,
6186
+ {
6187
+ grant_type: "refresh_token",
6188
+ // Throw before the grant: rotation RETIRES the old pair the moment it
6189
+ // returns, so a credential-less call that Shopify rejects opaquely is
6190
+ // the one failure mode worth being loud about.
6191
+ client_id: required("clientId", clientId),
6192
+ client_secret: required("clientSecret", clientSecret),
6193
+ refresh_token: refreshToken
6194
+ }
6195
+ );
6196
+ const adminAccessToken = data.access_token;
6197
+ const newRefreshToken = data.refresh_token;
6198
+ const expiresIn = data.expires_in;
6199
+ const tokenExpiresAt = expiresIn ? new Date(Date.now() + expiresIn * 1e3) : null;
6200
+ const refreshTokenExpiresAt = new Date(Date.now() + REFRESH_TOKEN_LIFETIME_MS);
6201
+ let liveToken = adminAccessToken;
6202
+ if (target === "shop") {
6203
+ const written = await controller.update({
6204
+ collection: "shop",
6205
+ data: {
6206
+ $set: {
6207
+ settings: encrypt({
6208
+ ...session,
6209
+ accessToken: adminAccessToken,
6210
+ expires: tokenExpiresAt,
6211
+ refreshToken: newRefreshToken,
6212
+ refreshTokenExpires: refreshTokenExpiresAt
6213
+ })
6214
+ }
6215
+ },
6216
+ query: {
6217
+ shop,
6218
+ ...raw && { settings: raw }
6219
+ }
6220
+ });
6221
+ if (!written) {
6222
+ const current = await controller.get({ collection: "shop", query: { shop } });
6223
+ if (!(current == null ? void 0 : current.settings)) {
6224
+ throw new Error("Shopify token refresh write-back failed: shop record missing for " + shop);
6225
+ }
6226
+ ;
6227
+ const currentSession = decrypt(current.settings);
6228
+ if ((currentSession == null ? void 0 : currentSession.accessToken) && currentSession.accessToken !== settings.adminAccessToken) {
6229
+ liveToken = currentSession.accessToken;
6230
+ } else {
6231
+ throw new Error("Shopify token refresh write-back failed for " + shop);
6232
+ }
6233
+ ;
6234
+ }
6235
+ ;
6236
+ } else {
6237
+ const written = await controller.update({
6238
+ collection: "connection",
6239
+ data: {
6240
+ $set: {
6241
+ settings: encrypt({
6242
+ ...settings,
6243
+ adminAccessToken,
6244
+ refreshToken: newRefreshToken,
6245
+ refreshTokenExpiresAt,
6246
+ tokenExpiresAt
6247
+ })
6248
+ }
6249
+ },
6250
+ query: {
6251
+ id: connection.id,
6252
+ ...raw && { settings: raw }
6253
+ }
6254
+ });
6255
+ if (!written) {
6256
+ const current = await controller.get({ collection: "connection", query: { id: connection.id } });
6257
+ const currentSettings = (current == null ? void 0 : current.settings) ? decrypt(current.settings) : null;
6258
+ if ((currentSettings == null ? void 0 : currentSettings.adminAccessToken) && currentSettings.adminAccessToken !== settings.adminAccessToken) {
6259
+ liveToken = currentSettings.adminAccessToken;
6260
+ } else {
6261
+ throw new Error("Shopify token refresh write-back failed for connection " + (connection == null ? void 0 : connection.id));
6262
+ }
6263
+ ;
6264
+ }
6265
+ ;
6266
+ }
6267
+ ;
6268
+ await ping({ adminAccessToken: liveToken, domain });
6269
+ return liveToken;
6270
+ };
6271
+ var getAdminToken = async ({ fetcher, clientId, clientSecret, connection, controller }) => {
6272
+ required("clientId", clientId);
6273
+ required("clientSecret", clientSecret);
6274
+ const settings = await resolveConnectionSettings({ connection, controller });
6275
+ const { adminAccessToken, refreshToken, tokenExpiresAt } = settings;
6276
+ if (!adminAccessToken) {
6277
+ return null;
6278
+ }
6279
+ ;
6280
+ if (!refreshToken) {
6281
+ return adminAccessToken;
6282
+ }
6283
+ ;
6284
+ const needsRefresh = !tokenExpiresAt || new Date(tokenExpiresAt) < new Date(Date.now() + ACCESS_TOKEN_REFRESH_BUFFER_MS);
6285
+ if (needsRefresh) {
6286
+ return refreshAdminToken({ clientId, clientSecret, connection, controller });
6287
+ }
6288
+ ;
6289
+ return adminAccessToken;
6290
+ };
6291
+
6292
+ // lib/shopify/partner.js
6293
+ var partner_exports = {};
6294
+ __export(partner_exports, {
6295
+ getUsageChargeEvents: () => getUsageChargeEvents
6296
+ });
6297
+ var PARTNER_API = "https://partners.shopify.com";
6298
+ var getUsageChargeEvents = async ({ fetcher, appId, first = 10, occurredAtMin, organizationId, partnerToken, shopId }) => {
6299
+ var _a, _b, _c;
6300
+ if (!partnerToken || !organizationId || !appId) {
6301
+ throw new Error("getUsageChargeEvents requires partnerToken, organizationId, and appId");
6302
+ }
6303
+ ;
6304
+ const data = await request({
6305
+ fetcher,
6306
+ method: "POST",
6307
+ url: PARTNER_API + "/" + organizationId + "/api/" + PARTNER_API_VERSION + "/graphql.json",
6308
+ headers: {
6309
+ "X-Shopify-Access-Token": partnerToken
6310
+ },
6311
+ body: {
6312
+ query: `query usageCharges( $filter : EventFilterInput!, $first : Int! ) {
6313
+ events( filter : $filter, orderBy : OCCURRED_AT_DESC, first : $first ) {
6314
+ edges {
6315
+ node {
6316
+ id
6317
+ occurredAt
6318
+ eventType
6319
+ shop { id myshopifyDomain }
6320
+ ... on Charge {
6321
+ chargeId
6322
+ chargeType
6323
+ amount { amount currencyCode }
6324
+ usageQuantity
6325
+ planHandle
6326
+ description
6327
+ }
6328
+ }
6329
+ }
6330
+ pageInfo { hasNextPage endCursor }
6331
+ }
6332
+ }`,
6333
+ variables: {
6334
+ filter: {
6335
+ eventTypes: ["CHARGE_USAGE"],
6336
+ subjectId: String(appId),
6337
+ ...occurredAtMin && { occurredAtMin },
6338
+ ...shopId && { shopId: String(shopId) }
6339
+ },
6340
+ first
6341
+ }
6342
+ }
6343
+ });
6344
+ if ((_a = data == null ? void 0 : data.errors) == null ? void 0 : _a.length) {
6345
+ throw new Error("Shopify partner events query failed: " + data.errors.map((entry) => entry.message).join("; "));
6346
+ }
6347
+ ;
6348
+ return (((_c = (_b = data == null ? void 0 : data.data) == null ? void 0 : _b.events) == null ? void 0 : _c.edges) || []).map((edge) => {
6349
+ var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j;
6350
+ return {
6351
+ amount: ((_a2 = edge.node) == null ? void 0 : _a2.amount) || null,
6352
+ chargeId: ((_b2 = edge.node) == null ? void 0 : _b2.chargeId) || null,
6353
+ // USAGE vs the recurring plan charge an approval emits — the
6354
+ // disambiguator callers filter on.
6355
+ chargeType: ((_c2 = edge.node) == null ? void 0 : _c2.chargeType) || null,
6356
+ description: ((_d = edge.node) == null ? void 0 : _d.description) || null,
6357
+ eventType: ((_e = edge.node) == null ? void 0 : _e.eventType) || null,
6358
+ id: ((_f = edge.node) == null ? void 0 : _f.id) || null,
6359
+ occurredAt: ((_g = edge.node) == null ? void 0 : _g.occurredAt) || null,
6360
+ planHandle: ((_h = edge.node) == null ? void 0 : _h.planHandle) || null,
6361
+ shop: ((_i = edge.node) == null ? void 0 : _i.shop) || null,
6362
+ usageQuantity: ((_j = edge.node) == null ? void 0 : _j.usageQuantity) ?? null
6363
+ };
6364
+ });
6365
+ };
6366
+
6367
+ // lib/shopify/storefront.js
6368
+ var storefront_exports = {};
6369
+ __export(storefront_exports, {
6370
+ cartCreate: () => cartCreate,
6371
+ cartGet: () => cartGet,
6372
+ cartLinesAdd: () => cartLinesAdd,
6373
+ cartLinesRemove: () => cartLinesRemove,
6374
+ cartLinesUpdate: () => cartLinesUpdate,
6375
+ createCheckoutToken: () => createCheckoutToken,
6376
+ getProduct: () => getProduct,
6377
+ getProductVariantsPage: () => getProductVariantsPage,
6378
+ getProducts: () => getProducts,
6379
+ probeVariantsOutOfStock: () => probeVariantsOutOfStock
6380
+ });
6381
+ var SORT_KEY_MAP = {
6382
+ bestSelling: "BEST_SELLING",
6383
+ createdAt: "CREATED_AT",
6384
+ id: "ID",
6385
+ price: "PRICE",
6386
+ productType: "PRODUCT_TYPE",
6387
+ title: "TITLE",
6388
+ updatedAt: "UPDATED_AT",
6389
+ vendor: "VENDOR"
6390
+ };
6391
+ var resolveProductSort = (sort) => {
6392
+ const entry = sort && Object.entries(sort)[0];
6393
+ if (!entry) return null;
6394
+ const [field, direction] = entry;
6395
+ const sortKey = SORT_KEY_MAP[field];
6396
+ if (!sortKey) return null;
6397
+ return {
6398
+ sortKey,
6399
+ reverse: Number(direction) < 0
6400
+ };
6401
+ };
6402
+ var storefrontUrl = (domain) => `https://${domain}/api/${SHOPIFY_STOREFRONT_API_VERSION}/graphql.json`;
6403
+ var storefrontFetch = async ({ fetcher, domain, storefrontAccessToken, query, variables }) => {
6404
+ return request({
6405
+ method: "POST",
6406
+ url: storefrontUrl(domain),
6407
+ headers: {
6408
+ "X-Shopify-Storefront-Access-Token": storefrontAccessToken
6409
+ },
6410
+ body: {
6411
+ query,
6412
+ ...variables && { variables }
6413
+ }
6414
+ });
6415
+ };
6416
+ var shopCountryCache = {};
6417
+ var getShopCountry = async ({ domain, fetcher, storefrontAccessToken }) => {
6418
+ var _a, _b;
6419
+ if (shopCountryCache[domain]) return shopCountryCache[domain];
6420
+ const { data } = await storefrontFetch({
6421
+ fetcher,
6422
+ domain,
6423
+ storefrontAccessToken,
6424
+ query: `{
6425
+ shop {
6426
+ paymentSettings {
6427
+ countryCode
6428
+ }
6429
+ }
6430
+ }`
6431
+ });
6432
+ const countryCode = ((_b = (_a = data == null ? void 0 : data.shop) == null ? void 0 : _a.paymentSettings) == null ? void 0 : _b.countryCode) || null;
6433
+ if (countryCode) shopCountryCache[domain] = countryCode;
6434
+ return countryCode;
6435
+ };
6436
+ var OUT_OF_STOCK_WARNING_CODES = [
6437
+ "MERCHANDISE_OUT_OF_STOCK",
6438
+ "MERCHANDISE_NOT_ENOUGH_STOCK"
6439
+ ];
6440
+ var probeVariantsOutOfStock = async ({ fetcher, domain, storefrontAccessToken, variantIds, countryCode }) => {
6441
+ var _a, _b;
6442
+ if (!(variantIds == null ? void 0 : variantIds.length)) return [];
6443
+ const resolvedCountry = countryCode || await getShopCountry({ domain, fetcher, storefrontAccessToken });
6444
+ const { data, errors } = await storefrontFetch({
6445
+ fetcher,
6446
+ domain,
6447
+ storefrontAccessToken,
6448
+ query: `
6449
+ mutation probe( $input : CartInput! ){
6450
+ cartCreate( input : $input ){
6451
+ cart {
6452
+ lines( first : 250 ){
6453
+ edges {
6454
+ node {
6455
+ id
6456
+ merchandise {
6457
+ ... on ProductVariant {
6458
+ id
6459
+ }
6460
+ }
6461
+ }
6462
+ }
6463
+ }
6464
+ }
6465
+ warnings {
6466
+ code
6467
+ message
6468
+ target
6469
+ }
6470
+ }
6471
+ }
6472
+ `,
6473
+ variables: {
6474
+ input: {
6475
+ lines: variantIds.map((merchandiseId) => ({
6476
+ merchandiseId,
6477
+ quantity: 1
6478
+ })),
6479
+ ...resolvedCountry && {
6480
+ buyerIdentity: {
6481
+ countryCode: resolvedCountry
6482
+ }
6483
+ }
6484
+ }
6485
+ }
6486
+ });
6487
+ if (errors) return [];
6488
+ const payload = data == null ? void 0 : data.cartCreate;
6489
+ const soldOut = new Set(
6490
+ ((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)
6491
+ );
6492
+ 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 }) => {
6493
+ var _a2;
6494
+ return (_a2 = node == null ? void 0 : node.merchandise) == null ? void 0 : _a2.id;
6495
+ }).filter(Boolean);
6496
+ };
6497
+ var productsQuery = (search, cursor, limit, sort) => {
6498
+ const resolved = resolveProductSort(sort);
6499
+ const sortArgs = resolved ? `, sortKey: ${resolved.sortKey}, reverse: ${resolved.reverse}` : "";
6500
+ return `{
6501
+ products(first: ${limit}${search ? `, query: "title:*${search}*"` : ""}${cursor ? `, after: "${cursor}"` : ""}${sortArgs}) {
6502
+ edges {
6503
+ node {
6504
+ id
6505
+ title
6506
+ description
6507
+ handle
6508
+ productType
6509
+ featuredImage {
6510
+ url
6511
+ }
6512
+ variants(first: 10) {
6513
+ edges {
6514
+ node {
6515
+ id
6516
+ title
6517
+ image {
6518
+ url
6519
+ }
6520
+ price {
6521
+ amount
6522
+ currencyCode
6523
+ }
6524
+ compareAtPrice {
6525
+ amount
6526
+ currencyCode
6527
+ }
6528
+ availableForSale
6529
+ requiresShipping
6530
+ }
6531
+ }
6532
+ }
6533
+ }
6534
+ }
6535
+ pageInfo {
6536
+ endCursor
6537
+ hasNextPage
6538
+ hasPreviousPage
6539
+ startCursor
6540
+ }
6541
+ }
6542
+ }`;
6543
+ };
6544
+ var productQuery = (productId) => `{
6545
+ product(id: "${productId}") {
6546
+ id
6547
+ title
6548
+ description
6549
+ handle
6550
+ productType
6551
+ featuredImage {
6552
+ url
6553
+ }
6554
+ variants(first: 10) {
6555
+ edges {
6556
+ node {
6557
+ id
6558
+ title
6559
+ image {
6560
+ url
6561
+ }
6562
+ price {
6563
+ amount
6564
+ currencyCode
6565
+ }
6566
+ compareAtPrice {
6567
+ amount
6568
+ currencyCode
6569
+ }
6570
+ availableForSale
6571
+ requiresShipping
6572
+ }
6573
+ }
6574
+ }
6575
+ }
6576
+ }`;
6577
+ var variantsQuery = (productId, cursor) => `{
6578
+ product(id: "${productId}") {
6579
+ variants(first: 250${cursor ? `, after: "${cursor}"` : ""}) {
6580
+ edges {
6581
+ node {
6582
+ id
6583
+ title
6584
+ image {
6585
+ url
6586
+ }
6587
+ price {
6588
+ amount
6589
+ currencyCode
6590
+ }
6591
+ compareAtPrice {
6592
+ amount
6593
+ currencyCode
6594
+ }
6595
+ availableForSale
6596
+ requiresShipping
6597
+ }
6598
+ }
6599
+ pageInfo {
6600
+ hasNextPage
6601
+ endCursor
6602
+ }
6603
+ }
6604
+ }
6605
+ }`;
6606
+ var getProducts = async ({ fetcher, domain, storefrontAccessToken, search, cursor, limit, sort }) => {
6607
+ const { data, errors } = await storefrontFetch({
6608
+ fetcher,
6609
+ domain,
6610
+ storefrontAccessToken,
6611
+ query: productsQuery(search, cursor, limit, sort)
6612
+ });
6613
+ if (errors) {
6614
+ throw new Error("Failed to fetch Shopify products");
6615
+ }
6616
+ ;
6617
+ return data == null ? void 0 : data.products;
6618
+ };
6619
+ var getProduct = async ({ fetcher, domain, storefrontAccessToken, productId }) => {
6620
+ var _a;
6621
+ const { data, errors } = await storefrontFetch({
6622
+ fetcher,
6623
+ domain,
6624
+ storefrontAccessToken,
6625
+ query: productQuery(productId)
6626
+ });
6627
+ if (errors) {
6628
+ throw new Error("Shopify storefront error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
6629
+ }
6630
+ ;
6631
+ if (!(data == null ? void 0 : data.product)) {
6632
+ throw new Error("Shopify product not found");
6633
+ }
6634
+ ;
6635
+ return data.product;
6636
+ };
6637
+ var getProductVariantsPage = async ({ fetcher, domain, storefrontAccessToken, productId, cursor }) => {
6638
+ var _a;
6639
+ const { data, errors } = await storefrontFetch({
6640
+ fetcher,
6641
+ domain,
6642
+ storefrontAccessToken,
6643
+ query: variantsQuery(productId, cursor)
6644
+ });
6645
+ if (errors) {
6646
+ throw new Error("Shopify storefront error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
6647
+ }
6648
+ ;
6649
+ if (!(data == null ? void 0 : data.product)) {
6650
+ throw new Error("Shopify product not found");
6651
+ }
6652
+ ;
6653
+ return data.product.variants;
6654
+ };
6655
+ var CART_FIELDS = `
6656
+ id
6657
+ checkoutUrl
6658
+ lines(first: 100) {
6659
+ edges {
6660
+ node {
6661
+ id
6662
+ quantity
6663
+ merchandise {
6664
+ ... on ProductVariant {
6665
+ id
6666
+ title
6667
+ availableForSale
6668
+ image {
6669
+ url
6670
+ }
6671
+ price {
6672
+ amount
6673
+ currencyCode
6674
+ }
6675
+ product {
6676
+ title
6677
+ }
6678
+ }
6679
+ }
6680
+ }
6681
+ }
6682
+ }
6683
+ `;
6684
+ var mapCart = (cart) => {
6685
+ var _a;
6686
+ if (!cart) return null;
6687
+ return {
6688
+ checkoutUrl: cart.checkoutUrl,
6689
+ id: cart.id,
6690
+ lines: (((_a = cart.lines) == null ? void 0 : _a.edges) || []).map(({ node }) => {
6691
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
6692
+ return {
6693
+ availableForSale: ((_a2 = node == null ? void 0 : node.merchandise) == null ? void 0 : _a2.availableForSale) ?? true,
6694
+ currency: ((_c = (_b = node == null ? void 0 : node.merchandise) == null ? void 0 : _b.price) == null ? void 0 : _c.currencyCode) || null,
6695
+ id: node.id,
6696
+ image: ((_e = (_d = node == null ? void 0 : node.merchandise) == null ? void 0 : _d.image) == null ? void 0 : _e.url) || null,
6697
+ price: ((_g = (_f = node == null ? void 0 : node.merchandise) == null ? void 0 : _f.price) == null ? void 0 : _g.amount) || null,
6698
+ productTitle: ((_i = (_h = node == null ? void 0 : node.merchandise) == null ? void 0 : _h.product) == null ? void 0 : _i.title) || null,
6699
+ quantity: node.quantity,
6700
+ variantId: (_j = node == null ? void 0 : node.merchandise) == null ? void 0 : _j.id,
6701
+ variantTitle: ((_k = node == null ? void 0 : node.merchandise) == null ? void 0 : _k.title) || null
6702
+ };
6703
+ })
6704
+ };
6705
+ };
6706
+ var firstUserError = (userErrors) => {
6707
+ const error = userErrors == null ? void 0 : userErrors[0];
6708
+ if (!error) return null;
6709
+ const message = new Error(error.message || "Shopify cart error");
6710
+ message.userError = true;
6711
+ return message;
6712
+ };
6713
+ var createCheckoutToken = async ({ fetcher, clientId, clientSecret } = {}) => {
6714
+ if (!clientId || !clientSecret) {
6715
+ throw new Error("createCheckoutToken requires clientId and clientSecret");
6716
+ }
6717
+ ;
6718
+ const response = await request({
6719
+ fetcher,
6720
+ method: "POST",
6721
+ url: "https://api.shopify.com/auth/access_token",
6722
+ body: {
6723
+ client_id: clientId,
6724
+ client_secret: clientSecret,
6725
+ grant_type: "client_credentials"
6726
+ }
6727
+ });
6728
+ const token = response == null ? void 0 : response.access_token;
6729
+ if (!token) {
6730
+ throw new Error("Failed to create Shopify checkout token");
6731
+ }
6732
+ ;
6733
+ return token;
6734
+ };
6735
+ var cartCreate = async ({ fetcher, domain, storefrontAccessToken, lines }) => {
6736
+ var _a, _b;
6737
+ const { data, errors } = await storefrontFetch({
6738
+ fetcher,
6739
+ domain,
6740
+ storefrontAccessToken,
6741
+ query: `
6742
+ mutation cartCreate($input: CartInput!) {
6743
+ cartCreate(input: $input) {
6744
+ cart {
6745
+ ${CART_FIELDS}
6746
+ }
6747
+ userErrors {
6748
+ field
6749
+ message
6750
+ }
6751
+ }
6752
+ }
6753
+ `,
6754
+ variables: {
6755
+ input: {
6756
+ lines
6757
+ }
6758
+ }
6759
+ });
6760
+ if (errors) {
6761
+ throw new Error("Failed to create Shopify cart");
6762
+ }
6763
+ ;
6764
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartCreate) == null ? void 0 : _a.userErrors);
6765
+ if (userError) throw userError;
6766
+ return mapCart((_b = data == null ? void 0 : data.cartCreate) == null ? void 0 : _b.cart);
6767
+ };
6768
+ var cartGet = async ({ fetcher, domain, storefrontAccessToken, cartId }) => {
6769
+ const { data, errors } = await storefrontFetch({
6770
+ fetcher,
6771
+ domain,
6772
+ storefrontAccessToken,
6773
+ query: `
6774
+ query cart($id: ID!) {
6775
+ cart(id: $id) {
6776
+ ${CART_FIELDS}
6777
+ }
6778
+ }
6779
+ `,
6780
+ variables: {
6781
+ id: cartId
6782
+ }
6783
+ });
6784
+ if (errors) {
6785
+ throw new Error("Failed to fetch Shopify cart");
6786
+ }
6787
+ ;
6788
+ return mapCart(data == null ? void 0 : data.cart);
6789
+ };
6790
+ var cartLinesAdd = async ({ fetcher, domain, storefrontAccessToken, cartId, lines }) => {
6791
+ var _a, _b;
6792
+ const { data, errors } = await storefrontFetch({
6793
+ fetcher,
6794
+ domain,
6795
+ storefrontAccessToken,
6796
+ query: `
6797
+ mutation cartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {
6798
+ cartLinesAdd(cartId: $cartId, lines: $lines) {
6799
+ cart {
6800
+ ${CART_FIELDS}
6801
+ }
6802
+ userErrors {
6803
+ field
6804
+ message
6805
+ }
6806
+ }
6807
+ }
6808
+ `,
6809
+ variables: {
6810
+ cartId,
6811
+ lines
6812
+ }
6813
+ });
6814
+ if (errors) {
6815
+ throw new Error("Failed to add Shopify cart lines");
6816
+ }
6817
+ ;
6818
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartLinesAdd) == null ? void 0 : _a.userErrors);
6819
+ if (userError) throw userError;
6820
+ return mapCart((_b = data == null ? void 0 : data.cartLinesAdd) == null ? void 0 : _b.cart);
6821
+ };
6822
+ var cartLinesRemove = async ({ fetcher, domain, storefrontAccessToken, cartId, lineIds }) => {
6823
+ var _a, _b;
6824
+ const { data, errors } = await storefrontFetch({
6825
+ fetcher,
6826
+ domain,
6827
+ storefrontAccessToken,
6828
+ query: `
6829
+ mutation cartLinesRemove($cartId: ID!, $lineIds: [ID!]!) {
6830
+ cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {
6831
+ cart {
6832
+ ${CART_FIELDS}
6833
+ }
6834
+ userErrors {
6835
+ field
6836
+ message
6837
+ }
6838
+ }
6839
+ }
6840
+ `,
6841
+ variables: {
6842
+ cartId,
6843
+ lineIds
6844
+ }
6845
+ });
6846
+ if (errors) {
6847
+ throw new Error("Failed to remove Shopify cart lines");
6848
+ }
6849
+ ;
6850
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartLinesRemove) == null ? void 0 : _a.userErrors);
6851
+ if (userError) throw userError;
6852
+ return mapCart((_b = data == null ? void 0 : data.cartLinesRemove) == null ? void 0 : _b.cart);
6853
+ };
6854
+ var cartLinesUpdate = async ({ fetcher, domain, storefrontAccessToken, cartId, lines }) => {
6855
+ var _a, _b;
6856
+ const { data, errors } = await storefrontFetch({
6857
+ fetcher,
6858
+ domain,
6859
+ storefrontAccessToken,
6860
+ query: `
6861
+ mutation cartLinesUpdate($cartId: ID!, $lines: [CartLineUpdateInput!]!) {
6862
+ cartLinesUpdate(cartId: $cartId, lines: $lines) {
6863
+ cart {
6864
+ ${CART_FIELDS}
6865
+ }
6866
+ userErrors {
6867
+ field
6868
+ message
6869
+ }
6870
+ }
6871
+ }
6872
+ `,
6873
+ variables: {
6874
+ cartId,
6875
+ lines
6876
+ }
6877
+ });
6878
+ if (errors) {
6879
+ throw new Error("Failed to update Shopify cart lines");
6880
+ }
6881
+ ;
6882
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartLinesUpdate) == null ? void 0 : _a.userErrors);
6883
+ if (userError) throw userError;
6884
+ return mapCart((_b = data == null ? void 0 : data.cartLinesUpdate) == null ? void 0 : _b.cart);
6885
+ };
6886
+
6887
+ // lib/email.js
6888
+ var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
6889
+ var toCanonicalEmail = (value) => {
6890
+ if (!value || typeof value !== "string") return null;
6891
+ const email = value.trim().toLowerCase();
6892
+ const at = email.lastIndexOf("@");
6893
+ if (at < 1 || at === email.length - 1) return null;
6894
+ let local = email.slice(0, at);
6895
+ const domain = email.slice(at + 1);
6896
+ const plus = local.indexOf("+");
6897
+ if (plus > 0) local = local.slice(0, plus);
6898
+ if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
6899
+ if (!local) return null;
6900
+ return local + "@" + domain;
6901
+ };
6902
+
6903
+ // lib/oauth/index.js
6904
+ var lifetimes = {
6905
+ access: 60 * 60 * 8,
6906
+ // 8 hours
6907
+ authorizationCode: 10 * 60,
6908
+ // 10 minutes
6909
+ code: 15 * 60,
6910
+ // 15 minutes (email OTC)
6911
+ refresh: 30 * 24 * 60 * 60
6912
+ // 30 days
6913
+ };
6914
+ var tokenTypes = {
6915
+ access: "access",
6916
+ oauthState: "oauth.state",
6917
+ pat: "pat",
6918
+ refresh: "refresh"
6919
+ };
6920
+ var scopes = [
6921
+ "profile:read",
6922
+ "profile:write",
6923
+ "organization:read",
6924
+ "organization:write",
6925
+ "campaigns:read",
6926
+ "campaigns:write",
6927
+ "contacts:read",
6928
+ "contacts:write",
6929
+ "workflows:read",
6930
+ "workflows:write",
6931
+ "connections:read",
6932
+ "connections:write",
6933
+ "billing:read",
6934
+ "billing:write",
6935
+ "admin"
6936
+ ];
6937
+ var developer = [
6938
+ "profile:read",
6939
+ "organization:read",
6940
+ "campaigns:read",
6941
+ "campaigns:write",
6942
+ "contacts:read",
6943
+ "contacts:write",
6944
+ "workflows:read",
6945
+ "workflows:write",
6946
+ "connections:read",
6947
+ "connections:write"
6948
+ ];
6949
+ var scopeLabels = {
6950
+ "profile:read": "Read own profile",
6951
+ "profile:write": "Update own profile",
6952
+ "organization:read": "Read organization info",
6953
+ "organization:write": "Manage organization",
6954
+ "campaigns:read": "Read campaigns",
6955
+ "campaigns:write": "Manage campaigns",
6956
+ "contacts:read": "Read contacts",
6957
+ "contacts:write": "Manage contacts",
6958
+ "workflows:read": "Read workflows",
6959
+ "workflows:write": "Manage workflows",
6960
+ "connections:read": "Read integrations",
6961
+ "connections:write": "Manage integrations",
6962
+ "billing:read": "Read billing",
6963
+ "billing:write": "Manage billing",
6964
+ admin: "Admin access"
6965
+ };
6966
+ var toOption = (scope) => ({
6967
+ key: scopeLabels[scope] || scope,
6968
+ value: scope
6969
+ });
6970
+ var developerOptions = developer.map(toOption);
6971
+ var scopeOptions = scopes.map(toOption);
6972
+ var hashToken = (raw) => hash(raw, process.env.HMAC_OAUTH_TOKEN_KEY);
6973
+
6974
+ // lib/sanitize.js
6975
+ var import_disposable_email_domains = __toESM(require("disposable-email-domains/index.js"), 1);
6976
+ var disposableBlacklist = new Set(import_disposable_email_domains.default.map((d) => d.toLowerCase()));
6977
+ var sanitizeDomain = (value, pattern) => {
6978
+ if (!value) return value;
6979
+ const cleaned = value.trim().toLowerCase().replace(/^https?:\/\//i, "").replace(/\/+$/, "");
6980
+ if (pattern) {
6981
+ const match = cleaned.match(pattern);
6982
+ return match ? match[0] : cleaned;
6983
+ }
6984
+ return cleaned;
6985
+ };
6986
+
6987
+ // lib/slugify.js
6988
+ var import_slugify = __toESM(require("slugify"), 1);
6989
+ var slugify = (value, nochars = false) => {
6990
+ const remove = nochars ? /[-?*+~.()'"!:@#^_{}\[\];,/\\]/g : /[?*+~.()'"!:@#^_{}\[\];,/\\]/g;
6991
+ const replacement = nochars ? "" : "-";
6992
+ return (0, import_slugify.default)(
6993
+ value,
6994
+ {
6995
+ remove,
6996
+ replacement,
6997
+ lower: true,
6998
+ trim: true
6999
+ }
7000
+ );
7001
+ };
7002
+
7003
+ // lib/connections/manifests/shopify.js
7004
+ var client = Object.freeze({
7005
+ admin: admin_exports,
7006
+ billing: billing_exports,
7007
+ oauth: oauth_exports,
7008
+ partner: partner_exports,
7009
+ storefront: storefront_exports
7010
+ });
7011
+ var toLine = ({
7012
+ price,
7013
+ product_id: productId,
7014
+ quantity,
7015
+ title,
7016
+ variant_id: variantId,
7017
+ variant_title: variantTitle
7018
+ }) => ({
7019
+ price: parseFloat(price) || 0,
7020
+ productId: productId ? "gid://shopify/Product/" + productId : null,
7021
+ quantity: quantity || 1,
7022
+ title: title || null,
7023
+ variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
7024
+ variantTitle: variantTitle || null
7025
+ });
7026
+ var attributeLineItems = (lineItems = []) => lineItems.reduce(
7027
+ (acc, item) => {
7028
+ const attrs = (item.properties || []).reduce(
7029
+ (map, { name, value }) => {
7030
+ map[name] = value;
7031
+ return map;
7032
+ },
7033
+ {}
7034
+ );
7035
+ if (!attrs["_drwbrdg_ca"]) return acc;
7036
+ if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
7037
+ const line = toLine(item);
7038
+ acc.attributedGross += line.price * line.quantity;
7039
+ acc.attributedLines.push(line);
7040
+ return acc;
7041
+ },
7042
+ { attrMap: {}, attributedGross: 0, attributedLines: [] }
7043
+ );
7044
+ var generateDiscountCode = (0, import_nanoid.customAlphabet)("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
7045
+ var blockedReason = (discount) => {
7046
+ var _a;
7047
+ if ((discount == null ? void 0 : discount.status) === "EXPIRED") return "This discount has expired.";
7048
+ const buyers = (_a = discount == null ? void 0 : discount.context) == null ? void 0 : _a.__typename;
7049
+ if (buyers && buyers !== "DiscountBuyerSelectionAll") {
7050
+ 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.";
7051
+ }
7052
+ ;
7053
+ if (typeof (discount == null ? void 0 : discount.usageLimit) === "number" && discount.usageLimit > 0 && ((discount == null ? void 0 : discount.asyncUsageCount) || 0) >= discount.usageLimit) {
7054
+ return "This discount has reached its total usage limit.";
7055
+ }
7056
+ ;
7057
+ return null;
7058
+ };
7059
+ var discountWarning = (discount) => {
7060
+ if ((discount == null ? void 0 : discount.status) === "SCHEDULED") {
7061
+ return "This discount hasn't started yet, so codes issued before it does won't work until then.";
7062
+ }
7063
+ ;
7064
+ if (discount == null ? void 0 : discount.appliesOncePerCustomer) return "Each customer can use this discount only once.";
7065
+ return null;
7066
+ };
7067
+ var ORDER_EVENT_HANDLE = slugify("drawbridge-orders");
7068
+ var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
7069
+ var OAUTH_ERROR_SOURCE = "oauth";
7070
+ var BILLING_ERROR_SOURCE = "billing";
7071
+ var BILLING_ERROR_MESSAGE = "Order billing isn't set up for this store \u2014 reselect and approve the plan from the Shopify connection page.";
7072
+ var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
7073
+ var inbound = {
7074
+ headers: {
7075
+ event: "x-shopify-topic",
7076
+ id: "x-shopify-webhook-id",
7077
+ shop: "x-shopify-shop-domain",
7078
+ signature: "x-shopify-hmac-sha256"
7079
+ },
7080
+ signature: {
7081
+ algorithm: "sha256",
7082
+ encoding: "base64",
7083
+ secret: "SHOPIFY_API_SECRET"
7084
+ }
7085
+ };
7086
+ var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
5227
7087
  "customers/data_request",
5228
7088
  "customers/redact",
5229
7089
  "shop/redact"
5230
7090
  ]);
7091
+ var refusal = (message, status) => Object.assign(new Error(message), { status });
7092
+ var LINK_TOKEN_TTL_MS = 30 * 60 * 1e3;
7093
+ var CONNECTABLE_STATUSES = ["active", "unsubscribed"];
7094
+ var merchantOrganizations = ({ read, user }) => read.aggregate({
7095
+ collection: "organization",
7096
+ pipeline: [
7097
+ // A member qualifies only at `manage`; an owner always qualifies.
7098
+ {
7099
+ $lookup: {
7100
+ as: "membership",
7101
+ from: "member",
7102
+ let: { organization: "$id" },
7103
+ pipeline: [
7104
+ {
7105
+ $match: {
7106
+ $expr: { $eq: ["$organization", "$$organization"] },
7107
+ "capabilities.connections": "manage",
7108
+ status: "accepted",
7109
+ user
7110
+ }
7111
+ },
7112
+ { $limit: 1 },
7113
+ { $project: { _id: 0, organization: 1 } }
7114
+ ]
7115
+ }
7116
+ },
7117
+ {
7118
+ $match: {
7119
+ status: { $ne: "canceled" },
7120
+ $or: [{ owner: user }, { "membership.0": { $exists: true } }]
7121
+ }
7122
+ },
7123
+ // `organization.subscription` is a subscription RECORD ID — resolved here so
7124
+ // the list can read the real plan and conversion rate. Without it every org
7125
+ // rendered as free tier.
7126
+ { $lookup: { as: "subscription", foreignField: "id", from: "subscription", localField: "subscription" } },
7127
+ { $unwind: { path: "$subscription", preserveNullAndEmptyArrays: true } },
7128
+ {
7129
+ $lookup: {
7130
+ as: "connection",
7131
+ foreignField: "organization",
7132
+ from: "connection",
7133
+ localField: "id",
7134
+ pipeline: [
7135
+ { $match: { slug: "shopify" } },
7136
+ { $limit: 1 },
7137
+ { $project: { _id: 0, id: 1, shop: 1, status: 1 } }
7138
+ ]
7139
+ }
7140
+ },
7141
+ { $unwind: { path: "$connection", preserveNullAndEmptyArrays: true } },
7142
+ { $project: { _id: 0, billingStatus: "$status", connection: 1, id: 1, name: "$title", subscription: 1 } },
7143
+ { $sort: { name: 1 } }
7144
+ ]
7145
+ });
7146
+ var storePlan = async ({ record, shopify }) => {
7147
+ var _a;
7148
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
7149
+ if (!(settings == null ? void 0 : settings.accessToken)) return { active: false, name: null };
7150
+ try {
7151
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
7152
+ adminAccessToken: settings.accessToken,
7153
+ domain: record.shop
7154
+ });
7155
+ const active = (subscriptions || []).length > 0;
7156
+ const metered = active && subscriptions.some((subscription) => subscription.metered === true) ? true : null;
7157
+ return { active, metered, name: active ? ((_a = subscriptions[0]) == null ? void 0 : _a.name) || null : null };
7158
+ } catch (_) {
7159
+ return { active: false, name: null, unavailable: true };
7160
+ }
7161
+ };
7162
+ var releaseApprovals = async ({ context, read, shopify }) => {
7163
+ var _a;
7164
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
7165
+ if (!shop) throw refusal("shop is required", 400);
7166
+ const record = await read.get({ collection: "shop", query: { shop } });
7167
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
7168
+ if (!(settings == null ? void 0 : settings.accessToken)) throw refusal("Store is not installed", 409);
7169
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
7170
+ adminAccessToken: settings.accessToken,
7171
+ domain: shop
7172
+ });
7173
+ for (const subscription of subscriptions || []) {
7174
+ const data = await shopify.admin.adminFetch({
7175
+ adminAccessToken: settings.accessToken,
7176
+ domain: shop,
7177
+ query: "mutation appSubscriptionCancel( $id : ID! ) { appSubscriptionCancel( id : $id ) { appSubscription { id status } userErrors { field message } } }",
7178
+ variables: { id: subscription.id }
7179
+ });
7180
+ const [userError] = ((_a = data == null ? void 0 : data.appSubscriptionCancel) == null ? void 0 : _a.userErrors) || [];
7181
+ if (userError) throw refusal(userError.message, 422);
7182
+ }
7183
+ return {
7184
+ message: "Released " + (subscriptions || []).length + " approval(s).",
7185
+ request: { shop },
7186
+ result: { ok: true }
7187
+ };
7188
+ };
7189
+ var LEDGER_WINDOW_MS = 30 * 24 * 60 * 60 * 1e3;
7190
+ var meterVerdict = async ({ adminAccessToken, ledgerFloor, partner, shop, shopId, shopify }) => {
7191
+ var _a;
7192
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({ adminAccessToken, domain: shop });
7193
+ let metered = (_a = subscriptions.find((subscription) => subscription.usageLineItemId)) == null ? void 0 : _a.usageLineItemId;
7194
+ if (!((partner == null ? void 0 : partner.partnerToken) && (partner == null ? void 0 : partner.partnerOrgId) && (partner == null ? void 0 : partner.partnerAppId) && shopId)) {
7195
+ return { boundaries: [], ledger: false, metered };
7196
+ }
7197
+ const accruals = await shopify.partner.getUsageChargeEvents({
7198
+ appId: "gid://shopify/App/" + partner.partnerAppId,
7199
+ first: 10,
7200
+ occurredAtMin: ledgerFloor.toISOString(),
7201
+ organizationId: partner.partnerOrgId,
7202
+ partnerToken: partner.partnerToken,
7203
+ shopId: "gid://shopify/Shop/" + shopId
7204
+ });
7205
+ const boundaries = (accruals || []).filter((event) => event.occurredAt).sort((a, b) => new Date(a.occurredAt) - new Date(b.occurredAt));
7206
+ const accrued = [...boundaries].reverse().find((event) => Number(event.usageQuantity) > 0);
7207
+ if (accrued) metered = String(accrued.chargeId || accrued.id);
7208
+ return { boundaries, ledger: true, metered };
7209
+ };
7210
+ var toVariant = (edge) => {
7211
+ var _a, _b, _c, _d;
7212
+ return {
7213
+ availableForSale: edge.node.availableForSale || false,
7214
+ currency: ((_a = edge.node.price) == null ? void 0 : _a.currencyCode) || null,
7215
+ id: edge.node.id,
7216
+ image: ((_b = edge.node.image) == null ? void 0 : _b.url) || null,
7217
+ price: parseFloat((_c = edge.node.price) == null ? void 0 : _c.amount) || null,
7218
+ requiresShipping: edge.node.requiresShipping || false,
7219
+ sale: parseFloat((_d = edge.node.compareAtPrice) == null ? void 0 : _d.amount) || null,
7220
+ title: edge.node.title !== "Default Title" ? edge.node.title : null
7221
+ };
7222
+ };
7223
+ var applyOutOfStock = async ({ domain, shopify, storefrontAccessToken, variants }) => {
7224
+ try {
7225
+ const outOfStock = new Set(await shopify.storefront.probeVariantsOutOfStock({
7226
+ domain,
7227
+ storefrontAccessToken,
7228
+ variantIds: variants.map((variant) => variant.id)
7229
+ }));
7230
+ return variants.map((variant) => ({
7231
+ ...variant,
7232
+ availableForSale: variant.availableForSale && !outOfStock.has(variant.id)
7233
+ }));
7234
+ } catch (_) {
7235
+ return variants;
7236
+ }
7237
+ };
7238
+ var sendFeedback = async ({ adminToken, connection, messages, productId, shopify, state }) => {
7239
+ try {
7240
+ await shopify.admin.sendProductResourceFeedback({
7241
+ adminAccessToken: await adminToken(),
7242
+ domain: connection.shop,
7243
+ messages,
7244
+ productId,
7245
+ state
7246
+ });
7247
+ return null;
7248
+ } catch (error) {
7249
+ return error;
7250
+ }
7251
+ };
7252
+ var resolveProduct = async ({ connection, context, read }) => {
7253
+ const byId = (context == null ? void 0 : context.product) ? await read.get({ collection: "product", query: { id: context.product } }) : null;
7254
+ const row2 = byId || ((context == null ? void 0 : context.providerId) && ((context == null ? void 0 : context.shop) || (connection == null ? void 0 : connection.shop)) ? await read.get({
7255
+ collection: "product",
7256
+ query: {
7257
+ "provider.id": context.providerId,
7258
+ "provider.slug": "shopify",
7259
+ "source.domain": context.shop || connection.shop
7260
+ }
7261
+ }) : null);
7262
+ return row2;
7263
+ };
7264
+ var UNAVAILABLE_FEEDBACK = "Drawbridge can't display this product. Check it is active and available in the United States.";
7265
+ var NOT_FOUND = "Shopify product not found";
7266
+ var syncProduct = async ({ adminToken, connection, context, read, settings, shopify }) => {
7267
+ var _a, _b, _c;
7268
+ const row2 = await resolveProduct({ connection, context, read });
7269
+ if (!row2) return { message: "No product row to sync.", request: { product: (context == null ? void 0 : context.product) || null }, skipped: true };
7270
+ const domain = connection.shop;
7271
+ const providerId = (_a = row2.provider) == null ? void 0 : _a.id;
7272
+ const request2 = { product: row2.id, providerId: providerId || null, shop: domain };
7273
+ let product;
7274
+ try {
7275
+ product = await shopify.storefront.getProduct({
7276
+ domain,
7277
+ productId: providerId,
7278
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
7279
+ });
7280
+ } catch (error) {
7281
+ if (error.message !== NOT_FOUND) throw error;
7282
+ const failed2 = await sendFeedback({
7283
+ adminToken,
7284
+ connection,
7285
+ messages: [UNAVAILABLE_FEEDBACK],
7286
+ productId: providerId,
7287
+ shopify,
7288
+ state: "REQUIRES_ACTION"
7289
+ });
7290
+ return {
7291
+ failed: failed2 ? [failed2.message] : void 0,
7292
+ message: "Storefront cannot see this product \u2014 deactivated.",
7293
+ request: request2,
7294
+ result: { status: "inactive" },
7295
+ writes: [
7296
+ {
7297
+ collection: "product",
7298
+ data: { $set: { status: "inactive" } },
7299
+ operation: "update",
7300
+ query: { id: row2.id }
7301
+ },
7302
+ {
7303
+ collection: "advertisement",
7304
+ data: { $set: { status: "drafted" } },
7305
+ multiple: true,
7306
+ operation: "update",
7307
+ query: { product: row2.id }
7308
+ }
7309
+ ]
7310
+ };
7311
+ }
7312
+ const variants = await applyOutOfStock({
7313
+ domain,
7314
+ shopify,
7315
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken,
7316
+ variants: (((_b = product == null ? void 0 : product.variants) == null ? void 0 : _b.edges) || []).map(toVariant)
7317
+ });
7318
+ const failed = await sendFeedback({
7319
+ adminToken,
7320
+ connection,
7321
+ messages: [],
7322
+ productId: providerId,
7323
+ shopify,
7324
+ state: "ACCEPTED"
7325
+ });
7326
+ return {
7327
+ // EVERYTHING PAST THE FIRST PAGE, filled in silently. The first page is
7328
+ // written above; a product with thousands of variants becomes N short
7329
+ // sequential jobs rather than one long loop that risks a BullMQ stall.
7330
+ enqueues: [{
7331
+ data: { operation: "variants", product: row2.id },
7332
+ name: "sync",
7333
+ options: { jobId: "product.shopify.variants." + row2.id + "." + Date.now() },
7334
+ queue: "product.shopify.variants"
7335
+ }],
7336
+ failed: failed ? [failed.message] : void 0,
7337
+ message: "Synced " + (product.title || "product") + ".",
7338
+ request: request2,
7339
+ result: { status: "active", variants: variants.length },
7340
+ writes: [{
7341
+ collection: "product",
7342
+ data: {
7343
+ $set: {
7344
+ description: product.description || null,
7345
+ image: ((_c = product.featuredImage) == null ? void 0 : _c.url) || null,
7346
+ // A successful sync PROVES channel visibility, which reverses the
7347
+ // deactivation above. Ads stay drafted.
7348
+ status: "active",
7349
+ title: product.title || null,
7350
+ type: product.productType || null,
7351
+ url: domain && product.handle ? "https://" + domain + "/products/" + product.handle : null,
7352
+ variants
7353
+ }
7354
+ },
7355
+ operation: "update",
7356
+ query: { id: row2.id }
7357
+ }]
7358
+ };
7359
+ };
7360
+ var syncVariants = async ({ connection, context, read, settings, shopify }) => {
7361
+ var _a, _b, _c;
7362
+ const row2 = await resolveProduct({ connection, context, read });
7363
+ if (!row2) return { message: "No product row to paginate.", request: { product: (context == null ? void 0 : context.product) || null }, skipped: true };
7364
+ const cursor = (context == null ? void 0 : context.cursor) || null;
7365
+ const request2 = { cursor, product: row2.id };
7366
+ let page;
7367
+ try {
7368
+ page = await shopify.storefront.getProductVariantsPage({
7369
+ cursor,
7370
+ domain: connection.shop,
7371
+ productId: (_a = row2.provider) == null ? void 0 : _a.id,
7372
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
7373
+ });
7374
+ } catch (error) {
7375
+ if (error.message !== NOT_FOUND) throw error;
7376
+ return { message: "Storefront lost this product mid-pagination \u2014 stopping.", request: request2, skipped: true };
7377
+ }
7378
+ const variants = await applyOutOfStock({
7379
+ domain: connection.shop,
7380
+ shopify,
7381
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken,
7382
+ variants: (page.edges || []).map(toVariant)
7383
+ });
7384
+ return {
7385
+ ...((_b = page.pageInfo) == null ? void 0 : _b.hasNextPage) && { enqueues: [{
7386
+ data: { cursor: page.pageInfo.endCursor, operation: "variants", product: row2.id },
7387
+ name: "page",
7388
+ options: { jobId: "product.shopify.variants." + row2.id + "." + Date.now() },
7389
+ queue: "product.shopify.variants"
7390
+ }] },
7391
+ message: variants.length + " variant(s) on this page.",
7392
+ request: request2,
7393
+ result: { hasNextPage: Boolean((_c = page.pageInfo) == null ? void 0 : _c.hasNextPage), variants: variants.length },
7394
+ writes: [{
7395
+ collection: "product",
7396
+ data: cursor ? { $push: { variants: { $each: variants } } } : { $set: { variants } },
7397
+ operation: "update",
7398
+ query: { id: row2.id }
7399
+ }]
7400
+ };
7401
+ };
5231
7402
  var shopify_default2 = {
5232
7403
  // THE WORDS ON THE BUTTONS. `listing` was `content.redirect.title`, which put
5233
7404
  // a BUTTON LABEL inside the copy object next to a url — the title and the
@@ -5414,8 +7585,8 @@ var shopify_default2 = {
5414
7585
  // string; this answers what is missing from it.
5415
7586
  //
5416
7587
  // `shopify` is injected for the same reason it is everywhere else — this
5417
- // package cannot import @drawbridge/shopify, which depends on it.
5418
- scopes: ({ scope }, { shopify } = {}) => ({ result: { missing: scope ? shopify.oauth.missingScopes(scope) : null } }),
7588
+ // client is imported here and defaulted, never wired in by a caller.
7589
+ scopes: ({ scope }, { shopify = client } = {}) => ({ result: { missing: scope ? shopify.oauth.missingScopes(scope) : null } }),
5419
7590
  // Shopify's install grant is exchanged inside its own app flow, not
5420
7591
  // through the shared OAuth runner.
5421
7592
  token: false
@@ -5429,17 +7600,53 @@ var shopify_default2 = {
5429
7600
  // can reference another), `dispatch` (the caller's own coordinator table,
5430
7601
  // for the hooks that are dispatches).
5431
7602
  commerce: {
5432
- // NOT YET. The Checkout Kit cart path is `api/route/subdomain.js`, six direct
5433
- // calls into `@drawbridge/shopify/storefront` that write nothing — which is
5434
- // exactly why it never became a hook: a hook is reached to have its effects
5435
- // performed, and this one has none to perform. It moves here when the vendor
5436
- // client moves into the manifest and `subdomain.js` stops importing the
5437
- // package directly.
5438
- cart: false,
7603
+ // THE CHECKOUT KIT CART. Six operations that were six direct calls into
7604
+ // the storefront client from api/route/subdomain.js.
7605
+ //
7606
+ // IT WRITES NOTHING, which is exactly why it was the last surface to
7607
+ // become a hook a hook is usually reached to have its effects performed
7608
+ // and this one has none. That reasoning was wrong: a hook is also the one
7609
+ // place a vendor's client is allowed to be called from, and leaving the
7610
+ // cart out meant a public route importing a vendor SDK directly.
7611
+ //
7612
+ // ONE HOOK, OPERATION IN THE CONTEXT, the same shape `inbound.process`
7613
+ // uses for its topic table. Six slots would be six names in the closed
7614
+ // vocabulary for one question — what does this shopper's cart look like
7615
+ // now — asked six ways.
7616
+ //
7617
+ // A USER ERROR IS A 400 AND THE SHOPPER'S OWN WORDS. Shopify's cart
7618
+ // mutations answer "that variant is sold out" as a userError rather than a
7619
+ // transport failure, and the route it replaced already told the two apart.
7620
+ // runHook carries `status` off a thrown error, so it survives to the
7621
+ // caller; the rest of a thrown error's shape does not.
7622
+ cart: async ({ clientId, clientSecret, context, settings }, { fetcher, shopify = client } = {}) => {
7623
+ const { cartId, lineIds, lines, operation } = context || {};
7624
+ const { domain, storefrontAccessToken } = settings || {};
7625
+ if (operation === "checkout") {
7626
+ const token = await shopify.storefront.createCheckoutToken({ clientId, clientSecret, fetcher });
7627
+ return { message: "Checkout token minted.", result: { token } };
7628
+ }
7629
+ const storefront = { domain, fetcher, storefrontAccessToken };
7630
+ try {
7631
+ const cart = await ({
7632
+ create: () => shopify.storefront.cartCreate({ ...storefront, lines }),
7633
+ get: () => shopify.storefront.cartGet({ ...storefront, cartId }),
7634
+ linesAdd: () => shopify.storefront.cartLinesAdd({ ...storefront, cartId, lines }),
7635
+ linesRemove: () => shopify.storefront.cartLinesRemove({ ...storefront, cartId, lineIds }),
7636
+ linesUpdate: () => shopify.storefront.cartLinesUpdate({ ...storefront, cartId, lines })
7637
+ }[operation] || (() => {
7638
+ throw Object.assign(new Error("Unknown cart operation: " + operation), { status: 400 });
7639
+ }))();
7640
+ return { message: "Cart " + operation + ".", request: { cartId: cartId || null, operation }, result: cart };
7641
+ } catch (error) {
7642
+ if (error == null ? void 0 : error.userError) throw Object.assign(error, { status: 400 });
7643
+ throw error;
7644
+ }
7645
+ },
5439
7646
  // MINT A DISCOUNT CODE against the merchant's chosen discount, mapped to
5440
7647
  // one lead — which is what lets an order that redeems it be attributed
5441
7648
  // back.
5442
- code: async ({ connection, context, step }, { adminToken, shopify } = {}) => {
7649
+ code: async ({ connection, context, step }, { adminToken, shopify = client } = {}) => {
5443
7650
  var _a;
5444
7651
  const discount = (_a = step.settings) == null ? void 0 : _a.discount;
5445
7652
  const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection.shop };
@@ -5485,7 +7692,7 @@ var shopify_default2 = {
5485
7692
  // customer at the store is a support ticket: the context may already
5486
7693
  // carry the id from an earlier step, the lead may already be linked from
5487
7694
  // an earlier run, and Shopify's own get-or-create settles the rest.
5488
- customer: async ({ connection, context }, { adminToken, read, shopify } = {}) => {
7695
+ customer: async ({ connection, context }, { adminToken, read, shopify = client } = {}) => {
5489
7696
  const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection.shop };
5490
7697
  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 };
5491
7698
  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 };
@@ -5535,6 +7742,30 @@ var shopify_default2 = {
5535
7742
  }]
5536
7743
  };
5537
7744
  },
7745
+ // HOW MANY ARE LEFT. Read at the moment a campaign's product list is
7746
+ // rendered rather than stored on the product, because stock is the one
7747
+ // product fact that is stale the instant it is written down.
7748
+ //
7749
+ // SUMMED HERE, not by the caller. Shopify answers per variant and every
7750
+ // caller wanted the total; the one that existed summed it inline, and
7751
+ // summing `Object.values()` over the raw map is how a cache wrapper's own
7752
+ // bookkeeping key got counted as a quantity.
7753
+ inventory: async ({ connection, context }, { adminToken, shopify = client } = {}) => {
7754
+ const productId = context == null ? void 0 : context.product;
7755
+ const request2 = { product: productId || null, shop: connection.shop };
7756
+ if (!productId) return { message: "No product id \u2014 nothing to count.", request: request2, result: { total: null }, skipped: true };
7757
+ const adminAccessToken = await adminToken();
7758
+ const byVariant = await shopify.admin.getProductInventory({
7759
+ adminAccessToken,
7760
+ domain: connection.shop,
7761
+ productId
7762
+ });
7763
+ return {
7764
+ message: "Inventory read.",
7765
+ request: request2,
7766
+ result: { total: Object.values(byVariant || {}).reduce((sum, quantity) => sum + quantity, 0) }
7767
+ };
7768
+ },
5538
7769
  // AN ORDER ARRIVED AT THE STORE. The largest hook in the family, because
5539
7770
  // attribution genuinely is: an order can reach Drawbridge two ways and
5540
7771
  // they bill differently.
@@ -5894,10 +8125,28 @@ var shopify_default2 = {
5894
8125
  //
5895
8126
  // The shell has already refused a missing or inactive Shopify connection,
5896
8127
  // so what is left is the two things only this hook can know are wrong.
5897
- product: async ({ connection, context, workflow }, { mintId, read } = {}) => {
8128
+ // A PRODUCT, IN THREE MOVES. Nested by operation rather than by three
8129
+ // slots in the closed vocabulary, the same shape inbound.process uses
8130
+ // for its topic table — they are one subject, and a vendor that syncs
8131
+ // products has to answer all three or none.
8132
+ //
8133
+ // record a webhook said a product changed: upsert the row and
8134
+ // queue the pull
8135
+ // sync pull the product from the storefront and write what it
8136
+ // says, including what it says by NOT answering
8137
+ // variants one page of variants, self-chaining
8138
+ //
8139
+ // `sync` and `variants` were 443 lines of drawbridge-sync's
8140
+ // queue/product.js — a shadow implementation of the step this manifest
8141
+ // already declared, importing three of the vendor's client modules from
8142
+ // a worker file.
8143
+ product: async ({ connection, context, settings, workflow }, { adminToken, mintId, read, shopify = client } = {}) => {
8144
+ const operation = (context == null ? void 0 : context.operation) || "record";
8145
+ if (operation === "sync") return syncProduct({ adminToken, connection, context, read, settings, shopify });
8146
+ if (operation === "variants") return syncVariants({ connection, context, read, settings, shopify });
5898
8147
  const request2 = {
5899
8148
  numericId: (context == null ? void 0 : context.id) || null,
5900
- organizationId: workflow.organization,
8149
+ organizationId: (workflow == null ? void 0 : workflow.organization) || null,
5901
8150
  title: (context == null ? void 0 : context.title) || null
5902
8151
  };
5903
8152
  if (!(context == null ? void 0 : context.id)) return { message: "Skipped \u2014 product webhook payload had no id.", request: request2, response: { skipped: true }, skipped: true };
@@ -5947,9 +8196,612 @@ var shopify_default2 = {
5947
8196
  }
5948
8197
  },
5949
8198
  contacts: { remove: false, sync: false },
5950
- // The embedded-app surface. Only a vendor whose merchants arrive from its
5951
- // own app store has one.
5952
- install: false,
8199
+ // THE EMBEDDED-APP SURFACE. Only a vendor whose merchants arrive from its
8200
+ // own app store has one, and these thirteen slots are the thirteen routes
8201
+ // that used to live in api/route/shopify-embedded.js.
8202
+ //
8203
+ // A HOOK DESCRIBES ITS WRITES and the shell performs them, so none of these
8204
+ // holds a controller — `read` is the controller's read methods and nothing
8205
+ // else. Where one REFUSES it throws with a status, and the route answers
8206
+ // what it said. The helpers they share are above the manifest.
8207
+ install: {
8208
+ account: {
8209
+ // ESTABLISH THE DURABLE MERCHANT-TO-STORE LINK. The breakout
8210
+ // authenticates the merchant once, top-level, and stashes their user
8211
+ // token in `install.token.save`; App Bridge has already proven shop
8212
+ // control by the time this runs.
8213
+ //
8214
+ // THE STASHED TOKEN IS THE TRUST ANCHOR, not merely any valid user
8215
+ // token: the presented one must BE this shop's one-shot handoff token,
8216
+ // unexpired, and an access or pat record — a refresh or oauth-state
8217
+ // token that happens to resolve to a user must not qualify, which is
8218
+ // the rule a session is held to in drawbridge-api's middleware.
8219
+ link: async ({ context }, { read } = {}) => {
8220
+ var _a;
8221
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8222
+ const token = context == null ? void 0 : context.token;
8223
+ if (!shop || !token) throw refusal("shop and token are required", 400);
8224
+ const now = /* @__PURE__ */ new Date();
8225
+ const record = await read.get({ collection: "shop", query: { shop } });
8226
+ const stashed = (record == null ? void 0 : record.linkToken) ? (_a = decrypt(record.linkToken)) == null ? void 0 : _a.token : null;
8227
+ const expired = !(record == null ? void 0 : record.linkTokenExpiresAt) || new Date(record.linkTokenExpiresAt) <= now;
8228
+ if (!stashed || expired || stashed !== token) throw refusal("Invalid or expired link token", 401);
8229
+ const granted = await read.get({
8230
+ collection: "token",
8231
+ query: {
8232
+ revoked: false,
8233
+ tokenHash: hashToken(token),
8234
+ type: { $in: [tokenTypes.access, tokenTypes.pat] }
8235
+ }
8236
+ });
8237
+ if (!(granted == null ? void 0 : granted.user) || granted.expiresAt && new Date(granted.expiresAt) <= now) {
8238
+ throw refusal("Invalid or expired link token", 401);
8239
+ }
8240
+ const switching = Boolean(record == null ? void 0 : record.user) && record.user !== granted.user;
8241
+ const connections2 = switching ? await read.aggregate({
8242
+ collection: "connection",
8243
+ pipeline: [
8244
+ { $match: { shop, slug: "shopify" } },
8245
+ { $project: { _id: 0, id: 1 } }
8246
+ ]
8247
+ }) : [];
8248
+ return {
8249
+ message: switching ? "Linked to a different Drawbridge account." : "Linked.",
8250
+ request: { shop },
8251
+ result: { connected: true, switched: switching },
8252
+ // ALL OR NONE. A half-done switch is a store linked to the new
8253
+ // account while the old account's connections still serve from it.
8254
+ transaction: true,
8255
+ writes: [
8256
+ ...(connections2 || []).map((connection) => ({
8257
+ collection: "connection",
8258
+ operation: "delete",
8259
+ query: { id: connection.id }
8260
+ })),
8261
+ {
8262
+ collection: "shop",
8263
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null, user: granted.user } },
8264
+ operation: "update",
8265
+ query: { shop }
8266
+ }
8267
+ ]
8268
+ };
8269
+ },
8270
+ // DISCONNECT THE ACCOUNT FROM THE STORE. Every org connection goes and
8271
+ // the durable link clears; the offline token and the shop record stay,
8272
+ // because the app is still installed and the merchant may link a
8273
+ // different account next.
8274
+ unlink: async ({ context }, { read } = {}) => {
8275
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8276
+ if (!shop) throw refusal("shop is required", 400);
8277
+ const connections2 = await read.aggregate({
8278
+ collection: "connection",
8279
+ pipeline: [
8280
+ { $match: { shop, slug: "shopify" } },
8281
+ { $project: { _id: 0, id: 1 } }
8282
+ ]
8283
+ });
8284
+ return {
8285
+ message: "Unlinked " + (connections2 || []).length + " connection(s).",
8286
+ request: { shop },
8287
+ result: { ok: true },
8288
+ transaction: true,
8289
+ writes: [
8290
+ ...(connections2 || []).map((connection) => ({
8291
+ collection: "connection",
8292
+ operation: "delete",
8293
+ query: { id: connection.id }
8294
+ })),
8295
+ {
8296
+ collection: "shop",
8297
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null, user: null } },
8298
+ operation: "update",
8299
+ query: { shop }
8300
+ }
8301
+ ]
8302
+ };
8303
+ }
8304
+ },
8305
+ organizations: {
8306
+ // BIND ONE ORGANIZATION TO THIS STORE. The longest slot here, and every
8307
+ // gate in it came from a line in the route it replaces.
8308
+ add: async ({ context }, { currencies, mintId, read, shopify = client } = {}) => {
8309
+ var _a, _b;
8310
+ const organization = context == null ? void 0 : context.organization;
8311
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8312
+ if (!shop) throw refusal("shop is required", 400);
8313
+ if (!organization) throw refusal("organization is required", 400);
8314
+ const record = await read.get({ collection: "shop", query: { shop } });
8315
+ if (!(record == null ? void 0 : record.user)) throw refusal("Account is not connected for this store", 409);
8316
+ const owned = await merchantOrganizations({ read, user: record.user });
8317
+ const org = (owned || []).find((entry) => entry.id === organization);
8318
+ if (!org) throw refusal("No access to this organization", 403);
8319
+ if (!CONNECTABLE_STATUSES.includes(org.billingStatus)) {
8320
+ throw refusal("This organization can't accept connections right now \u2014 check its billing status in the dashboard", 403);
8321
+ }
8322
+ if (org.connection && org.connection.shop !== shop) {
8323
+ throw refusal("This organization is already connected to another Shopify store", 409);
8324
+ }
8325
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
8326
+ if (!(settings == null ? void 0 : settings.accessToken)) {
8327
+ throw refusal("Store is not installed \u2014 open the app in the Shopify admin first", 409);
8328
+ }
8329
+ const plan = await storePlan({ record, shopify });
8330
+ if (plan.unavailable) throw refusal("Couldn't verify the store's plan \u2014 try again shortly", 502);
8331
+ if (!plan.active) throw refusal("Approve a plan before connecting organizations", 402);
8332
+ let storefront = null;
8333
+ if (!record.storefront) {
8334
+ try {
8335
+ const minted2 = await shopify.oauth.createStorefrontToken({
8336
+ adminAccessToken: settings.accessToken,
8337
+ shop
8338
+ });
8339
+ if (minted2) storefront = encrypt({ token: minted2 });
8340
+ } catch (_) {
8341
+ }
8342
+ }
8343
+ let currency = (record == null ? void 0 : record.currency) || null;
8344
+ let source = (record == null ? void 0 : record.source) || null;
8345
+ try {
8346
+ const shopData = await shopify.oauth.getShop({ adminAccessToken: settings.accessToken, shop });
8347
+ if (shopData) {
8348
+ currency = String(shopData.currency || "").toLowerCase() || null;
8349
+ source = { domain: shopData.myshopifyDomain, id: String(shopData.id), label: shopData.name };
8350
+ }
8351
+ } catch (_) {
8352
+ }
8353
+ if (currency && currencies && !currencies.includes(currency)) {
8354
+ throw refusal("This store settles in a currency we can't bill yet. Connect a store with a supported settlement currency.", 422);
8355
+ }
8356
+ const minted = ((_a = org.connection) == null ? void 0 : _a.id) ? null : mintId();
8357
+ const connectionId = ((_b = org.connection) == null ? void 0 : _b.id) || minted.id;
8358
+ return {
8359
+ message: "Connected " + org.name + " to " + shop + ".",
8360
+ request: { organization, shop },
8361
+ result: { ok: true },
8362
+ transaction: true,
8363
+ writes: [
8364
+ ...storefront ? [{
8365
+ collection: "shop",
8366
+ data: { $set: { storefront } },
8367
+ operation: "update",
8368
+ query: { shop }
8369
+ }] : [],
8370
+ {
8371
+ collection: "connection",
8372
+ data: {
8373
+ $set: {
8374
+ currency,
8375
+ errors: [],
8376
+ // The token of record lives on the shared `shop` row; this
8377
+ // is the pointer that satisfies the required `settings`
8378
+ // string, and `auth.install.shared` declares how to read it.
8379
+ settings: encrypt({ ref: "shop", shop }),
8380
+ shop,
8381
+ status: "pending",
8382
+ ...source && { source }
8383
+ },
8384
+ $setOnInsert: {
8385
+ ...minted && { _id: minted._id, id: minted.id },
8386
+ feature: "organization:connection:shopify",
8387
+ organization,
8388
+ slug: "shopify"
8389
+ }
8390
+ },
8391
+ operation: "update",
8392
+ options: { upsert: true },
8393
+ query: { organization, slug: "shopify" }
8394
+ },
8395
+ {
8396
+ collection: "organization",
8397
+ data: {
8398
+ // $addToSet UNCONDITIONALLY. The route this replaces only
8399
+ // registered the refs when the upsert INSERTED, which meant an
8400
+ // org whose refs had drifted stayed drifted through every
8401
+ // re-link. Adding a member that is already there is a no-op,
8402
+ // so doing it every time costs nothing and repairs the drift.
8403
+ $addToSet: {
8404
+ "connections.groups": "ecommerce",
8405
+ "connections.ids": connectionId,
8406
+ "connections.keys": "shopify"
8407
+ },
8408
+ $set: { billingProvider: "shopify" }
8409
+ },
8410
+ operation: "update",
8411
+ query: { id: organization }
8412
+ }
8413
+ ]
8414
+ };
8415
+ },
8416
+ // WHAT THIS STORE CAN SEE: the linked merchant's organizations, the
8417
+ // store's live plan, and the products the merchant has to act on.
8418
+ //
8419
+ // AN ORG CONNECTED TO A DIFFERENT STORE IS OMITTED ENTIRELY, because
8420
+ // `add` would refuse it — a list that offers what the next call rejects
8421
+ // is worse than a shorter one.
8422
+ list: async ({ context }, { conversionRate, planTitle, read, shopify = client } = {}) => {
8423
+ var _a;
8424
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8425
+ if (!shop) throw refusal("shop is required", 400);
8426
+ const record = await read.get({ collection: "shop", query: { shop } });
8427
+ if (!(record == null ? void 0 : record.user)) {
8428
+ return {
8429
+ message: "No account linked to this store.",
8430
+ request: { shop },
8431
+ result: {
8432
+ account: null,
8433
+ connected: false,
8434
+ organizations: [],
8435
+ plan: { active: false, name: null },
8436
+ unavailableProducts: [],
8437
+ unavailableProductsTotal: 0
8438
+ }
8439
+ };
8440
+ }
8441
+ const owned = await merchantOrganizations({ read, user: record.user });
8442
+ const organizations = (owned || []).filter((org) => !org.connection || org.connection.shop === shop).map((org) => {
8443
+ var _a2;
8444
+ return {
8445
+ // The org's OWN billing status decides whether `add` accepts it.
8446
+ // Sent up so the app can disable Connect and name the reason
8447
+ // rather than letting the merchant click into a 403 —
8448
+ // listed-but-blocked beats hidden, because an org vanishing from
8449
+ // the list is indistinguishable from a bug.
8450
+ billingStatus: org.billingStatus || null,
8451
+ connectable: CONNECTABLE_STATUSES.includes(org.billingStatus),
8452
+ connected: Boolean(org.connection),
8453
+ conversion: conversionRate(org.subscription),
8454
+ id: org.id,
8455
+ name: org.name,
8456
+ plan: planTitle(org.subscription),
8457
+ status: ((_a2 = org.connection) == null ? void 0 : _a2.status) || null
8458
+ };
8459
+ });
8460
+ const connections2 = (owned || []).filter((org) => {
8461
+ var _a2;
8462
+ return ((_a2 = org.connection) == null ? void 0 : _a2.shop) === shop && org.connection.id;
8463
+ }).map((org) => org.connection.id);
8464
+ const [account, plan, unavailable] = await Promise.all([
8465
+ read.get({ collection: "user", query: { id: record.user } }),
8466
+ storePlan({ record, shopify }),
8467
+ connections2.length ? read.aggregate({
8468
+ collection: "product",
8469
+ pipeline: [
8470
+ { $match: { connections: { $in: connections2 }, "source.domain": shop, status: "inactive" } },
8471
+ // $facet so the app can name the first 25 AND report a
8472
+ // truthful total: listing 25 of 40 under "25 products need
8473
+ // attention" would understate the problem.
8474
+ {
8475
+ $facet: {
8476
+ items: [{ $sort: { title: 1 } }, { $limit: 25 }, { $project: { _id: 0, id: 1, title: 1 } }],
8477
+ total: [{ $count: "count" }]
8478
+ }
8479
+ }
8480
+ ]
8481
+ }) : []
8482
+ ]);
8483
+ const facet = (unavailable || [])[0] || {};
8484
+ if (plan.active && plan.metered !== true) {
8485
+ const stamped = await read.aggregate({
8486
+ collection: "connection",
8487
+ pipeline: [
8488
+ { $match: { shop, slug: "shopify" } },
8489
+ { $project: { _id: 0, "source.metered": 1 } }
8490
+ ]
8491
+ });
8492
+ const verdicts = (stamped || []).map((row2) => {
8493
+ var _a2;
8494
+ return (_a2 = row2 == null ? void 0 : row2.source) == null ? void 0 : _a2.metered;
8495
+ });
8496
+ if (verdicts.some((verdict) => typeof verdict === "string")) plan.metered = true;
8497
+ else if (verdicts.some((verdict) => verdict === null)) plan.metered = false;
8498
+ }
8499
+ return {
8500
+ message: organizations.length + " organization(s) for this store.",
8501
+ request: { shop },
8502
+ result: {
8503
+ account: { email: (account == null ? void 0 : account.email) || null },
8504
+ connected: true,
8505
+ organizations,
8506
+ plan,
8507
+ unavailableProducts: (facet.items || []).map((product) => ({
8508
+ id: product.id,
8509
+ title: product.title || "Untitled product"
8510
+ })),
8511
+ // The total can exceed the 25 listed above, and has to.
8512
+ unavailableProductsTotal: ((_a = (facet.total || [])[0]) == null ? void 0 : _a.count) || 0
8513
+ }
8514
+ };
8515
+ },
8516
+ // DISCONNECT ONE ORGANIZATION. The connection is deleted and nothing
8517
+ // else: every dependent — products, ads, steps, workflows, and the org's
8518
+ // own connection refs — is torn down by drawbridge-sync's connection
8519
+ // change stream. The shared token and the other orgs are untouched.
8520
+ remove: async ({ context }, { read } = {}) => {
8521
+ const organization = context == null ? void 0 : context.organization;
8522
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8523
+ if (!shop) throw refusal("shop is required", 400);
8524
+ if (!organization) throw refusal("organization is required", 400);
8525
+ const record = await read.get({ collection: "shop", query: { shop } });
8526
+ if (!(record == null ? void 0 : record.user)) throw refusal("Account is not connected for this store", 409);
8527
+ const owned = await merchantOrganizations({ read, user: record.user });
8528
+ if (!(owned || []).some((entry) => entry.id === organization)) {
8529
+ throw refusal("No access to this organization", 403);
8530
+ }
8531
+ const connection = await read.get({
8532
+ collection: "connection",
8533
+ query: { organization, shop, slug: "shopify" }
8534
+ });
8535
+ if (!connection) throw refusal("No connection to remove", 404);
8536
+ return {
8537
+ message: "Disconnected.",
8538
+ request: { organization, shop },
8539
+ result: { ok: true },
8540
+ writes: [{ collection: "connection", operation: "delete", query: { id: connection.id } }]
8541
+ };
8542
+ }
8543
+ },
8544
+ plan: {
8545
+ // RELEASE EVERY ACTIVE APPROVAL. The App Home then re-checks the plan
8546
+ // and falls back to "Choose a plan".
8547
+ cancel: ({ context }, { read, shopify = client } = {}) => releaseApprovals({ context, read, shopify }),
8548
+ // ONE ATTRIBUTED ORDER'S USAGE CHARGE. Enqueued per conversion by the
8549
+ // order step and run on a retrying queue, so this may be called
8550
+ // several times for one order — which is safe because the idempotency
8551
+ // key is PERMANENT for billing events and Shopify settles the repeat.
8552
+ //
8553
+ // THE HANDLE IS CHECKED AGAINST THE MANIFEST'S OWN DECLARATION, which
8554
+ // is a real strengthening of what it replaced: drawbridge-sync compared
8555
+ // the job's `handle` against the job's `transaction` — two fields from
8556
+ // the same enqueuer, so a drifted enqueuer agreed with itself. The
8557
+ // handle is the one string that decides whether the event bills at all,
8558
+ // and this is the file that publishes it.
8559
+ //
8560
+ // REFUSE BEFORE SENDING, because sending burns the order's PERMANENT
8561
+ // idempotency key on an event that misclassifies or mistraces. The
8562
+ // throw rides the queue's normal retry path and the abandoned-job alert
8563
+ // pages on exhaustion.
8564
+ //
8565
+ // DELIBERATELY NO TIMESTAMP. sendAppEvent defaults to the SEND time,
8566
+ // which is always inside the merchant's current billing cycle at the
8567
+ // moment of sending and so can never hit PERIOD_CLOSED. Pinning the
8568
+ // purchase time reads more correct and is strictly worse: a retry
8569
+ // backoff crossing a cycle boundary would carry a closed-cycle
8570
+ // timestamp, Shopify would 202-accept, silently drop it, and the
8571
+ // commission would be lost. Send-time's worst case is benign — the
8572
+ // charge lands in the next cycle, but it lands.
8573
+ charge: async ({ clientId, clientSecret, context, manifest }, { shopify = client } = {}) => {
8574
+ const { idempotencyKey, order, orderId, rate, revision, shopId, timestamp, transaction, value } = context || {};
8575
+ const handle = (context == null ? void 0 : context.handle) || manifest.auth.install.billing.handle;
8576
+ if (!transaction || !String(transaction).startsWith(handle + ".")) {
8577
+ throw new Error("shopify.usage.billing.handle.mismatch on order " + orderId + ": transaction " + (transaction || "null") + " does not carry handle " + handle + " \u2014 refusing to send");
8578
+ }
8579
+ await shopify.billing.sendAppEvent({
8580
+ clientId,
8581
+ clientSecret,
8582
+ eventHandle: handle,
8583
+ idempotencyKey,
8584
+ // The Shopify-side event record names the order that produced it.
8585
+ reference: transaction,
8586
+ // OPERATOR-ONLY, BOTH OF THEM, and absent on every automatic
8587
+ // send. `revision` suffixes the idempotency key, which is what
8588
+ // makes a second attempt possible once a key has been consumed;
8589
+ // the encoding is owned by sendAppEvent so no caller builds keys
8590
+ // itself. `timestamp` pins the PURCHASE time, which the automatic
8591
+ // path must never do — see the note above — and the recovery
8592
+ // migration must, because it is resending orders from a closed
8593
+ // window and bounds its own run to the merchant's current cycle.
8594
+ ...revision && { revision },
8595
+ ...timestamp && { timestamp },
8596
+ shopId,
8597
+ value
8598
+ });
8599
+ return {
8600
+ message: "Usage charge sent for order " + orderId + ".",
8601
+ request: { order: order || null, orderId: orderId || null, shopId: shopId || null, value },
8602
+ result: { transaction: String(transaction) },
8603
+ // TRACEABILITY. The App Events API returns no event id, so the
8604
+ // trace key into Shopify's event logs is the transaction id the
8605
+ // commerce.order hook minted and this sent as `reference`.
8606
+ // `amount` is the per-order usage value in cents, mirroring the
8607
+ // Stripe path's marker.
8608
+ ...order && { writes: [{
8609
+ collection: "order",
8610
+ data: {
8611
+ $set: {
8612
+ billed: {
8613
+ amount: value,
8614
+ date: /* @__PURE__ */ new Date(),
8615
+ rate: rate || 0,
8616
+ transaction: String(transaction)
8617
+ }
8618
+ }
8619
+ },
8620
+ operation: "update",
8621
+ query: { id: order }
8622
+ }] }
8623
+ };
8624
+ },
8625
+ // RESELECT, NOT CANCEL. The same mechanics — the current approval has to
8626
+ // be released before the pricing page will offer the plan again — but
8627
+ // the intent is a thirty-second round trip rather than a departure.
8628
+ //
8629
+ // `mark` IS A DECLARED CAPABILITY, and this is the only slot here that
8630
+ // needs one. The marker has to be persisted BEFORE the approval is
8631
+ // released: it is what tells sync's CANCELLED handler to hold the pause
8632
+ // — no connection error, no owner email — and start a timed recheck that
8633
+ // pauses honestly if the merchant abandons. A described write lands
8634
+ // after the hook returns, which is after the cancel, and a marker
8635
+ // written then can race the very webhook it exists to soften. Same
8636
+ // precedent as `resolveContact`: the one write a description cannot
8637
+ // carry.
8638
+ reselect: async ({ context }, { mark, read, shopify = client } = {}) => {
8639
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8640
+ if (!shop) throw refusal("shop is required", 400);
8641
+ await mark({ shop });
8642
+ return releaseApprovals({ context, read, shopify });
8643
+ },
8644
+ // IS THIS STORE'S ORDER BILLING ACTUALLY METERED? Not a merchant
8645
+ // action — the other two slots here are — but the same subject, and
8646
+ // the reason it is a declared hook rather than a helper is that the
8647
+ // answer was being derived in two places: `lifecycle.health` below,
8648
+ // and drawbridge-sync's app_subscriptions/update handler, whose copy
8649
+ // stated in its own comment that it matched this one and did not.
8650
+ //
8651
+ // THREE ANSWERS, and the caller must keep them apart:
8652
+ //
8653
+ // a string PROVEN. The charge id or usage line id, stamped on
8654
+ // the connection as the evidence.
8655
+ // null PROBED, and nothing is accruing.
8656
+ // undefined NO VERDICT — the probe could not run. `probed` says
8657
+ // which, because undefined does not survive JSON.
8658
+ verify: async ({ context }, { adminToken, read, shopify = client } = {}) => {
8659
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8660
+ if (!shop) throw refusal("shop is required", 400);
8661
+ const adminAccessToken = await adminToken();
8662
+ if (!adminAccessToken) {
8663
+ return { message: "No admin token for this store \u2014 no verdict.", request: { shop }, result: { metered: null, probed: false }, skipped: true };
8664
+ }
8665
+ const partnerRow = (read == null ? void 0 : read.get) ? await read.get({ collection: "provider", query: { slug: "shopify" } }) : null;
8666
+ const partner = (partnerRow == null ? void 0 : partnerRow.settings) ? decrypt(partnerRow.settings) : {};
8667
+ const { ledger, metered } = await meterVerdict({
8668
+ adminAccessToken,
8669
+ ledgerFloor: new Date(Date.now() - LEDGER_WINDOW_MS),
8670
+ partner,
8671
+ shop,
8672
+ shopId: (context == null ? void 0 : context.shopId) || null,
8673
+ shopify
8674
+ });
8675
+ return {
8676
+ message: typeof metered === "string" ? "Billing is metered." : "No meter evidence for this store.",
8677
+ request: { shop },
8678
+ // `probed` is the LEDGER, not the call: a store whose Partner
8679
+ // credentials are absent was not asked, and reporting that as
8680
+ // "probed, nothing accruing" would stamp an unmetered verdict on
8681
+ // a store nobody looked at.
8682
+ result: { metered: metered ?? null, probed: ledger || typeof metered === "string" }
8683
+ };
8684
+ }
8685
+ },
8686
+ // THE EMBEDDED APP'S SESSION STORE. The @shopify/shopify-app library
8687
+ // persists the offline session on token exchange and refresh; it lives
8688
+ // encrypted on the shared `shop` record, which is the same row every
8689
+ // organization's connection to this store points at.
8690
+ session: {
8691
+ // SOFT-CLEAR, NEVER A DELETE. The library calls this on session
8692
+ // invalidation and not only on uninstall, so hard-deleting the record
8693
+ // would orphan every org connection pointing at it — token resolution
8694
+ // silently nulls — and destroy the durable account link and the
8695
+ // storefront token with it. The next embedded load re-runs token
8696
+ // exchange. The full record delete belongs to the uninstall webhook.
8697
+ clear: async ({ context }) => {
8698
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8699
+ if (!shop) throw refusal("shop is required", 400);
8700
+ return {
8701
+ message: "Session cleared.",
8702
+ request: { shop },
8703
+ result: { ok: true },
8704
+ writes: [{
8705
+ collection: "shop",
8706
+ data: { $set: { settings: null } },
8707
+ operation: "update",
8708
+ query: { shop }
8709
+ }]
8710
+ };
8711
+ },
8712
+ read: async ({ context }, { read } = {}) => {
8713
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8714
+ if (!shop) throw refusal("shop is required", 400);
8715
+ const record = await read.get({ collection: "shop", query: { shop } });
8716
+ if (!(record == null ? void 0 : record.settings)) throw refusal("No session for this store", 404);
8717
+ return {
8718
+ message: "Session read.",
8719
+ request: { shop },
8720
+ result: { session: decrypt(record.settings) }
8721
+ };
8722
+ },
8723
+ save: async ({ context }) => {
8724
+ const session = context == null ? void 0 : context.session;
8725
+ const shop = sanitizeDomain(session == null ? void 0 : session.shop);
8726
+ if (!shop || !(session == null ? void 0 : session.accessToken)) throw refusal("session.shop and session.accessToken are required", 400);
8727
+ return {
8728
+ message: "Session saved.",
8729
+ request: { shop },
8730
+ result: { ok: true },
8731
+ writes: [{
8732
+ collection: "shop",
8733
+ data: {
8734
+ $set: { settings: encrypt(session), shop },
8735
+ $setOnInsert: { status: "pending" }
8736
+ },
8737
+ operation: "update",
8738
+ options: { upsert: true },
8739
+ query: { shop }
8740
+ }]
8741
+ };
8742
+ }
8743
+ },
8744
+ // THE LINK-TOKEN HANDOFF. The breakout callback runs top-level and can set
8745
+ // a first-party cookie; the embedded App Home cannot read that cookie from
8746
+ // inside the Shopify admin iframe. So the callback stashes the merchant's
8747
+ // user token here keyed by shop, and App Home reads it once and clears it.
8748
+ //
8749
+ // DURABLE RATHER THAN IN REDIS: a restart must not strand a merchant
8750
+ // mid-handoff. Short-lived and encrypted.
8751
+ token: {
8752
+ clear: async ({ context }) => {
8753
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8754
+ if (!shop) throw refusal("shop is required", 400);
8755
+ return {
8756
+ message: "Link token cleared.",
8757
+ request: { shop },
8758
+ result: { ok: true },
8759
+ writes: [{
8760
+ collection: "shop",
8761
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null } },
8762
+ operation: "update",
8763
+ query: { shop }
8764
+ }]
8765
+ };
8766
+ },
8767
+ read: async ({ context }, { read } = {}) => {
8768
+ var _a;
8769
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8770
+ if (!shop) throw refusal("shop is required", 400);
8771
+ const record = await read.get({ collection: "shop", query: { shop } });
8772
+ const expiresAt = (record == null ? void 0 : record.linkTokenExpiresAt) ? new Date(record.linkTokenExpiresAt) : null;
8773
+ if (!(record == null ? void 0 : record.linkToken) || !expiresAt || expiresAt <= /* @__PURE__ */ new Date()) {
8774
+ throw refusal("No link token for this store", 404);
8775
+ }
8776
+ return {
8777
+ message: "Link token read.",
8778
+ request: { shop },
8779
+ result: { token: ((_a = decrypt(record.linkToken)) == null ? void 0 : _a.token) ?? null }
8780
+ };
8781
+ },
8782
+ save: async ({ context }) => {
8783
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8784
+ const token = context == null ? void 0 : context.token;
8785
+ if (!shop || !token) throw refusal("shop and token are required", 400);
8786
+ return {
8787
+ message: "Link token saved.",
8788
+ request: { shop },
8789
+ result: { ok: true },
8790
+ writes: [{
8791
+ collection: "shop",
8792
+ data: {
8793
+ $set: {
8794
+ linkToken: encrypt({ token }),
8795
+ linkTokenExpiresAt: new Date(Date.now() + LINK_TOKEN_TTL_MS)
8796
+ }
8797
+ },
8798
+ operation: "update",
8799
+ query: { shop }
8800
+ }]
8801
+ };
8802
+ }
8803
+ }
8804
+ },
5953
8805
  // Drawbridge sends its own notification email and SMS — see the private
5954
8806
  // `drawbridge` manifest. A vendor answering these would be a second sender,
5955
8807
  // which is the arrangement the platform sender replaced.
@@ -6011,8 +8863,8 @@ var shopify_default2 = {
6011
8863
  // access token still works, reconciles the scopes the store granted
6012
8864
  // against the ones the app now needs, and queues a webhook
6013
8865
  // reconciliation.
6014
- health: async ({ connection, workflow }, { adminToken, logger, read, reconcileScopes, resolveSettings, rotateToken, shopify } = {}) => {
6015
- var _a, _b, _c, _d, _e, _f;
8866
+ health: async ({ connection, workflow }, { adminToken, logger, read, reconcileScopes, resolveSettings, rotateToken, shopify = client } = {}) => {
8867
+ var _a, _b, _c, _d;
6016
8868
  const request2 = {
6017
8869
  connectionId: workflow.connection,
6018
8870
  organizationId: workflow.organization,
@@ -6049,33 +8901,26 @@ var shopify_default2 = {
6049
8901
  shopCurrency = String(shopData.currency || "").toLowerCase() || null;
6050
8902
  sourceRepaired = true;
6051
8903
  }
6052
- const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
6053
- adminAccessToken,
6054
- domain: connection.shop
6055
- });
6056
- const usageLine = (_a = subscriptions.find((subscription) => subscription.usageLineItemId)) == null ? void 0 : _a.usageLineItemId;
6057
- if (usageLine) metered = usageLine;
6058
8904
  const partnerRow = (read == null ? void 0 : read.get) ? await read.get({ collection: "provider", query: { slug: "shopify" } }) : null;
6059
8905
  const partner = (partnerRow == null ? void 0 : partnerRow.settings) ? decrypt(partnerRow.settings) : {};
6060
- if (partner.partnerToken && partner.partnerOrgId && partner.partnerAppId && (source == null ? void 0 : source.id) && ((_b = shopify.partner) == null ? void 0 : _b.getUsageChargeEvents)) {
6061
- const ledgerFloor = new Date(Date.now() - 30 * 24 * 60 * 60 * 1e3);
6062
- const accruals = await shopify.partner.getUsageChargeEvents({
6063
- appId: "gid://shopify/App/" + partner.partnerAppId,
6064
- first: 10,
6065
- occurredAtMin: ledgerFloor.toISOString(),
6066
- organizationId: partner.partnerOrgId,
6067
- partnerToken: partner.partnerToken,
6068
- shopId: "gid://shopify/Shop/" + source.id
6069
- });
6070
- const boundaries = accruals.filter((event) => event.occurredAt).sort((a, b) => new Date(a.occurredAt) - new Date(b.occurredAt));
6071
- const accrued = [...boundaries].reverse().find((event) => Number(event.usageQuantity) > 0);
6072
- if (accrued) metered = String(accrued.chargeId || accrued.id);
6073
- const stampedAt = (_c = boundaries.find(
8906
+ const ledgerFloor = new Date(Date.now() - LEDGER_WINDOW_MS);
8907
+ const verdict = await meterVerdict({
8908
+ adminAccessToken,
8909
+ ledgerFloor,
8910
+ partner,
8911
+ shop: connection.shop,
8912
+ shopId: source == null ? void 0 : source.id,
8913
+ shopify
8914
+ });
8915
+ if (verdict.metered !== void 0) metered = verdict.metered;
8916
+ const { boundaries } = verdict;
8917
+ if (boundaries.length) {
8918
+ const stampedAt = (_a = boundaries.find(
6074
8919
  (event) => {
6075
8920
  var _a2;
6076
8921
  return String(event.chargeId || event.id) === String(((_a2 = connection.source) == null ? void 0 : _a2.metered) || "");
6077
8922
  }
6078
- )) == null ? void 0 : _c.occurredAt;
8923
+ )) == null ? void 0 : _a.occurredAt;
6079
8924
  reconciliation = [];
6080
8925
  let windowStart = ledgerFloor;
6081
8926
  for (const boundary of boundaries) {
@@ -6125,7 +8970,7 @@ var shopify_default2 = {
6125
8970
  }
6126
8971
  });
6127
8972
  } else {
6128
- (_d = logger == null ? void 0 : logger.error) == null ? void 0 : _d.call(logger, new Error(
8973
+ (_b = logger == null ? void 0 : logger.error) == null ? void 0 : _b.call(logger, new Error(
6129
8974
  "shopify.usage.reconciliation.mismatch on shop " + connection.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"
6130
8975
  ), {
6131
8976
  extra: {
@@ -6144,13 +8989,13 @@ var shopify_default2 = {
6144
8989
  }
6145
8990
  } catch (probeError) {
6146
8991
  billingProbeFailed = true;
6147
- (_e = logger == null ? void 0 : logger.warn) == null ? void 0 : _e.call(logger, "shopify.health.billing.probe.failed", {
8992
+ (_c = logger == null ? void 0 : logger.warn) == null ? void 0 : _c.call(logger, "shopify.health.billing.probe.failed", {
6148
8993
  connectionId: connection.id,
6149
8994
  message: probeError == null ? void 0 : probeError.message,
6150
8995
  shop: connection.shop
6151
8996
  });
6152
8997
  }
6153
- if (sourceRepaired || metered !== void 0 && metered !== (((_f = connection.source) == null ? void 0 : _f.metered) ?? void 0)) {
8998
+ if (sourceRepaired || metered !== void 0 && metered !== (((_d = connection.source) == null ? void 0 : _d.metered) ?? void 0)) {
6154
8999
  writes.push({
6155
9000
  collection: "connection",
6156
9001
  data: {
@@ -6285,13 +9130,13 @@ var shopify_default2 = {
6285
9130
  // They are the same two questions every other vendor answers through
6286
9131
  // resources.*, so they answer them the same way now.
6287
9132
  //
6288
- // `shopify` is INJECTED: this package cannot import @drawbridge/shopify,
9133
+ // `shopify` DEFAULTS to the client this file imports; nothing injects it,
6289
9134
  // which depends on it. What arrives is the SDK's pure HTTP namespaces
6290
9135
  // and nothing else — no controller, no collection access. Resolving the
6291
9136
  // credential is the caller's job because it is Drawbridge's job: the
6292
9137
  // admin token refreshes and writes itself back, which is service work,
6293
9138
  // not vendor work.
6294
- products: async ({ cursor, limit = 100, search, settings, sort }, { shopify } = {}) => {
9139
+ products: async ({ cursor, limit = 100, search, settings, sort }, { shopify = client } = {}) => {
6295
9140
  var _a, _b, _c, _d;
6296
9141
  const products = await shopify.storefront.getProducts({
6297
9142
  cursor,
@@ -6313,7 +9158,7 @@ var shopify_default2 = {
6313
9158
  }
6314
9159
  };
6315
9160
  },
6316
- promotions: async ({ cursor, limit = 100, search, settings }, { shopify } = {}) => {
9161
+ promotions: async ({ cursor, limit = 100, search, settings }, { shopify = client } = {}) => {
6317
9162
  var _a, _b;
6318
9163
  const discounts = await shopify.admin.getDiscounts({
6319
9164
  adminAccessToken: settings == null ? void 0 : settings.adminAccessToken,
@@ -6818,14 +9663,15 @@ var webhook_default = {
6818
9663
  "Drawbridge can POST event payloads to your endpoint as activity happens in your account, so your own systems can react to it.",
6819
9664
  "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."
6820
9665
  ],
6821
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
6822
- // The dashboard already carries generic reasons for every way an
6823
- // authorization can fail declined, expired state, a vendor we are not set
6824
- // up for and a sentence here is an ADDITION to those, for a vendor whose
6825
- // failures need saying differently. This one's do not.
9666
+ // THERE IS NO CONSENT SCREEN TO FAIL. Connecting mints a signing secret;
9667
+ // nothing is authorized against a third party, so neither `denied` nor
9668
+ // `invalid` has a state it could describe. The failures this connection
9669
+ // really has are at DELIVERY a merchant's endpoint refusing a POST and
9670
+ // those reach them through the connection's own errors rather than through
9671
+ // connect copy.
6826
9672
  //
6827
- // Answered rather than omitted, because `errors` existed on two of six
6828
- // manifests and there was no way to tell "nothing to add" from "nobody
9673
+ // `false` is the recorded decision, not silence: `errors` existed on two of
9674
+ // six manifests and there was no way to tell "nothing to add" from "nobody
6829
9675
  // wrote it".
6830
9676
  errors: false,
6831
9677
  excerpt: "Sign outgoing webhook payloads with an HMAC secret to verify authenticity.",
@@ -7804,7 +10650,7 @@ var hookSupport = (name) => ({
7804
10650
  });
7805
10651
  var connectFields = (slug2) => {
7806
10652
  var _a;
7807
- return (((_a = connections[slug2]) == null ? void 0 : _a.fields) || []).map(({ copy, from, hook, input, key, label, message, options, placeholder, redact, required, search }) => ({
10653
+ return (((_a = connections[slug2]) == null ? void 0 : _a.fields) || []).map(({ copy, from, hook, input, key, label, message, options, placeholder, redact, required: required2, search }) => ({
7808
10654
  ...copy && { copy: true },
7809
10655
  ...hook && { hook },
7810
10656
  ...from && { from },
@@ -7817,7 +10663,7 @@ var connectFields = (slug2) => {
7817
10663
  // Declared false only where the vendor cannot filter, so a picker does not
7818
10664
  // offer a search box that quietly searches one page.
7819
10665
  ...search === false && { search: false },
7820
- required: Boolean(required),
10666
+ required: Boolean(required2),
7821
10667
  // A UI hint, not a leak: the form uses it to stop requiring the field once
7822
10668
  // the connection exists, and to say "leave blank to keep" — because the GET
7823
10669
  // response deliberately never returns the stored value.
@@ -7977,6 +10823,7 @@ var resolveConnection = (item, data, env = {}) => {
7977
10823
  buildVendor,
7978
10824
  catalogConnections,
7979
10825
  connectFields,
10826
+ connectionSettings,
7980
10827
  connectionSteps,
7981
10828
  connections,
7982
10829
  consentUrl,
@@ -7986,10 +10833,12 @@ var resolveConnection = (item, data, env = {}) => {
7986
10833
  isStale,
7987
10834
  isStatus,
7988
10835
  mergeSettings,
10836
+ perform,
7989
10837
  pkcePair,
7990
10838
  projectConnection,
7991
10839
  publicConnectionKeys,
7992
10840
  publicSettingsBySlug,
10841
+ reconcileConnectionScopes,
7993
10842
  redactSettings,
7994
10843
  resolveConnection,
7995
10844
  runHook,