@drawbridge/drawbridge-utils 0.0.116 → 0.0.118

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.
@@ -0,0 +1,3291 @@
1
+ // lib/connections/contract.js
2
+ var HOOKS = Object.freeze({
3
+ // Proving and holding the credential.
4
+ auth: Object.freeze([
5
+ // Accept what the merchant supplied — a form submission or an OAuth
6
+ // callback — and store what is needed to call the vendor later.
7
+ "connect",
8
+ // Is the stored credential still good? Answered by the cheapest real call
9
+ // the vendor offers, never by inspecting what we stored: a key that was
10
+ // revoked at the vendor still looks perfect in our database.
11
+ "probe",
12
+ // Which permissions we asked for and no longer hold. Distinct from probe:
13
+ // the credential can be valid and the grant still be too narrow.
14
+ "scopes",
15
+ // Revoke at the vendor and drop what we hold.
16
+ "disconnect",
17
+ // MINT A TOKEN — from a consent code, or from a stored refresh token. Both
18
+ // are the same POST, so they are one hook.
19
+ //
20
+ // The default body is authToken() in oauth.js and most vendors point
21
+ // straight at it. It is a hook rather than a declared flag because the
22
+ // vendors that differ, differ in ways config cannot express: Klaviyo needs
23
+ // HTTP Basic where others want body fields, and Mailchimp cannot use the
24
+ // token it receives until a second call tells it which data centre the
25
+ // account is behind.
26
+ "token"
27
+ ]),
28
+ // What happens around connecting and disconnecting, beyond the credential.
29
+ lifecycle: Object.freeze([
30
+ // KEEP ACCESS WORKING. Rotate a credential before its window closes, prove
31
+ // it still works, and reconcile whatever the vendor has changed underneath
32
+ // — scopes, webhooks. Distinct from auth.probe, which only answers "is this
33
+ // still good": this one FIXES what it can and reports what it cannot.
34
+ "health",
35
+ // Post-connect setup: register the vendor's webhooks, create the system
36
+ // workflows that describe them.
37
+ "register",
38
+ // Re-pull vendor state we mirror, after a reconnect or on a schedule.
39
+ "rehydrate",
40
+ // Undo `register` — deregister webhooks, release anything reserved.
41
+ "cleanup"
42
+ ]),
43
+ // Receiving from the vendor.
44
+ //
45
+ // Split across TWO SERVICES, and the split is the point. `verify` and `event`
46
+ // and `receive` run in drawbridge-webhooks against the vendor's open
47
+ // connection, where the budget is whatever that vendor's timeout is —
48
+ // Shopify's is about five seconds, and missing it means they retry and the
49
+ // delivery is buffered twice. `process` runs in drawbridge-sync off the
50
+ // buffer, where it can take as long as it needs and retry without the vendor
51
+ // ever knowing.
52
+ //
53
+ // One hook spanning that seam would hide it, and the thing it hides is the
54
+ // one most likely to bite: slow work written on the receiving side turns
55
+ // into duplicate deliveries.
56
+ inbound: Object.freeze([
57
+ // Prove the request came from the vendor, AND return the payload it
58
+ // carries. One hook rather than two because for some vendors they are
59
+ // genuinely one operation: a JWT-bodied webhook (Kinde) cannot be decoded
60
+ // into anything trustworthy without verifying it first, and a decode that
61
+ // runs before the signature check is exactly the bug this shape prevents.
62
+ //
63
+ // So the raw bytes stop here. Everything downstream receives the payload
64
+ // this returned, which means nothing downstream can act on unverified
65
+ // data even by mistake.
66
+ //
67
+ // It is also where a request gets refused for any other reason — an event
68
+ // outside the allowlist, a connection in the wrong state. Anything that
69
+ // can reject belongs here, so the route holds no rules of its own.
70
+ "verify",
71
+ // Name the event, from wherever this vendor puts it. A header for
72
+ // Shopify, the route itself for Twilio, a claim in the payload for a
73
+ // JWT-bodied vendor.
74
+ "event",
75
+ // What to buffer and what to answer RIGHT NOW, while the vendor waits.
76
+ // Thin by obligation. Most vendors only shape a buffer doc here; one that
77
+ // must reply with content (Twilio answers HELP inline with TwiML, which
78
+ // carriers require) returns that too.
79
+ "receive",
80
+ // Do the work the event implies. Runs in drawbridge-sync, off the buffer.
81
+ //
82
+ // DECLARED here, IMPLEMENTED there — the same split as the step handlers,
83
+ // and for the same reason: this half needs controllers, queues and vendor
84
+ // SDKs, and putting those behind a published package makes every consumer
85
+ // carry them. The declaration is what proves the implementation exists.
86
+ "process"
87
+ ]),
88
+ // WHAT A WORKFLOW STEP DOES, as a verb like any other. Step handlers used to
89
+ // live in drawbridge-sync keyed by step type, which meant a vendor's logic sat
90
+ // in a repo the vendor file could not see — the split this whole exercise
91
+ // exists to close.
92
+ //
93
+ // A `steps` entry points at one of these; the step says when it runs and what
94
+ // it costs, the hook does the work.
95
+ contacts: Object.freeze([
96
+ // Forget a contact at the vendor. Distinct from suppression, which keeps the
97
+ // record and marks it unsubscribed: this is deletion, for account closure.
98
+ "remove",
99
+ // Push one contact into the audience the merchant chose, honouring
100
+ // suppression rather than omitting an opted-out person — omission lets them
101
+ // quietly reappear on the next sync.
102
+ "sync"
103
+ ]),
104
+ commerce: Object.freeze([
105
+ // Mint a discount code against this merchant's store, mapped to one lead.
106
+ "code",
107
+ // Create the buyer at the vendor, so an order can be attributed to them.
108
+ "customer",
109
+ // An order arrived at the vendor: attribute it, record it, update totals.
110
+ "order",
111
+ // Pull product data across on a vendor update.
112
+ "product"
113
+ ]),
114
+ // WHAT DRAWBRIDGE ITSELF DOES. These are not a third party's verbs — nobody
115
+ // connects an account to send email through Drawbridge — but they are steps a
116
+ // workflow runs, and a step points at a hook. So they live on a PRIVATE
117
+ // connection: one that contributes steps and never appears in the catalog.
118
+ //
119
+ // Without it the base steps stay the exception the shell has to know about,
120
+ // and "every step is a declaration pointing at a hook" stops being true the
121
+ // moment somebody looks at the six most common ones.
122
+ email: Object.freeze([
123
+ // To a lead. Suppression applies, and the send is billed.
124
+ "send",
125
+ // To organization members. Never suppressed — an entrant's opt-out must not
126
+ // silence an alert to staff — and never billed.
127
+ "notify",
128
+ // A batched summary to members.
129
+ "digest"
130
+ ]),
131
+ sms: Object.freeze(["send"]),
132
+ segment: Object.freeze(["sync"]),
133
+ // OUTBOUND DELIVERY to an address the merchant owns, rather than to a vendor.
134
+ // The Webhooks connection is the only thing here with no third party behind
135
+ // it, and the destination is per STEP rather than per connection.
136
+ webhook: Object.freeze(["send"]),
137
+ // Vendor data we READ — the things a merchant picks from. Named `resources`
138
+ // rather than `catalog` because it also holds audiences, and a catalog is a
139
+ // commerce word for something that is not only commerce. It matches the
140
+ // pickers that render it, too: InputResource and ListResource.
141
+ //
142
+ // The verbs are named for what every vendor has, not for what one calls it:
143
+ // Shopify says discounts, Stripe says coupons and promotion codes,
144
+ // BigCommerce says coupons and promotions.
145
+ //
146
+ // ONE SHAPE FOR ALL OF THEM — searchable and cursor-paged:
147
+ //
148
+ // ({ connection, cursor, limit, search, settings, token })
149
+ // -> { items : [ { id, title, ... } ], pageInfo : { endCursor, hasNextPage } }
150
+ //
151
+ // Lifted from what the Shopify product picker already does, rather than
152
+ // invented: that endpoint takes cursor/limit/search and returns items plus a
153
+ // pageInfo, and ListResource consumes exactly that. It was a good contract
154
+ // written once for one vendor; this makes it the contract.
155
+ //
156
+ // `title` is not arbitrary — ListResource searches `[ 'title' ]` by default,
157
+ // so normalising to { id, title } is what lets a picker work with no
158
+ // per-vendor configuration.
159
+ //
160
+ // HOW a vendor searches is its own business, which is the point of a hook.
161
+ // Shopify pushes the term into its GraphQL query, Klaviyo has a filter
162
+ // parameter, and Mailchimp's /lists has no name filter at all so its hook
163
+ // matches against what it fetched. The caller never learns which.
164
+ resources: Object.freeze([
165
+ // The named groups a contact can be synced INTO. Klaviyo calls them lists,
166
+ // Mailchimp calls them audiences; `audiences` is the industry-generic term
167
+ // and belongs to neither vendor's API. Read at form time, so a merchant
168
+ // picks from what actually exists in their account rather than pasting an
169
+ // id from another tab.
170
+ "audiences",
171
+ "products",
172
+ // Shopify folds price into the product variant; Stripe makes Price a
173
+ // first-class object beside Product. Declared so a vendor that separates
174
+ // them has somewhere to answer.
175
+ "prices",
176
+ "promotions"
177
+ ])
178
+ });
179
+ var STEPS = Object.freeze({
180
+ "commerce.code.issue": "Issue discount code",
181
+ "commerce.customer.insert": "Create customer",
182
+ "commerce.order.record": "Record order",
183
+ "commerce.product.sync": "Sync product",
184
+ // Not commerce at all — connection lifecycle, and they generalise to any
185
+ // vendor holding a rotating credential.
186
+ "connection.health.check": "Connection health check",
187
+ "connection.token.exchange": "Exchange token",
188
+ "connection.token.refresh": "Refresh token",
189
+ "contacts.sync": "Sync contact",
190
+ "email.digest": "Digest",
191
+ "email.notify": "Notification",
192
+ "email.send": "Send email",
193
+ "segment.sync": "Sync segment",
194
+ "sms.send": "Send SMS",
195
+ "webhook.send": "Send webhook"
196
+ });
197
+ var RETIRED = Object.freeze({
198
+ "step.shopify.customer.insert": "step.commerce.customer.insert",
199
+ "step.shopify.discount.update": "step.commerce.code.issue",
200
+ "step.shopify.health.check": "step.connection.health.check",
201
+ "step.shopify.order.record": "step.commerce.order.record",
202
+ "step.shopify.product.sync": "step.commerce.product.sync",
203
+ "step.shopify.token.exchange": "step.connection.token.exchange",
204
+ "step.shopify.token.refresh": "step.connection.token.refresh"
205
+ });
206
+ var STEP_TYPES = Object.freeze(Object.keys(STEPS).map((name) => "step." + name));
207
+ var STEP_LABELS = Object.freeze(Object.fromEntries(
208
+ Object.entries(STEPS).map(([name, label]) => ["step." + name, label])
209
+ ));
210
+ var HOOK_NAMES = Object.freeze(
211
+ Object.entries(HOOKS).flatMap(([domain, verbs]) => verbs.map((verb) => domain + "." + verb))
212
+ );
213
+ var OUTCOMES = Object.freeze({
214
+ answered: "answered",
215
+ disconnected: "disconnected",
216
+ failed: "failed",
217
+ // Declared supported, implemented in a consumer rather than in this package —
218
+ // sync owns the step handlers and lifecycle jobs. Different from unsupported,
219
+ // which means the vendor cannot do it at all.
220
+ unimplemented: "unimplemented",
221
+ unsupported: "unsupported"
222
+ });
223
+ var STATUSES = Object.freeze(["active", "disconnected", "error", "pending"]);
224
+ var AUTH_TYPES = Object.freeze(["generated", "install", "keys", "none", "oauth"]);
225
+ var GROUPS = Object.freeze(["commerce", "contacts", "developer", "messaging"]);
226
+ var OAUTH_FIELDS = Object.freeze(["client"]);
227
+ var OAUTH_URLS = Object.freeze(["authorize", "redirect", "token"]);
228
+ var INPUTS = Object.freeze([
229
+ "checkbox",
230
+ "email",
231
+ "number",
232
+ "password",
233
+ "select",
234
+ "text",
235
+ "textarea",
236
+ "url"
237
+ ]);
238
+
239
+ // lib/connections/oauth.js
240
+ import { createHash, randomBytes } from "crypto";
241
+ var credentials = ({ basic, clientId, clientSecret }) => basic ? {
242
+ body: {},
243
+ headers: { authorization: "Basic " + Buffer.from(clientId + ":" + clientSecret).toString("base64") }
244
+ } : {
245
+ body: { client_id: clientId, client_secret: clientSecret },
246
+ headers: {}
247
+ };
248
+ var authToken = async ({
249
+ basic,
250
+ clientId,
251
+ clientSecret,
252
+ code: code2,
253
+ descriptor,
254
+ fetcher = fetch,
255
+ redirect,
256
+ refreshToken,
257
+ verifier
258
+ } = {}) => {
259
+ var _a;
260
+ if (!clientId || !clientSecret) throw new Error("This deployment has no OAuth client configured, so no token can be minted");
261
+ if (!((_a = descriptor == null ? void 0 : descriptor.urls) == null ? void 0 : _a.token)) throw new Error("This connection declares no token url");
262
+ const renewing = !code2;
263
+ if (renewing && !refreshToken) throw new Error("Nothing has been consented to yet, so there is no refresh token to spend");
264
+ if (!renewing && descriptor.pkce && !verifier) throw new Error("This connection requires PKCE, so the code verifier is not optional");
265
+ const client = credentials({ basic, clientId, clientSecret });
266
+ const response = await fetcher(descriptor.urls.token, {
267
+ body: new URLSearchParams({
268
+ ...client.body,
269
+ ...renewing ? { grant_type: "refresh_token", refresh_token: refreshToken } : {
270
+ code: decodeURIComponent(String(code2 || "").trim()),
271
+ grant_type: "authorization_code",
272
+ redirect_uri: redirect,
273
+ ...descriptor.pkce && { code_verifier: verifier }
274
+ }
275
+ }),
276
+ headers: { "content-type": "application/x-www-form-urlencoded", ...client.headers },
277
+ method: "POST",
278
+ signal: AbortSignal.timeout(15e3)
279
+ });
280
+ const body = await response.json().catch(() => ({}));
281
+ if (!response.ok) {
282
+ throw new Error(
283
+ renewing ? "The vendor refused the refresh token (" + response.status + ") \u2014 reconnect the connection" : "The vendor refused the exchange (" + response.status + ")" + ((body == null ? void 0 : body.error) ? ": " + body.error : "")
284
+ );
285
+ }
286
+ if (!renewing && !body.access_token) throw new Error("The vendor returned no access token");
287
+ return {
288
+ accessToken: body.access_token,
289
+ expiresIn: body.expires_in || null,
290
+ // A REFRESH TOKEN IS NOT UNIVERSAL. Google returns one only with
291
+ // access_type=offline; Mailchimp's tokens do not expire and it returns none
292
+ // at all, so its absence cannot be an error here.
293
+ //
294
+ // On a RENEWAL the same null matters for the opposite reason: a vendor that
295
+ // rotates returns a new one, and dropping it silently invalidates the stored
296
+ // grant on the NEXT refresh — a failure a day late and nowhere near its
297
+ // cause. tokenSettings() keeps the existing one when this is null.
298
+ refreshToken: body.refresh_token || null,
299
+ scope: body.scope || null
300
+ };
301
+ };
302
+
303
+ // lib/connections/token.js
304
+ var SKEW_SECONDS = 120;
305
+ var isStale = (settings, now = Date.now()) => {
306
+ if (!(settings == null ? void 0 : settings.expiresAt)) return false;
307
+ return new Date(settings.expiresAt).getTime() - SKEW_SECONDS * 1e3 <= now;
308
+ };
309
+ var tokenSettings = ({ existing = {}, now = Date.now(), tokens }) => ({
310
+ accessToken: tokens.accessToken,
311
+ // A vendor that does not rotate its refresh token returns none on a refresh
312
+ // (Klaviyo). Keeping the existing one is what makes the NEXT refresh work —
313
+ // dropping it invalidates the grant one call later, nowhere near the cause.
314
+ ...(tokens.refreshToken || existing.refreshToken) && {
315
+ refreshToken: tokens.refreshToken || existing.refreshToken
316
+ },
317
+ // Absent when the vendor issues non-expiring tokens, and absent is meaningful
318
+ // — isStale reads it as "nothing to refresh toward".
319
+ ...tokens.expiresIn && {
320
+ expiresAt: new Date(now + tokens.expiresIn * 1e3).toISOString()
321
+ },
322
+ ...tokens.scope && { scope: tokens.scope }
323
+ });
324
+ var accessToken = async ({
325
+ clientId,
326
+ clientSecret,
327
+ fetcher,
328
+ force = false,
329
+ manifest,
330
+ now = Date.now(),
331
+ save,
332
+ settings
333
+ } = {}) => {
334
+ if (!(settings == null ? void 0 : settings.accessToken) && !(settings == null ? void 0 : settings.refreshToken)) {
335
+ throw new Error("This connection holds no credential, so there is no token to use");
336
+ }
337
+ if (!force && !isStale(settings, now)) return settings.accessToken;
338
+ if (!settings.refreshToken) {
339
+ throw new Error("This connection has expired and cannot be renewed automatically. Reconnect it.");
340
+ }
341
+ const minted = await manifest.hooks.auth.token({
342
+ clientId,
343
+ clientSecret,
344
+ descriptor: manifest.auth.oauth,
345
+ ...fetcher && { fetcher },
346
+ refreshToken: settings.refreshToken
347
+ });
348
+ const next = tokenSettings({ existing: settings, now, tokens: minted });
349
+ if (save) await save(next);
350
+ return next.accessToken;
351
+ };
352
+
353
+ // lib/connections/icons/attentive.js
354
+ var attentive_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
355
+ <rect width="500" height="500" fill="#FFD967"/>
356
+ <path d="M239.369 127.404C260.863 122.013 284.964 132.569 295.576 152.039C321.796 201.286 347.928 250.567 374.131 299.825C380.149 311.989 381.244 326.564 376.733 339.41C371.446 355.097 358.039 367.69 342.107 372.089C326.274 376.67 308.351 372.871 295.741 362.255C288.865 356.892 284.161 349.359 280.354 341.629C261.869 306.95 243.478 272.217 225.071 237.501C214.409 218.614 187.221 212.656 169.622 225.315C168.104 227.309 164.159 226.857 164.72 223.796C176.911 202.569 189.361 181.497 201.662 160.331C205.183 154.428 208.214 148.129 212.967 143.091C219.844 135.272 229.263 129.782 239.374 127.404" fill="#1E1C1C"/>
357
+ <path d="M166.04 261.805C180.228 259.107 195.528 261.893 207.581 269.971C218.512 277.079 226.908 288.136 230.604 300.657C234.835 314.103 233.614 329.124 227.485 341.788C220.097 356.875 205.782 368.543 189.317 372.089C173.957 375.652 157.089 372.386 144.304 363.103C132.971 355.295 124.912 342.989 121.891 329.581C118.943 316.636 120.725 302.656 127.002 290.938C134.699 275.951 149.503 264.933 166.046 261.811" fill="#1E1C1C"/>
358
+ </svg>`;
359
+
360
+ // lib/connections/attentive.js
361
+ var attentive_default2 = {
362
+ auth: {
363
+ oauth: {
364
+ // NAMES of the env vars holding OUR app's client — set at registration,
365
+ // never before. No `headers` on the client: Attentive takes credentials
366
+ // as form fields, which is the runner's default.
367
+ client: {
368
+ id: "ATTENTIVE_OAUTH_CLIENT_ID",
369
+ secret: "ATTENTIVE_OAUTH_CLIENT_SECRET"
370
+ },
371
+ urls: {
372
+ authorize: "https://ui.attentivemobile.com/integrations/oauth-install",
373
+ redirect: "/api/connection/attentive/callback",
374
+ token: "https://api.attentivemobile.com/v1/authorization-codes/tokens"
375
+ }
376
+ },
377
+ type: "oauth"
378
+ },
379
+ // EVERYTHING A MERCHANT READS. `errors` would live in here too — the
380
+ // connection DOCUMENT carries its own `errors` array and is spread OVER the
381
+ // resolved manifest downstream, so a top-level one would never render.
382
+ content: {
383
+ // SAYS WHAT ACTUALLY HAPPENS. This used to promise that disconnecting
384
+ // revokes Drawbridge's access, and it cannot: Attentive documents no
385
+ // revocation endpoint, and their authentication page states an access
386
+ // token "does not expire". So the grant survives a disconnect forever
387
+ // unless the merchant removes the integration at Attentive, and the copy
388
+ // has to say so rather than let them believe otherwise.
389
+ confirm: "Disconnecting removes Drawbridge's stored Attentive token. Attentive does not offer a way for us to revoke it, so remove the Drawbridge integration in Attentive as well if you want its access fully withdrawn. Your subscribers stay in both Attentive and Drawbridge \u2014 neither list is deleted.",
390
+ description: [
391
+ "Attentive is where your SMS marketing lives, and this connection is becoming the way your Drawbridge contacts sync into an Attentive segment.",
392
+ "You authorize Drawbridge from inside Attentive and can revoke that access there at any time. Drawbridge never sees or stores your Attentive password.",
393
+ "Subscriber syncing is not live yet, so connecting today does nothing except choose the segment it will use when it ships."
394
+ ],
395
+ excerpt: "Sync your Drawbridge contacts into an Attentive segment.",
396
+ guide: [
397
+ "Press Connect. Drawbridge sends you to Attentive to approve access.",
398
+ "Sign in to Attentive if you are not already, and authorize the permissions listed.",
399
+ "You are returned here \u2014 choose which Attentive segment your contacts should sync into."
400
+ ]
401
+ },
402
+ // A contact destination, like Klaviyo and Mailchimp — a merchant could
403
+ // reasonably keep several up to date at once.
404
+ exclusive: false,
405
+ feature: "organization:connection:attentive",
406
+ fields: [
407
+ {
408
+ input: "select",
409
+ key: "segment",
410
+ label: "Attentive segment",
411
+ message: "Contacts your campaigns collect are synced into this segment.",
412
+ hook: "resources.audiences",
413
+ required: true
414
+ // No `search : false` here, and that is a first: /v2/segments takes a
415
+ // `name` filter (partial match, cited above), so this picker searches
416
+ // the ACCOUNT — Klaviyo and Mailchimp can only match the fetched page.
417
+ }
418
+ ],
419
+ group: "contacts",
420
+ // A HOOK'S VALUE IS ITS ANSWER. The consent is stored and can be revoked;
421
+ // nothing else is built yet, because subscriber sync has not shipped. Every
422
+ // false here is "not yet" rather than "never" — when the sync lands, probe
423
+ // and contacts.sync are the first to flip.
424
+ hooks: {
425
+ auth: {
426
+ // The exchange already yields the tokens, and Attentive documents no
427
+ // account-identity endpoint to enrich them with — Klaviyo's connect
428
+ // reads the account name back; this has nothing cited to read. The
429
+ // callback stores the tokens and skips enrichment on `unimplemented`.
430
+ // FALSE, NOT {}. `{}` means "supported, implemented in the repo with the
431
+ // dependencies", and nothing anywhere implements either of these —
432
+ // there is nothing for them to do. The exchange already yields the
433
+ // tokens and Attentive documents no account-identity endpoint to
434
+ // enrich them with, so connect has nothing to add; and they document
435
+ // no revocation endpoint at all, so disconnect has nothing to call.
436
+ // Recorded as a decision rather than left as an unkept promise.
437
+ connect: false,
438
+ disconnect: false,
439
+ probe: false,
440
+ scopes: false,
441
+ // THE ONE THING WRAPPED, and it is about the response rather than the
442
+ // request. Attentive's token reply carries expires_in : 900 while their
443
+ // auth overview says access tokens "do not expire" — and no refresh
444
+ // token exists to renew with. Storing that expiry would have
445
+ // accessToken() declaring the credential spent fifteen minutes after
446
+ // consent, with nothing to renew it: every connection would demand
447
+ // reconnecting four times an hour.
448
+ //
449
+ // The overview's answer is modelled — the expiry is dropped, so the
450
+ // token is treated as long-lived. Registration item 1 in the header is
451
+ // the live exchange that proves this right or wrong.
452
+ token: async (args) => {
453
+ const minted = await authToken(args);
454
+ return { ...minted, expiresIn: null };
455
+ }
456
+ },
457
+ commerce: false,
458
+ contacts: { remove: false, sync: false },
459
+ email: false,
460
+ inbound: false,
461
+ lifecycle: false,
462
+ resources: {
463
+ // The segments a merchant can sync into, for the picker on their
464
+ // connection.
465
+ //
466
+ // GET /v2/segments (cited in the header). `limit` caps at 1000 in their
467
+ // own spec, defaulting to 20 — low enough that leaving it unset would
468
+ // show a picker quietly missing most of a real account. The response's
469
+ // only identifier is `externalId`, so an entry without one cannot be
470
+ // stored and is dropped.
471
+ audiences: async ({ cursor, fetcher = fetch, limit = 100, search, token }) => {
472
+ const query = new URLSearchParams({
473
+ limit: String(Math.min(limit, 1e3)),
474
+ ...cursor && { cursor },
475
+ ...(search == null ? void 0 : search.value) && { name: String(search.value).trim() }
476
+ });
477
+ const response = await fetcher(
478
+ "https://api.attentivemobile.com/v2/segments?" + query,
479
+ {
480
+ headers: { authorization: "Bearer " + token },
481
+ signal: AbortSignal.timeout(15e3)
482
+ }
483
+ );
484
+ if (!response.ok) {
485
+ throw Object.assign(
486
+ new Error("Attentive refused the request (" + response.status + ")"),
487
+ { status: response.status }
488
+ );
489
+ }
490
+ const body = await response.json();
491
+ return {
492
+ items: ((body == null ? void 0 : body.segments) || []).filter((segment) => segment == null ? void 0 : segment.externalId).map((segment) => ({ id: segment.externalId, title: (segment == null ? void 0 : segment.name) || segment.externalId })),
493
+ pageInfo: {
494
+ endCursor: (body == null ? void 0 : body.hasMore) ? (body == null ? void 0 : body.cursor) || null : null,
495
+ hasNextPage: Boolean(body == null ? void 0 : body.hasMore)
496
+ }
497
+ };
498
+ },
499
+ prices: false,
500
+ products: false,
501
+ promotions: false
502
+ },
503
+ segment: false,
504
+ sms: false,
505
+ webhook: false
506
+ },
507
+ icon: attentive_default,
508
+ requires: [
509
+ "ATTENTIVE_OAUTH_CLIENT_ID",
510
+ "ATTENTIVE_OAUTH_CLIENT_SECRET"
511
+ ],
512
+ slug: "attentive",
513
+ // A consent with no segment chosen is authenticated and inert — the sync,
514
+ // when it ships, needs somewhere to put people.
515
+ status: (data2) => {
516
+ var _a;
517
+ return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.segment) ? data2.status : "pending";
518
+ },
519
+ // No steps: subscriber sync has not shipped, so this vendor contributes
520
+ // nothing to a workflow yet. An empty steps object is the honest declaration.
521
+ steps: {},
522
+ tasks: (data2) => {
523
+ var _a;
524
+ return [
525
+ ...((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.segment) ? [] : [
526
+ {
527
+ message: "Choose which Attentive segment your contacts should sync into. Until you do, nothing is being synced.",
528
+ title: "Choose a segment"
529
+ }
530
+ ],
531
+ {
532
+ message: "Contact syncing to Attentive segments has not shipped yet. Nothing is being sent to Attentive right now.",
533
+ title: "Subscriber sync not available yet",
534
+ type: "warning"
535
+ }
536
+ ];
537
+ },
538
+ title: "Attentive"
539
+ };
540
+
541
+ // lib/http.js
542
+ var DEFAULT_TIMEOUT_MS = 15e3;
543
+ var request = async ({
544
+ body,
545
+ headers = {},
546
+ method = "GET",
547
+ query,
548
+ timeout = DEFAULT_TIMEOUT_MS,
549
+ type = "json",
550
+ url
551
+ }) => {
552
+ const fullUrl = new URL(url);
553
+ if (query) {
554
+ Object.entries(query).forEach(([k, v]) => fullUrl.searchParams.set(k, v));
555
+ }
556
+ ;
557
+ const isForm = type === "form";
558
+ const response = await fetch(fullUrl.toString(), {
559
+ method,
560
+ headers: {
561
+ "Content-Type": isForm ? "application/x-www-form-urlencoded" : "application/json",
562
+ ...headers
563
+ },
564
+ signal: AbortSignal.timeout(timeout),
565
+ ...body !== void 0 && {
566
+ body: isForm ? new URLSearchParams(body).toString() : JSON.stringify(body)
567
+ }
568
+ });
569
+ if (!response.ok) {
570
+ const text2 = await response.text().catch(() => "");
571
+ const error = new Error(text2 || response.statusText);
572
+ error.status = response.status;
573
+ throw error;
574
+ }
575
+ ;
576
+ const text = await response.text();
577
+ try {
578
+ return text ? JSON.parse(text) : null;
579
+ } catch {
580
+ return null;
581
+ }
582
+ };
583
+
584
+ // lib/hubspot.js
585
+ var HUBSPOT_BASE = "https://api.hubapi.com";
586
+ var hubspotRequest = ({ body, fetcher, method, path, query, token }) => {
587
+ return (fetcher || request)({
588
+ body,
589
+ headers: {
590
+ "Authorization": "Bearer " + (token || process.env.HUBSPOT_ACCESS_TOKEN)
591
+ },
592
+ method,
593
+ query,
594
+ url: HUBSPOT_BASE + path
595
+ });
596
+ };
597
+ var UTM_PROPERTIES = {
598
+ campaign: "utm_campaign",
599
+ content: "utm_content",
600
+ id: "utm_id",
601
+ medium: "utm_medium",
602
+ source: "utm_source",
603
+ term: "utm_term"
604
+ };
605
+ var CLICK_PROPERTIES = {
606
+ fbclid: "hs_facebook_click_id",
607
+ gclid: "hs_google_click_id",
608
+ liFatId: "hs_linkedin_click_id",
609
+ msclkid: "hs_bing_click_id",
610
+ ttclid: "hs_tiktok_click_id"
611
+ };
612
+ var DROPPABLE = new Set(Object.values(UTM_PROPERTIES));
613
+ var isUtmProperty = (key) => DROPPABLE.has(key);
614
+ var toProperties = ({ email, firstName, lastName, utm }) => {
615
+ var _a;
616
+ const properties = {};
617
+ if (email !== void 0) properties.email = email;
618
+ if (firstName !== void 0) properties.firstname = firstName;
619
+ if (lastName !== void 0) properties.lastname = lastName;
620
+ if (utm) {
621
+ for (const [key, property] of Object.entries(UTM_PROPERTIES)) {
622
+ if (utm[key]) properties[property] = utm[key];
623
+ }
624
+ ;
625
+ for (const [key, property] of Object.entries(CLICK_PROPERTIES)) {
626
+ if ((_a = utm.click) == null ? void 0 : _a[key]) properties[property] = utm.click[key];
627
+ }
628
+ ;
629
+ }
630
+ ;
631
+ return properties;
632
+ };
633
+ var send = async ({ doc, fetcher, method, path, token }) => {
634
+ const properties = toProperties(doc);
635
+ try {
636
+ return await hubspotRequest({
637
+ body: { properties },
638
+ fetcher,
639
+ method,
640
+ path,
641
+ token
642
+ });
643
+ } catch (error) {
644
+ const enriched = Object.keys(properties).some(isUtmProperty);
645
+ if ((error == null ? void 0 : error.status) !== 400 || !enriched) throw error;
646
+ return await hubspotRequest({
647
+ body: {
648
+ properties: Object.fromEntries(
649
+ Object.entries(properties).filter(([key]) => !isUtmProperty(key))
650
+ )
651
+ },
652
+ fetcher,
653
+ method,
654
+ path,
655
+ token
656
+ });
657
+ }
658
+ };
659
+ var lookup = async ({ email, fetcher, token }) => {
660
+ var _a, _b;
661
+ if (!token || !email) return;
662
+ try {
663
+ const body = await hubspotRequest({
664
+ body: {
665
+ filterGroups: [
666
+ {
667
+ filters: [
668
+ {
669
+ operator: "EQ",
670
+ propertyName: "email",
671
+ value: email
672
+ }
673
+ ]
674
+ }
675
+ ],
676
+ limit: 1,
677
+ properties: ["email"]
678
+ },
679
+ fetcher,
680
+ method: "POST",
681
+ path: "/crm/v3/objects/contacts/search",
682
+ token
683
+ });
684
+ return (_b = (_a = body == null ? void 0 : body.results) == null ? void 0 : _a[0]) == null ? void 0 : _b.id;
685
+ } catch (error) {
686
+ }
687
+ };
688
+ var contacts = {
689
+ // FORGET A CONTACT, by id or by email. Account deletion — the caller had
690
+ // to search then remove, which is one round trip it should not have to
691
+ // know about.
692
+ remove: async ({ email, fetcher, id, token }) => {
693
+ const key = token || process.env.HUBSPOT_ACCESS_TOKEN;
694
+ if (!key) return;
695
+ const contact = id || await lookup({ email, fetcher, token: key });
696
+ if (!contact) return;
697
+ return hubspotRequest({
698
+ fetcher,
699
+ method: "DELETE",
700
+ path: "/crm/v3/objects/contacts/" + contact,
701
+ token: key
702
+ });
703
+ },
704
+ // Connect an account to its contact by email, creating it if absent, and
705
+ // return the contact id. Unlike SendGrid, HubSpot renames a contact's
706
+ // email in place, so an email change is a plain PATCH on the cached id —
707
+ // no delete-old-then-create-new.
708
+ //
709
+ // Prefer the cached hubspotId; fall back to a search; create last.
710
+ sync: async ({ doc, fetcher, token }) => {
711
+ var _a, _b;
712
+ const key = token || process.env.HUBSPOT_ACCESS_TOKEN;
713
+ if (!key) return;
714
+ if (doc == null ? void 0 : doc.hubspotId) {
715
+ try {
716
+ return (_a = await send({ doc, fetcher, method: "PATCH", path: "/crm/v3/objects/contacts/" + doc.hubspotId, token: key })) == null ? void 0 : _a.id;
717
+ } catch (error) {
718
+ if ((error == null ? void 0 : error.status) !== 404) throw error;
719
+ }
720
+ }
721
+ const existing = await lookup({ email: doc == null ? void 0 : doc.email, fetcher, token: key });
722
+ return (_b = await send({
723
+ doc,
724
+ fetcher,
725
+ method: existing ? "PATCH" : "POST",
726
+ path: existing ? "/crm/v3/objects/contacts/" + existing : "/crm/v3/objects/contacts",
727
+ token: key
728
+ })) == null ? void 0 : _b.id;
729
+ }
730
+ };
731
+
732
+ // lib/connections/icons/drawbridge.js
733
+ var drawbridge_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
734
+ <rect width="500" height="500" fill="#BAEC5F"/>
735
+ <g clip-path="url(#clip0_2115_2832)">
736
+ <path d="M140.224 127.586L174.803 188.73V311.176L140 372.32L176.084 392.031L216.111 321.753V178.278L176.341 108L140.224 127.586Z" fill="#0D1314"/>
737
+ <path d="M360.001 127.523L323.693 108.282L284.948 178.498V321.596L322.923 391.749L359.393 372.79L326.224 311.52V188.73L360.001 127.523Z" fill="#0D1314"/>
738
+ </g>
739
+ <defs>
740
+ <clipPath id="clip0_2115_2832">
741
+ <rect width="220" height="284" fill="white" transform="translate(140 108)"/>
742
+ </clipPath>
743
+ </defs>
744
+ </svg>`;
745
+
746
+ // lib/features.js
747
+ var page = {
748
+ qrcode: {
749
+ key: "page:qrcode",
750
+ error: "Plan does not include qrcodes",
751
+ feature: "Page qrcode management"
752
+ },
753
+ shortcode: {
754
+ key: "page:shortcode",
755
+ error: "Plan does not include shortcodes",
756
+ feature: "Page shortcode management"
757
+ },
758
+ slug: {
759
+ key: "page:slug",
760
+ error: "Plan does not include url customization",
761
+ feature: "Page slug customization"
762
+ }
763
+ };
764
+ var fields = {
765
+ additional: {
766
+ key: "campaign:fields:additional",
767
+ error: "Plan does not include additional fields",
768
+ feature: "Campaign additional fields"
769
+ },
770
+ lead: {
771
+ key: "campaign:fields:lead",
772
+ error: "Plan does not include lead fields",
773
+ feature: "Campaign lead fields"
774
+ }
775
+ };
776
+ var field = {
777
+ email: {
778
+ key: "campaign:field:email",
779
+ error: "Plan does not include email field",
780
+ feature: "Campaign email field"
781
+ },
782
+ name: {
783
+ key: "campaign:field:name",
784
+ error: "Plan does not include name field",
785
+ feature: "Campaign name field"
786
+ },
787
+ number: {
788
+ key: "campaign:field:number",
789
+ error: "Plan does not include number field",
790
+ feature: "Campaign number field"
791
+ },
792
+ phone: {
793
+ key: "campaign:field:phone",
794
+ error: "Plan does not include phone field",
795
+ feature: "Campaign phone field"
796
+ },
797
+ select: {
798
+ key: "campaign:field:select",
799
+ error: "Plan does not include dropdown field",
800
+ feature: "Campaign dropdown field"
801
+ },
802
+ text: {
803
+ key: "campaign:field:text",
804
+ error: "Plan does not include short text field",
805
+ feature: "Campaign short text field"
806
+ },
807
+ textarea: {
808
+ key: "campaign:field:textarea",
809
+ error: "Plan does not include long text field",
810
+ feature: "Campaign long text field"
811
+ }
812
+ };
813
+ var connection = {
814
+ attentive: {
815
+ key: "organization:connection:attentive",
816
+ error: "Plan does not include Attentive connection",
817
+ feature: "Attentive connection"
818
+ },
819
+ // Klaviyo shipped without an entry here, which meant no plan GRANTED its
820
+ // key and the feature gate denied every non-admin request — a latent 403
821
+ // found while adding Attentive. getPlanFeature answers granted:false for a
822
+ // key absent from the plan's map, so a manifest feature key that appears in
823
+ // no plan list is a connection only admins can manage.
824
+ klaviyo: {
825
+ key: "organization:connection:klaviyo",
826
+ error: "Plan does not include Klaviyo connection",
827
+ feature: "Klaviyo connection"
828
+ },
829
+ mailchimp: {
830
+ key: "organization:connection:mailchimp",
831
+ error: "Plan does not include Mailchimp connection",
832
+ feature: "Mailchimp connection"
833
+ },
834
+ sendgrid: {
835
+ key: "organization:connection:sendgrid",
836
+ error: "Plan does not include SendGrid connection",
837
+ feature: "SendGrid connection"
838
+ },
839
+ shopify: {
840
+ key: "organization:connection:shopify",
841
+ error: "Plan does not include Shopify connection",
842
+ feature: "Shopify connection"
843
+ },
844
+ twilio: {
845
+ key: "organization:connection:twilio",
846
+ error: "Plan does not include Twilio connection",
847
+ feature: "Twilio connection"
848
+ },
849
+ webhook: {
850
+ key: "organization:connection:webhook",
851
+ error: "Plan does not include Webhook connection",
852
+ feature: "Webhook connection"
853
+ }
854
+ };
855
+ var organization = {
856
+ advertisements: {
857
+ key: "organization:advertisements",
858
+ error: "Your plan does not include advertisements",
859
+ feature: "Organization advertisement management"
860
+ },
861
+ affiliates: {
862
+ key: "organization:affiliates",
863
+ error: "Your plan does not include affiliates",
864
+ feature: "Organization affiliates management"
865
+ },
866
+ analytics: {
867
+ key: "organization:analytics",
868
+ error: "Your plan does not include analytics",
869
+ feature: "Organization analytics management"
870
+ },
871
+ brands: {
872
+ key: "organization:brands",
873
+ error: "Your plan does not include brands",
874
+ feature: "Organization brands management"
875
+ },
876
+ // Gates the Networking section as a whole — a verified sending domain today,
877
+ // the SMS number and a custom page domain as they land. One key rather than
878
+ // one per type: they are the same capability to a merchant, and splitting
879
+ // them would mean a plan could grant half a section.
880
+ //
881
+ // It replaces `connection.sender`, which named a connection this stopped
882
+ // being. Free organizations cannot send lead-facing email at all, so a
883
+ // sending identity there is one they could never send from.
884
+ networking: {
885
+ key: "organization:networking",
886
+ error: "Your plan does not include a custom sending identity",
887
+ feature: "Organization networking"
888
+ },
889
+ members: {
890
+ key: "organization:members",
891
+ error: "Your plan does not include team members",
892
+ feature: "Organization members management"
893
+ },
894
+ reports: {
895
+ key: "organization:report",
896
+ error: "Plan does not include report generation",
897
+ feature: "Organization report generation"
898
+ },
899
+ subdomain: {
900
+ key: "organization:subdomain",
901
+ error: "Plan does not include subdomain customization",
902
+ feature: "Organization subdomain customization"
903
+ }
904
+ };
905
+
906
+ // index.js
907
+ import { code, data } from "currency-codes";
908
+ import { customAlphabet } from "nanoid";
909
+
910
+ // lib/color.js
911
+ import tinycolor from "tinycolor2";
912
+ var colorFormatted = (value) => {
913
+ const color = tinycolor(value);
914
+ const attributes = {
915
+ brightness: color.getBrightness(),
916
+ dark: color.isDark(),
917
+ light: color.isLight(),
918
+ luminance: color.getLuminance()
919
+ };
920
+ return {
921
+ attributes,
922
+ hex: color.toHexString(),
923
+ hsl: color.toHsl(),
924
+ hsv: color.toHsv(),
925
+ rgb: color.toRgbString()
926
+ };
927
+ };
928
+ var colorAccessible = (background2) => {
929
+ const white = "#ffffff";
930
+ const black = "#000000";
931
+ return tinycolor.isReadable(
932
+ background2,
933
+ white,
934
+ {
935
+ level: "AA",
936
+ size: "normal"
937
+ }
938
+ ) ? white : black;
939
+ };
940
+
941
+ // lib/constants.js
942
+ var font = {
943
+ family: "Roboto Flex",
944
+ transform: "none",
945
+ weight: "regular"
946
+ };
947
+ var background = "#ffffff";
948
+ var style = {
949
+ background: {
950
+ color: colorFormatted(background)
951
+ },
952
+ body: font,
953
+ button: {
954
+ background: {
955
+ color: colorFormatted(background)
956
+ },
957
+ radius: 0,
958
+ text: {
959
+ color: colorFormatted(colorAccessible(background))
960
+ }
961
+ },
962
+ heading: font,
963
+ input: {
964
+ radius: 0
965
+ },
966
+ text: {
967
+ color: colorFormatted(colorAccessible(background))
968
+ }
969
+ };
970
+
971
+ // index.js
972
+ var nanoid = customAlphabet("0123456789abcdefghijklmnopqrstuvwxyz", 8);
973
+ var infinite = 1e300;
974
+ var megabyte = 1024 * 1024;
975
+ var gigabyte = megabyte * 1024;
976
+ var currencies = data.map((item) => ({
977
+ ...item,
978
+ key: item.currency,
979
+ value: item.code
980
+ }));
981
+
982
+ // lib/plans.js
983
+ var featuresFor = (array = []) => Object.values({
984
+ ...connection,
985
+ ...organization,
986
+ ...fields,
987
+ ...field,
988
+ ...page
989
+ }).reduce(
990
+ (accumulator, { key, error, feature }) => {
991
+ if (array.includes(key)) {
992
+ accumulator.granted[key] = feature;
993
+ } else {
994
+ accumulator.denied[key] = error;
995
+ }
996
+ return accumulator;
997
+ },
998
+ { denied: {}, granted: {} }
999
+ );
1000
+ var overage = (actionCents) => ({
1001
+ actionCents,
1002
+ overages: { actions: String(actionCents) }
1003
+ });
1004
+ var all = {
1005
+ features: (array = []) => featuresFor([
1006
+ connection.attentive.key,
1007
+ connection.klaviyo.key,
1008
+ connection.mailchimp.key,
1009
+ connection.sendgrid.key,
1010
+ connection.shopify.key,
1011
+ connection.twilio.key,
1012
+ connection.webhook.key,
1013
+ organization.affiliates.key,
1014
+ organization.brands.key,
1015
+ fields.additional.key,
1016
+ fields.lead.key,
1017
+ field.email.key,
1018
+ field.name.key,
1019
+ field.number.key,
1020
+ field.phone.key,
1021
+ field.select.key,
1022
+ field.text.key,
1023
+ field.textarea.key,
1024
+ page.qrcode.key,
1025
+ page.shortcode.key,
1026
+ ...array
1027
+ ]),
1028
+ // `members` and `storage` default to infinite so an unnamed term on a custom
1029
+ // plan reads as UNLIMITED rather than absent. Storage used to have no
1030
+ // default, so a deal that did not name it resolved to undefined and the
1031
+ // organization's usage card simply omitted the row — the same blank field
1032
+ // that showed "Unlimited" for members showed nothing at all for storage.
1033
+ // Every catalog plan names both, so the defaults only ever apply to a
1034
+ // custom plan. `actions` has no default on purpose: an unnamed allowance
1035
+ // bills nothing, which is why the availability switch refuses to flip
1036
+ // without one.
1037
+ limits: ({ actions, members = infinite, storage = infinite }) => ({
1038
+ campaign: {
1039
+ advertisements: infinite,
1040
+ links: infinite,
1041
+ fields: infinite,
1042
+ pages: infinite
1043
+ },
1044
+ organization: {
1045
+ actions,
1046
+ affiliates: infinite,
1047
+ brands: infinite,
1048
+ campaigns: infinite,
1049
+ members,
1050
+ storage
1051
+ }
1052
+ })
1053
+ };
1054
+ var free = {
1055
+ conversion: 3,
1056
+ features: all.features(),
1057
+ limits: all.limits({
1058
+ actions: 200,
1059
+ members: 0,
1060
+ storage: gigabyte * 5
1061
+ }),
1062
+ title: "Free"
1063
+ };
1064
+ var plans = {
1065
+ DB00002: {
1066
+ // A verified sending domain is a PAID capability: free plans cannot send
1067
+ // lead-facing email at all (the send path gates on an active
1068
+ // subscription), so granting it there would offer a domain that can
1069
+ // never send from.
1070
+ features: all.features([organization.networking.key, organization.members.key]),
1071
+ limits: all.limits({ actions: 5e3, members: 3, storage: gigabyte * 10 }),
1072
+ marketing: {
1073
+ description: "Tools to fine-tune campaigns and improve lead quality.",
1074
+ features: [],
1075
+ limits: [
1076
+ ["Actions per month", "5,000"],
1077
+ ["Affiliates", "Unlimited"],
1078
+ ["Brands", "Unlimited"],
1079
+ ["Campaigns", "Unlimited"],
1080
+ ["Pages", "Unlimited"],
1081
+ ["Members", "3"],
1082
+ ["Storage", "10GB"]
1083
+ ]
1084
+ },
1085
+ ...overage(2.5),
1086
+ title: "Starter",
1087
+ conversion: 2
1088
+ },
1089
+ DB00003: {
1090
+ features: all.features([
1091
+ organization.networking.key,
1092
+ organization.advertisements.key,
1093
+ organization.analytics.key,
1094
+ organization.members.key,
1095
+ organization.subdomain.key,
1096
+ page.slug.key
1097
+ ]),
1098
+ limits: all.limits({ actions: 15e3, members: 5, storage: gigabyte * 20 }),
1099
+ marketing: {
1100
+ description: "Expand your reach and grow your lead pipeline.",
1101
+ features: [
1102
+ "Analytics",
1103
+ "Custom subdomain / URLs",
1104
+ "Confirmation page ads"
1105
+ ],
1106
+ limits: [
1107
+ ["Actions per month", "15,000"],
1108
+ ["Affiliates", "Unlimited"],
1109
+ ["Brands", "Unlimited"],
1110
+ ["Campaigns", "Unlimited"],
1111
+ ["Pages", "Unlimited"],
1112
+ ["Members", "5"],
1113
+ ["Storage", "20GB"]
1114
+ ]
1115
+ },
1116
+ ...overage(2),
1117
+ title: "Pro",
1118
+ conversion: 1.5
1119
+ },
1120
+ DB00004: {
1121
+ features: all.features([
1122
+ organization.networking.key,
1123
+ organization.advertisements.key,
1124
+ organization.analytics.key,
1125
+ organization.members.key,
1126
+ organization.subdomain.key,
1127
+ page.slug.key
1128
+ ]),
1129
+ limits: all.limits({ actions: 4e4, members: 10, storage: gigabyte * 50 }),
1130
+ marketing: {
1131
+ description: "Accelerate acquisition with more power and flexibility.",
1132
+ features: [
1133
+ "Analytics",
1134
+ "Custom subdomain / URLs",
1135
+ "Confirmation page ads"
1136
+ ],
1137
+ limits: [
1138
+ ["Actions per month", "40,000"],
1139
+ ["Affiliates", "Unlimited"],
1140
+ ["Brands", "Unlimited"],
1141
+ ["Campaigns", "Unlimited"],
1142
+ ["Pages", "Unlimited"],
1143
+ ["Members", "10"],
1144
+ ["Storage", "50GB"]
1145
+ ]
1146
+ },
1147
+ ...overage(1.85),
1148
+ title: "Premium",
1149
+ conversion: 1
1150
+ },
1151
+ DB00005: {
1152
+ features: all.features([
1153
+ organization.networking.key,
1154
+ organization.advertisements.key,
1155
+ organization.analytics.key,
1156
+ organization.members.key,
1157
+ organization.subdomain.key,
1158
+ page.slug.key
1159
+ ]),
1160
+ limits: all.limits({ actions: 1e5, members: infinite, storage: gigabyte * 100 }),
1161
+ marketing: {
1162
+ description: "Built for brands focused on results.",
1163
+ features: [
1164
+ "Analytics",
1165
+ "Custom subdomain / URLs",
1166
+ "Confirmation page ads"
1167
+ ],
1168
+ limits: [
1169
+ ["Actions per month", "100,000"],
1170
+ ["Affiliates", "Unlimited"],
1171
+ ["Brands", "Unlimited"],
1172
+ ["Campaigns", "Unlimited"],
1173
+ ["Pages", "Unlimited"],
1174
+ ["Members", "Unlimited"],
1175
+ ["Storage", "100GB"]
1176
+ ]
1177
+ },
1178
+ ...overage(1.5),
1179
+ title: "Elite",
1180
+ conversion: 0.5
1181
+ }
1182
+ };
1183
+
1184
+ // lib/transactions.js
1185
+ import { currentTraceId } from "@drawbridge/drawbridge-telemetry";
1186
+
1187
+ // lib/billing.js
1188
+ import { createLogger } from "@drawbridge/drawbridge-telemetry";
1189
+ var logger = createLogger();
1190
+ var MARKUP = 1.3;
1191
+ var cost = {
1192
+ // gemini-3.5-flash — verified against Google's pricing page 2026-07-09:
1193
+ // $0.15 cached / $1.50 input / $9.00 output per 1M tokens (thinking billed at
1194
+ // output). ~3.6x the retired 2.5-flash output rate.
1195
+ "gemini-3.5-flash": {
1196
+ cached: 15,
1197
+ input: 150,
1198
+ output: 900
1199
+ },
1200
+ // gemini-3.5-flash-lite — verified against Google's pricing page 2026-08-20:
1201
+ // $0.03 cached / $0.30 input / $2.50 output per 1M tokens (thinking billed at
1202
+ // output). A fifth of flash on input, ~a quarter on output. Growth's assistant
1203
+ // ranks the feed on this tier — one call per page — so its rows were the
1204
+ // unpriced ones until now.
1205
+ "gemini-3.5-flash-lite": {
1206
+ cached: 3,
1207
+ input: 30,
1208
+ output: 250
1209
+ },
1210
+ "gemini-2.5-flash": {
1211
+ cached: 3,
1212
+ input: 30,
1213
+ output: 250
1214
+ },
1215
+ "gemini-2.5-flash-image": {
1216
+ cached: 3,
1217
+ input: 30,
1218
+ output: 3e3
1219
+ },
1220
+ // gemini-3-pro-image-preview — verified against Google's pricing page
1221
+ // 2026-08-12: $2.00 input / $12.00 text output per 1M, and image output
1222
+ // tokens at ~$120/1M (a 1K-2K image is 1120 tokens = $0.134, a 4K image
1223
+ // 2000 tokens = $0.24). Encoded the flash-image way: one flat output rate
1224
+ // that reproduces the per-image price from the tokens usageMetadata
1225
+ // reports. Growth's hero generation runs this model today.
1226
+ "gemini-3-pro-image-preview": {
1227
+ cached: 20,
1228
+ input: 200,
1229
+ output: 12e3
1230
+ }
1231
+ };
1232
+ var toolCost = {
1233
+ search: 3.5
1234
+ };
1235
+ var toolPricing = Object.fromEntries(
1236
+ Object.entries(toolCost).map(([tool, value]) => [
1237
+ tool,
1238
+ Math.ceil(value * MARKUP)
1239
+ ])
1240
+ );
1241
+ var pricing = Object.fromEntries(
1242
+ Object.entries(cost).map(([model, rates]) => [
1243
+ model,
1244
+ {
1245
+ cached: Math.round(rates.cached * MARKUP),
1246
+ input: Math.round(rates.input * MARKUP),
1247
+ output: Math.round(rates.output * MARKUP)
1248
+ }
1249
+ ])
1250
+ );
1251
+
1252
+ // lib/pricing.js
1253
+ var emailPlans = {
1254
+ essentials50k: {
1255
+ included: 5e4,
1256
+ // The plan's own price is not shown in the console once you are on it —
1257
+ // it reads "Your Current Plan" where the price would be. Left null rather
1258
+ // than guessed; fill from an invoice. Nothing derives from it yet, and an
1259
+ // invented figure would quietly become the basis of an upgrade decision.
1260
+ monthly: null,
1261
+ overageCents: 0.133,
1262
+ title: "Essentials 50K"
1263
+ },
1264
+ essentials100k: {
1265
+ included: 1e5,
1266
+ monthly: 3495,
1267
+ overageCents: 0.09,
1268
+ title: "Essentials 100K"
1269
+ },
1270
+ pro100k: {
1271
+ included: 1e5,
1272
+ monthly: 8995,
1273
+ overageCents: 0.11,
1274
+ title: "Pro 100K"
1275
+ },
1276
+ pro300k: {
1277
+ included: 3e5,
1278
+ monthly: 24900,
1279
+ overageCents: 0.091,
1280
+ title: "Pro 300K"
1281
+ },
1282
+ pro700k: {
1283
+ included: 7e5,
1284
+ monthly: 49900,
1285
+ overageCents: 0.078,
1286
+ title: "Pro 700K"
1287
+ },
1288
+ pro1500k: {
1289
+ included: 15e5,
1290
+ monthly: 79900,
1291
+ overageCents: 0.059,
1292
+ title: "Pro 1.5 Million"
1293
+ },
1294
+ pro2500k: {
1295
+ included: 25e5,
1296
+ monthly: 109900,
1297
+ overageCents: 0.047,
1298
+ title: "Pro 2.5 Million"
1299
+ }
1300
+ };
1301
+ var emailPlan = "essentials50k";
1302
+ var sending = {
1303
+ email: {
1304
+ // Fraction of the included volume that raises the alarm. Far enough ahead
1305
+ // to act on, high enough not to fire on ordinary growth.
1306
+ //
1307
+ // Crossing it is NOT an outage. The provider bills overage rather than
1308
+ // stopping sends, so the alarm is a COST signal: past the included volume
1309
+ // every email is charged at overageCents, and at some run rate the next
1310
+ // plan up is cheaper than the overage. That is the decision it exists to
1311
+ // prompt, and it is why nobody should be woken by it.
1312
+ alertThreshold: 0.8,
1313
+ // Emails per calendar month included, PLATFORM-WIDE and across every send
1314
+ // path: lead-facing mail, workflow steps, and the sign-in codes and
1315
+ // account mail that no plan allowance meters.
1316
+ monthlyCeiling: emailPlans[emailPlan].included,
1317
+ overageCents: emailPlans[emailPlan].overageCents,
1318
+ plan: emailPlan,
1319
+ plans: emailPlans,
1320
+ title: emailPlans[emailPlan].title
1321
+ }
1322
+ };
1323
+ var channels = {
1324
+ email: {
1325
+ actionsPerSend: 1,
1326
+ includedInAllowance: true
1327
+ },
1328
+ sms: {
1329
+ // Two actions PER SEGMENT (a long message is several segments), billed from
1330
+ // the FIRST segment and never drawn from the plan's included allowance —
1331
+ // carrier cost is real from message one, so there is no free tier of it.
1332
+ actionsPerSegment: 2,
1333
+ includedInAllowance: false
1334
+ }
1335
+ };
1336
+
1337
+ // lib/connections/drawbridge.js
1338
+ var drawbridge_default2 = {
1339
+ auth: {
1340
+ type: "none"
1341
+ },
1342
+ content: {
1343
+ confirm: "This connection is part of Drawbridge and cannot be disconnected.",
1344
+ description: [
1345
+ "Drawbridge sends your notification email and SMS, keeps your segments in sync, and posts to your own endpoints. These are built in rather than connected, so there is nothing here to set up."
1346
+ ],
1347
+ excerpt: "The steps Drawbridge runs itself.",
1348
+ guide: [
1349
+ "Nothing to do. These steps are available in every workflow builder."
1350
+ ]
1351
+ },
1352
+ exclusive: false,
1353
+ fields: [],
1354
+ group: "developer",
1355
+ // EVERY BODY LIVES IN drawbridge-sync. Sending needs the provider clients, the
1356
+ // suppression collection and the queues; segment sync needs the streams. A
1357
+ // published package carrying those makes every consumer carry them, which is
1358
+ // the reason `{}` exists as an answer.
1359
+ hooks: {
1360
+ auth: {
1361
+ // Nothing to connect, revoke, probe or re-scope.
1362
+ connect: false,
1363
+ disconnect: false,
1364
+ probe: false,
1365
+ scopes: false,
1366
+ token: false
1367
+ },
1368
+ commerce: false,
1369
+ // DRAWBRIDGE'S OWN CRM. Not a merchant's — this keeps our HubSpot portal in
1370
+ // step with account signups, and drawbridge-sync's user stream calls it.
1371
+ //
1372
+ // A real implementation here rather than `{}` because the bodies are pure
1373
+ // HTTP against a token: no controller, no queue, nothing that would have to
1374
+ // live in the service. lib/hubspot.js holds them, beside lib/sendgrid.js
1375
+ // and lib/twilio.js, which are the same kind of thing — vendor clients for
1376
+ // accounts DRAWBRIDGE holds rather than ones a merchant connects.
1377
+ contacts,
1378
+ email: {
1379
+ digest: {},
1380
+ // To organization members. NEVER suppressed and never billed: an
1381
+ // entrant's opt-out must not silence an alert to staff, and staff mail is
1382
+ // not a metered send.
1383
+ notify: {},
1384
+ // To a lead. Suppression applies and the send is billed.
1385
+ send: {}
1386
+ },
1387
+ inbound: false,
1388
+ lifecycle: false,
1389
+ resources: {
1390
+ audiences: false,
1391
+ prices: false,
1392
+ products: false,
1393
+ promotions: false
1394
+ },
1395
+ segment: { sync: {} },
1396
+ sms: { send: {} },
1397
+ webhook: false
1398
+ },
1399
+ icon: drawbridge_default,
1400
+ // PRIVATE: never in the catalog, always available to the builder.
1401
+ private: true,
1402
+ // NOTHING, and HUBSPOT_ACCESS_TOKEN in particular must not be here.
1403
+ //
1404
+ // `requires` gates AVAILABILITY: a name in it that is unset removes the whole
1405
+ // connection. This one is private and contributes every base workflow step —
1406
+ // email.send, sms.send, segment.sync — so gating it on a CRM token would take
1407
+ // all of them away from any deployment without a HubSpot portal, to protect a
1408
+ // sync that is best-effort and already no-ops without a token.
1409
+ //
1410
+ // The test 'a vendor is only available when its environment is configured'
1411
+ // caught exactly that: availableConnections({}) went from [ 'drawbridge' ] to
1412
+ // empty the moment this was added.
1413
+ requires: [],
1414
+ slug: "drawbridge",
1415
+ // Always on. There is no credential that could go bad and no configuration a
1416
+ // merchant could leave half-finished.
1417
+ status: () => "active",
1418
+ // DERIVED FROM drawbridge-api/lib/workflows.js, not invented. Every value
1419
+ // below — trigger, billable, settings — is what that catalog and the workflow
1420
+ // route already enforce today, because this replaces them rather than
1421
+ // competing with them.
1422
+ //
1423
+ // NOT HERE, deliberately:
1424
+ //
1425
+ // step.segment.sync a SYSTEM step, dispatched by drawbridge-sync rather
1426
+ // than offered in the builder. It fans out, so the shell
1427
+ // opens its step document and the chunks close it.
1428
+ steps: {
1429
+ email: {
1430
+ // SCHEDULE-TRIGGERED, not lead-triggered: it is offered under Daily,
1431
+ // Weekly and Monthly. Those triggers had offered no steps at all, so a
1432
+ // scheduled workflow was selectable and inert until this landed.
1433
+ digest: () => ({
1434
+ hook: "email.digest",
1435
+ key: "Email \u2014 Digest",
1436
+ queue: "notification",
1437
+ settings: {
1438
+ // The organization OWNER is always a recipient, resolved in sync,
1439
+ // so this is additional recipients rather than the list. It cannot
1440
+ // be required: the members endpoint is owner-gated and the owner is
1441
+ // not a member document, so a solo merchant has nothing to pick and
1442
+ // could never save the step.
1443
+ members: { of: "string", type: "array" },
1444
+ message: { required: true, type: "string" },
1445
+ subject: { required: true, type: "string" }
1446
+ },
1447
+ triggers: ["schedule.day", "schedule.week", "schedule.month"],
1448
+ usage: { actions: 0 }
1449
+ }),
1450
+ // To organization MEMBERS. Never suppressed — an entrant's opt-out must
1451
+ // not silence an alert to staff — and not billed.
1452
+ notify: () => ({
1453
+ hook: "email.notify",
1454
+ key: "Email \u2014 Notification",
1455
+ queue: "notification",
1456
+ settings: {
1457
+ members: { of: "string", type: "array" },
1458
+ message: { required: true, type: "string" },
1459
+ subject: { required: true, type: "string" }
1460
+ },
1461
+ triggers: ["lead.insert"],
1462
+ // Zero is a PRICE, and a deliberate one. Declared rather than omitted
1463
+ // so "this is free" and "nobody decided" stay different statements;
1464
+ // completeStep bills only when actions > 0.
1465
+ usage: { actions: 0 }
1466
+ }),
1467
+ // To a LEAD. Suppression applies and the send is billed.
1468
+ send: () => ({
1469
+ hook: "email.send",
1470
+ key: "Email \u2014 Send email",
1471
+ queue: "notification",
1472
+ settings: {
1473
+ message: { required: true, type: "string" },
1474
+ subject: { required: true, type: "string" }
1475
+ },
1476
+ triggers: ["lead.insert"],
1477
+ // ONE SOURCE FOR THE PRICE. lib/pricing.js is the index of every
1478
+ // customer-facing number; the handler read it too, so the same fact
1479
+ // was stated in two places and only one of them was reviewed.
1480
+ usage: { actions: channels.email.actionsPerSend }
1481
+ })
1482
+ },
1483
+ // WITHDRAWN, which is a third thing from builder and system: declared,
1484
+ // routed and runnable, but never offered.
1485
+ //
1486
+ // It went when the twilio connection did — a connection-gated step with no
1487
+ // connection to gate on could only ever render permanently disabled. Stored
1488
+ // workflows still carry it, so it must keep running, and enums.step.type
1489
+ // keeps it for the same reason.
1490
+ //
1491
+ // NO TRIGGERS is what keeps it out of the builder: the catalog derives from
1492
+ // triggers, so a step with none is unreachable by a merchant without a
1493
+ // second list saying so.
1494
+ //
1495
+ // Platform SMS returns as a base step the way email did. That is this entry
1496
+ // gaining triggers, not a new one.
1497
+ sms: {
1498
+ send: () => ({
1499
+ hook: "sms.send",
1500
+ key: "Send an SMS",
1501
+ queue: "notification",
1502
+ settings: {
1503
+ message: { required: true, type: "string" },
1504
+ subject: { required: true, type: "string" }
1505
+ },
1506
+ // Priced per SEGMENT and billed from the first, which the send
1507
+ // resolves from the message length. This is the floor.
1508
+ usage: { actions: channels.sms.actionsPerSegment },
1509
+ withdrawn: true
1510
+ })
1511
+ },
1512
+ segment: {
1513
+ // FANS OUT. It evaluates every contact in the organization against every
1514
+ // segment, which is too much for one job — so the hook returns chunks and
1515
+ // the shell defers completion: openStep writes the document with a slot
1516
+ // per chunk, and whichever chunk lands last closes it and resumes the
1517
+ // chain.
1518
+ //
1519
+ // It carries a hook like every other step. An earlier version declared
1520
+ // none, on the theory that fan-out was a second protocol the shell could
1521
+ // not run; it is the same protocol with the ending deferred, and a step
1522
+ // declaring no hook is silently SKIPPED by the runner.
1523
+ sync: () => ({
1524
+ description: "Recalculates segment membership on a daily schedule.",
1525
+ hook: "segment.sync",
1526
+ key: "Segment Sync",
1527
+ queue: "segment",
1528
+ system: true
1529
+ })
1530
+ }
1531
+ },
1532
+ tasks: () => [],
1533
+ title: "Drawbridge"
1534
+ };
1535
+
1536
+ // lib/connections/icons/klaviyo.js
1537
+ var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
1538
+ <rect width="500" height="500" fill="white"/>
1539
+ <path d="M365.047 327.038H134.954V172.964H365.047L316.856 250.001L365.047 327.038Z" fill="#232121"/>
1540
+ </svg>`;
1541
+
1542
+ // lib/connections/klaviyo.js
1543
+ var api = async (path, { fetcher = fetch, method = "GET", payload, token }) => {
1544
+ const response = await fetcher("https://a.klaviyo.com/api" + path, {
1545
+ ...payload && { body: JSON.stringify(payload) },
1546
+ headers: {
1547
+ // Bearer, not Klaviyo-API-Key — that header is for private keys, and
1548
+ // sending it with an OAuth token fails in a way that reads like a bad
1549
+ // token rather than a bad scheme.
1550
+ authorization: "Bearer " + token,
1551
+ ...payload && { "content-type": "application/json" },
1552
+ // Klaviyo pins its API by DATE. A request without this header is
1553
+ // refused, and one with an old date keeps the response shape that date
1554
+ // shipped with — which is the point: bumping it is a deliberate act
1555
+ // with a changelog to read, not something that drifts under us.
1556
+ revision: "2026-07-15"
1557
+ },
1558
+ method,
1559
+ signal: AbortSignal.timeout(15e3)
1560
+ });
1561
+ if (!response.ok) {
1562
+ throw Object.assign(
1563
+ new Error("Klaviyo refused the request (" + response.status + ")"),
1564
+ { status: response.status }
1565
+ );
1566
+ }
1567
+ return response.status === 204 ? null : response.json();
1568
+ };
1569
+ var klaviyo_default2 = {
1570
+ // OAuth 2.1, and PKCE is REQUIRED rather than recommended: Klaviyo refuses an
1571
+ // exchange without a code_verifier matching the challenge the consent
1572
+ // carried. Most vendors treat it as optional hardening; this one does not,
1573
+ // which is why it is a descriptor flag and not a global.
1574
+ //
1575
+ // HTTP Basic on the token endpoint is the other thing Klaviyo does
1576
+ // differently, and it says so in hooks.auth.token rather than as a flag here.
1577
+ auth: {
1578
+ oauth: {
1579
+ // NAMES the env vars holding OUR application's client. One identity,
1580
+ // every merchant — the token is the merchant's and arrives from their
1581
+ // own consent, which is what stops one organization reading another's
1582
+ // data.
1583
+ //
1584
+ client: {
1585
+ id: "KLAVIYO_OAUTH_CLIENT_ID",
1586
+ secret: "KLAVIYO_OAUTH_CLIENT_SECRET"
1587
+ },
1588
+ // Klaviyo drops a refresh token after 90 days of NON-USE. The vendor
1589
+ // never mentions this at runtime — you discover it when a refresh fails
1590
+ // on a connection nobody touched — so it is declared, and it is why
1591
+ // auth.probe has to run on a schedule rather than only before a call.
1592
+ //
1593
+ // Token lifetime is NOT declared: the vendor states it on every
1594
+ // exchange, and a copy here would be a second answer that goes stale.
1595
+ expiry: 90 * 24 * 60 * 60,
1596
+ pkce: true,
1597
+ // Space separated. accounts:read is required by Klaviyo on every app
1598
+ // and must stay in the list; the rest are what a contact sync needs.
1599
+ scopes: "accounts:read lists:read lists:write profiles:read profiles:write",
1600
+ // EVERY VENDOR URL, in one place. `revoke` used to be a literal inside
1601
+ // the disconnect hook — three vendor addresses, two of them declared,
1602
+ // which is exactly the kind of split that goes unnoticed.
1603
+ urls: {
1604
+ // TWO DIFFERENT HOSTS, and swapping them fails in opposite ways.
1605
+ //
1606
+ // authorize is a page a HUMAN loads, and it lives on www. Pointing it
1607
+ // at a.klaviyo.com — their API host — sends the merchant somewhere
1608
+ // that never renders a consent screen, so the journey stalls with no
1609
+ // error anybody can see.
1610
+ //
1611
+ // token and revoke are server calls and must stay on a.klaviyo.com:
1612
+ // Klaviyo began blocking OAuth token traffic through www on
1613
+ // 2025-03-31, so the mirror image of this mistake breaks the exchange
1614
+ // instead of the consent.
1615
+ authorize: "https://www.klaviyo.com/oauth/authorize",
1616
+ // WHERE THE MERCHANT LANDS — the dashboard, not drawbridge-api. The
1617
+ // `/api/` segment is Next's route-handler convention, which reads as
1618
+ // the api service to everyone who sees it; it is not, and the route
1619
+ // has never moved. build() pins it against the one callback route
1620
+ // that exists, because declared-but-wrong fails AFTER consent — a
1621
+ // 404 for someone who has already granted access.
1622
+ //
1623
+ // Registered in Klaviyo's own app settings, and they refuse anything
1624
+ // that does not byte-match, so it is a fact about someone else's
1625
+ // records rather than a string this code computes.
1626
+ redirect: "/api/connection/klaviyo/callback",
1627
+ revoke: "https://a.klaviyo.com/oauth/revoke",
1628
+ token: "https://a.klaviyo.com/oauth/token"
1629
+ }
1630
+ },
1631
+ type: "oauth"
1632
+ },
1633
+ // EVERYTHING A MERCHANT READS. Grouped by who it is for rather than by what
1634
+ // kind of sentence it is, so the question on the next vendor is "does a person
1635
+ // read this", which nobody gets wrong, instead of "is this marketing", which
1636
+ // someone will.
1637
+ //
1638
+ // `errors` is in here rather than at the top level, and that is not a
1639
+ // preference. The connection DOCUMENT carries its own `errors` array of
1640
+ // scope-drift entries, and the document is spread OVER the resolved manifest
1641
+ // downstream — so a top-level `errors` here would be silently replaced by that
1642
+ // array and this copy would never render. `fields`/`settings` already carry a
1643
+ // comment about the same collision.
1644
+ content: {
1645
+ // Shown at disconnect, so it says what is lost and what is not.
1646
+ confirm: "Disconnecting revokes Drawbridge's access to your Klaviyo account. Your profiles and lists stay in both Klaviyo and Drawbridge \u2014 neither is deleted.",
1647
+ description: [
1648
+ "Connecting Klaviyo lets Drawbridge sync the contacts your campaigns collect into a Klaviyo list, so the people who enter a giveaway can be marketed to alongside the rest of your audience.",
1649
+ "You authorize Drawbridge from inside Klaviyo and can revoke that access there at any time. Drawbridge never sees or stores your Klaviyo password, and only asks for the permissions listed on the consent screen.",
1650
+ "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."
1651
+ ],
1652
+ // KEYED BY WHAT FAILED, not nested inside it. Errors are the thing most
1653
+ // likely to grow — resources.* has already earned somewhere to put "we
1654
+ // could not load your lists" — so a new area adds a key here rather than a
1655
+ // second errors object somewhere else.
1656
+ //
1657
+ // `connect` no longer exists as a container above: its only other member
1658
+ // was `redirect`, which moved to auth.oauth.urls with the rest of the
1659
+ // vendor's addresses.
1660
+ errors: {
1661
+ connect: {
1662
+ denied: "The Klaviyo authorization was declined, so nothing was connected.",
1663
+ invalid: "We couldn't complete the Klaviyo connection. Try connecting again."
1664
+ }
1665
+ },
1666
+ excerpt: "Sync the contacts your campaigns collect into a Klaviyo list.",
1667
+ // HOW TO CONNECT, in the merchant's words. Was `setup`, which nothing
1668
+ // rendered — four useful instructions no component displayed.
1669
+ guide: [
1670
+ "Press Connect. Drawbridge sends you to Klaviyo to approve access.",
1671
+ "Sign in to Klaviyo if you are not already, and choose the account to connect.",
1672
+ "Approve the permissions Klaviyo lists. You are returned here and the connection shows Active.",
1673
+ "You can revoke access at any time from Klaviyo, under Integrations."
1674
+ ]
1675
+ },
1676
+ // CAN A MERCHANT KEEP TWO OF THESE AT ONCE?
1677
+ //
1678
+ // Required, and false is a decision rather than a default. Shopify is
1679
+ // exclusive because a store maps to exactly one organization. Contact syncs
1680
+ // are destinations — someone can reasonably keep Klaviyo and Mailchimp both
1681
+ // current — so the exclusivity that once applied when these were SENDERS is
1682
+ // deliberately gone. That was removed once already; declaring it out loud is
1683
+ // what stops it coming back by inference.
1684
+ exclusive: false,
1685
+ feature: "organization:connection:klaviyo",
1686
+ fields: [
1687
+ {
1688
+ key: "account",
1689
+ label: "Klaviyo account"
1690
+ },
1691
+ {
1692
+ // The choices come from the merchant's own account, so the field names
1693
+ // the capability and the client composes the url.
1694
+ hook: "resources.audiences",
1695
+ input: "select",
1696
+ key: "list",
1697
+ label: "Klaviyo list",
1698
+ message: "Contacts your campaigns collect are synced into this list.",
1699
+ required: true,
1700
+ // Klaviyo's list endpoint carries no name filter, so the hook can only
1701
+ // match what it already fetched. A search box that searches one page is
1702
+ // worse than none, so the picker does not offer one.
1703
+ search: false
1704
+ }
1705
+ ],
1706
+ // WHAT KIND OF THING THIS IS. One field, not two — `category` said the same
1707
+ // thing and was read by nothing, while `group` was quietly doing double duty
1708
+ // as the mutual-exclusion key. The exclusion moved to `exclusive` above, so
1709
+ // this is purely how a connection is grouped and labelled.
1710
+ group: "contacts",
1711
+ // Nothing typed at connect. The consent returns the grant, and the account it
1712
+ // belongs to is read back from Klaviyo rather than asked for.
1713
+ hooks: {
1714
+ auth: {
1715
+ // Turn a fresh grant into settings worth showing. Without this the card
1716
+ // renders an empty "Klaviyo account" field, because the merchant is
1717
+ // never asked which account they connected — the consent already
1718
+ // decided it, and asking again would be a question we can answer.
1719
+ connect: async ({ fetcher, tokens }) => {
1720
+ var _a, _b, _c;
1721
+ const body = await api("/accounts", { fetcher, token: tokens.accessToken });
1722
+ const account = (_a = body == null ? void 0 : body.data) == null ? void 0 : _a[0];
1723
+ return {
1724
+ account: ((_c = (_b = account == null ? void 0 : account.attributes) == null ? void 0 : _b.contact_information) == null ? void 0 : _c.organization_name) || (account == null ? void 0 : account.id) || null,
1725
+ accountId: (account == null ? void 0 : account.id) || null
1726
+ };
1727
+ },
1728
+ // Revoke at KLAVIYO, not just locally. Forgetting our copy leaves the
1729
+ // grant live in the merchant's account, so a disconnect that looks
1730
+ // complete here still shows Drawbridge with access over there.
1731
+ //
1732
+ // Basic auth with our client, exactly like the token exchange — the
1733
+ // token being revoked is the subject, not the credential.
1734
+ disconnect: async ({ clientId, clientSecret, fetcher = fetch, manifest, settings }) => {
1735
+ const token = (settings == null ? void 0 : settings.refreshToken) || (settings == null ? void 0 : settings.accessToken);
1736
+ if (!token) return { revoked: false };
1737
+ const response = await fetcher(manifest.auth.oauth.urls.revoke, {
1738
+ body: new URLSearchParams({
1739
+ token,
1740
+ token_type_hint: (settings == null ? void 0 : settings.refreshToken) ? "refresh_token" : "access_token"
1741
+ }),
1742
+ headers: {
1743
+ authorization: "Basic " + Buffer.from(clientId + ":" + clientSecret).toString("base64"),
1744
+ "content-type": "application/x-www-form-urlencoded"
1745
+ },
1746
+ method: "POST",
1747
+ signal: AbortSignal.timeout(15e3)
1748
+ });
1749
+ return { revoked: response.ok };
1750
+ },
1751
+ // THE MINT IS THE PROBE. Asking "is this token still good" by
1752
+ // inspecting what we stored answers the wrong question — a grant
1753
+ // revoked inside Klaviyo still looks perfect in our database. Spending
1754
+ // the refresh token is the only thing that asks Klaviyo.
1755
+ //
1756
+ // It also keeps the grant warm against the 90-day idle window above.
1757
+ probe: async ({ clientId, clientSecret, fetcher, manifest, settings }) => {
1758
+ const token = await accessToken({
1759
+ clientId,
1760
+ clientSecret,
1761
+ fetcher,
1762
+ // Mint even if the stored token still looks good — a probe that
1763
+ // short-circuits never reaches Klaviyo and reports healthy on a
1764
+ // grant revoked an hour ago.
1765
+ force: true,
1766
+ manifest,
1767
+ settings
1768
+ });
1769
+ return { ok: Boolean(token) };
1770
+ },
1771
+ // Klaviyo scopes are fixed at app level and re-consented, not drifted.
1772
+ scopes: false,
1773
+ // KLAVIYO REQUIRES HTTP BASIC on the token endpoint and rejects the same
1774
+ // client_id/client_secret pair as body fields. Everything else about the
1775
+ // request is standard, so this is the shared implementation told the one
1776
+ // thing that differs — in Klaviyo's own file, beside the rest of what
1777
+ // makes Klaviyo unusual, rather than as a flag a caller has to know to
1778
+ // read.
1779
+ token: (args) => authToken({ ...args, basic: true })
1780
+ },
1781
+ // No commerce here. Klaviyo tracks orders, but Drawbridge's order data comes
1782
+ // from the store that took the money — a second source for the same event
1783
+ // is two answers to "did this person buy", and the one we can bill from is
1784
+ // the store's.
1785
+ commerce: false,
1786
+ // The verb the contacts.sync step points at. It does the work — including
1787
+ // writing the profile id back onto the lead — and returns what happened.
1788
+ contacts: {
1789
+ // Not yet. Suppression syncs an opt-out as unsubscribed, which is a
1790
+ // different thing from deleting the profile.
1791
+ remove: false,
1792
+ sync: async ({ contact, fetcher, lead, settings, suppressed, token }) => {
1793
+ var _a, _b, _c;
1794
+ const list = settings == null ? void 0 : settings.list;
1795
+ if (!list) return { message: "No Klaviyo list is chosen for this connection.", skipped: true };
1796
+ const email = ((_b = (_a = lead == null ? void 0 : lead.canonical) == null ? void 0 : _a.email) == null ? void 0 : _b.value) || (lead == null ? void 0 : lead.email);
1797
+ if (!email) return { message: "That lead has no email address to sync.", skipped: true };
1798
+ const totals = (contact == null ? void 0 : contact.totals) || {};
1799
+ const profile = await api("/profiles/", {
1800
+ fetcher,
1801
+ method: "POST",
1802
+ payload: {
1803
+ data: {
1804
+ attributes: {
1805
+ email,
1806
+ ...(lead == null ? void 0 : lead.name) && { first_name: String(lead.name).trim().split(/\s+/)[0] },
1807
+ properties: {
1808
+ drawbridge_campaigns: ((contact == null ? void 0 : contact.campaigns) || []).length,
1809
+ drawbridge_draws: totals.draws || 0,
1810
+ drawbridge_entries: totals.entries || 0,
1811
+ drawbridge_orders: totals.orders || 0,
1812
+ // Campaign-attributed, NOT lifetime. A merchant running
1813
+ // Shopify already has lifetime revenue in Klaviyo through
1814
+ // Klaviyo's own integration; what only we can say is how
1815
+ // much a campaign drove. Named so the two cannot be
1816
+ // mistaken for one another in a segment builder.
1817
+ drawbridge_revenue: totals.gross || 0
1818
+ }
1819
+ },
1820
+ type: "profile"
1821
+ }
1822
+ },
1823
+ token
1824
+ });
1825
+ const profileId = (_c = profile == null ? void 0 : profile.data) == null ? void 0 : _c.id;
1826
+ if (!profileId) return { message: "Klaviyo returned no profile id.", skipped: true };
1827
+ await api("/profile-subscription-bulk-create-jobs/", {
1828
+ fetcher,
1829
+ method: "POST",
1830
+ payload: {
1831
+ data: {
1832
+ attributes: {
1833
+ profiles: {
1834
+ data: [{
1835
+ attributes: {
1836
+ email,
1837
+ subscriptions: {
1838
+ email: { marketing: { consent: suppressed ? "UNSUBSCRIBED" : "SUBSCRIBED" } }
1839
+ }
1840
+ },
1841
+ type: "profile"
1842
+ }]
1843
+ }
1844
+ },
1845
+ relationships: { list: { data: { id: list, type: "list" } } },
1846
+ type: "profile-subscription-bulk-create-job"
1847
+ }
1848
+ },
1849
+ token
1850
+ });
1851
+ return {
1852
+ // Merged into `context` for later steps in this run.
1853
+ context: { klaviyoProfileId: profileId },
1854
+ message: suppressed ? "Synced to Klaviyo as unsubscribed \u2014 this contact has opted out." : "Synced to the Klaviyo list.",
1855
+ // Recorded on the run for support to read back, not a write
1856
+ // instruction — the hook has already written what it needed to.
1857
+ response: { klaviyoProfileId: profileId }
1858
+ };
1859
+ }
1860
+ },
1861
+ // A WHOLE DOMAIN CAN DECLINE AT ONCE. Klaviyo sends us nothing and we
1862
+ // register nothing with it, so listing four falses would be noise around a
1863
+ // single decision. Still explicit — absence would not say whether anybody
1864
+ // considered it.
1865
+ // Drawbridge sends its own notification email and SMS, and owns its own
1866
+ // segments — see the private `drawbridge` manifest. A vendor answering
1867
+ // these would be a second sender, which is the arrangement the platform
1868
+ // sender replaced.
1869
+ email: false,
1870
+ segment: false,
1871
+ sms: false,
1872
+ inbound: false,
1873
+ // Nothing to set up or tear down at the vendor: the grant is the whole
1874
+ // integration, and revoking it is auth.disconnect's job.
1875
+ lifecycle: false,
1876
+ resources: {
1877
+ // The lists a merchant can sync into, for the picker on their
1878
+ // connection.
1879
+ //
1880
+ // PAGINATED DELIBERATELY. Klaviyo caps page[size] at 10 and defaults to
1881
+ // it, so one call quietly returns the first ten lists and an account
1882
+ // with more shows a picker missing the one they wanted, with nothing to
1883
+ // indicate anything was cut.
1884
+ audiences: async ({ cursor, fetcher, limit = 100, search, token }) => {
1885
+ var _a, _b;
1886
+ const audiences = [];
1887
+ let next = cursor ? "/lists?page%5Bsize%5D=10&page%5Bcursor%5D=" + encodeURIComponent(cursor) : "/lists?page%5Bsize%5D=10";
1888
+ let pages = 0;
1889
+ while (next && audiences.length < limit && pages < 20) {
1890
+ const body = await api(next, { fetcher, token });
1891
+ for (const list of (body == null ? void 0 : body.data) || []) {
1892
+ audiences.push({ id: list.id, title: ((_a = list == null ? void 0 : list.attributes) == null ? void 0 : _a.name) || list.id });
1893
+ }
1894
+ const link = (_b = body == null ? void 0 : body.links) == null ? void 0 : _b.next;
1895
+ next = link ? String(link).replace(/^https:\/\/a\.klaviyo\.com\/api/, "") : null;
1896
+ pages = pages + 1;
1897
+ }
1898
+ const term = String((search == null ? void 0 : search.value) || "").trim().toLowerCase();
1899
+ return {
1900
+ items: term ? audiences.filter((entry) => entry.title.toLowerCase().includes(term)) : audiences,
1901
+ pageInfo: {
1902
+ endCursor: next,
1903
+ hasNextPage: Boolean(next)
1904
+ }
1905
+ };
1906
+ },
1907
+ // Klaviyo sells no products and mints no discount codes.
1908
+ prices: false,
1909
+ products: false,
1910
+ promotions: false
1911
+ },
1912
+ // Drawbridge posts to a merchant's own endpoint, never through a vendor.
1913
+ webhook: false
1914
+ },
1915
+ icon: klaviyo_default,
1916
+ requires: [
1917
+ "KLAVIYO_OAUTH_CLIENT_ID",
1918
+ "KLAVIYO_OAUTH_CLIENT_SECRET"
1919
+ ],
1920
+ slug: "klaviyo",
1921
+ // ONE OF THE FOUR STATES AND NOTHING ELSE — the reason sits in `tasks`, which
1922
+ // is already the merchant-facing copy channel and is already rendered.
1923
+ //
1924
+ // A grant with no list chosen is authenticated and useless. The list cannot be
1925
+ // part of the consent flow — enumerating lists needs the token the consent
1926
+ // returns — so it is always a second step, and the card must say Pending
1927
+ // rather than Active over nothing.
1928
+ //
1929
+ // Otherwise the credential's own verdict stands. A manifest can only ever
1930
+ // DOWNGRADE: it can see the settings, and it cannot see whether the grant was
1931
+ // revoked at Klaviyo an hour ago.
1932
+ //
1933
+ // Computed at read time rather than written, for the same reason
1934
+ // shopifyMissingScopes is: it becomes true the moment a merchant clears the
1935
+ // list, without waiting for something to notice and write it down.
1936
+ status: (data2) => {
1937
+ var _a;
1938
+ return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.list) ? data2.status : "pending";
1939
+ },
1940
+ steps: {
1941
+ contacts: {
1942
+ // A DECLARATION, not the work. It names the hook that does the work, and
1943
+ // says where that hook's values belong. Nested like the hooks, and the
1944
+ // nesting IS the name: this is `step.contacts.sync`, which is what a
1945
+ // workflow document stores.
1946
+ //
1947
+ // A function, so it can depend on what this deployment or this
1948
+ // merchant's connection knows — a static object would have to be true
1949
+ // for every deployment at publish time.
1950
+ sync: ({ data: data2 }) => {
1951
+ var _a;
1952
+ return {
1953
+ hook: "contacts.sync",
1954
+ // The account the merchant actually connected, read back by
1955
+ // auth.connect. The builder reads "Sync contact to Acme Co" rather
1956
+ // than a label that could be any of their Klaviyo accounts.
1957
+ key: "Sync contact to " + (((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.account) || "Klaviyo"),
1958
+ queue: "connection",
1959
+ // Nothing for a merchant to configure on the step itself — the list
1960
+ // is chosen once on the connection. Declared empty rather than
1961
+ // omitted, so "this step takes no settings" and "nobody thought about
1962
+ // settings" are different statements.
1963
+ settings: {},
1964
+ // BOTH triggers. lead.insert alone only ever fires for someone with
1965
+ // no history yet — a brand-new entrant has no orders and no revenue,
1966
+ // so a profile written then carries an email and nothing else.
1967
+ // Crossing into a segment is the moment the ranking data exists.
1968
+ triggers: ["lead.insert", "segment.contact.add"],
1969
+ // One source for cost: what the builder discloses before a merchant
1970
+ // adds this step, and what is charged when it runs.
1971
+ usage: { actions: 1 }
1972
+ };
1973
+ }
1974
+ }
1975
+ },
1976
+ // WHY, in the merchant's words, and what to do about it.
1977
+ tasks: (data2) => {
1978
+ var _a;
1979
+ return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.list) ? [] : [
1980
+ {
1981
+ message: "Choose which Klaviyo list your contacts should sync into. Until you do, nothing is being synced.",
1982
+ title: "Choose a list"
1983
+ }
1984
+ ];
1985
+ },
1986
+ title: "Klaviyo"
1987
+ };
1988
+
1989
+ // lib/connections/icons/mailchimp.js
1990
+ var mailchimp_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
1991
+ <rect width="500" height="500" fill="#FFE01B"/>
1992
+ <path d="M310.633 243.561C312.49 243.336 314.249 243.308 315.882 243.561C316.81 241.394 316.979 237.665 316.149 233.598C314.882 227.561 313.18 223.917 309.662 224.508C306.13 225.071 305.989 229.433 307.269 235.47C307.973 238.847 309.24 241.746 310.633 243.561ZM280.392 248.332C282.925 249.429 284.473 250.147 285.05 249.542C285.458 249.148 285.345 248.36 284.74 247.375C283.112 245.042 280.844 243.229 278.211 242.154C275.397 240.982 272.328 240.556 269.301 240.916C266.274 241.275 263.391 242.41 260.93 244.209C259.256 245.447 257.666 247.15 257.863 248.191C257.961 248.515 258.186 248.782 258.777 248.895C260.17 249.049 265.025 246.587 270.64 246.249C274.608 245.968 277.859 247.206 280.392 248.332ZM275.312 251.216C272.047 251.737 270.232 252.807 269.078 253.848C268.079 254.72 267.488 255.649 267.488 256.339L267.741 256.93L268.262 257.127C269.008 257.127 270.668 256.479 270.668 256.479C275.228 254.861 278.253 255.044 281.25 255.382C282.897 255.579 283.671 255.663 284.037 255.1C284.135 254.931 284.29 254.608 283.938 254.059C283.15 252.778 279.843 250.682 275.312 251.216ZM300.416 261.855C302.654 262.953 305.102 262.502 305.904 260.884C306.735 259.266 305.567 257.056 303.329 255.973C301.106 254.861 298.643 255.283 297.841 256.902C297.039 258.52 298.207 260.757 300.416 261.855ZM314.742 249.317C312.94 249.289 311.449 251.259 311.393 253.764C311.35 256.254 312.8 258.281 314.615 258.295C316.43 258.323 317.922 256.339 317.964 253.862C318.006 251.385 316.571 249.359 314.742 249.317ZM193.103 294.108C192.653 293.545 191.907 293.7 191.189 293.897C190.683 293.995 190.12 294.136 189.515 294.122C188.909 294.134 188.308 293.998 187.767 293.726C187.225 293.454 186.757 293.054 186.405 292.56C185.575 291.294 185.617 289.394 186.546 287.241L186.968 286.27C188.431 283.019 190.838 277.559 188.122 272.367C187.234 270.534 185.908 268.948 184.261 267.75C182.614 266.553 180.697 265.78 178.679 265.5C176.772 265.256 174.835 265.469 173.026 266.123C171.218 266.776 169.591 267.85 168.28 269.257C164.284 273.661 163.679 279.684 164.439 281.823C164.734 282.611 165.184 282.822 165.494 282.864C166.169 282.963 167.169 282.456 167.802 280.754L167.999 280.219C168.28 279.318 168.801 277.63 169.659 276.307C170.717 274.689 172.375 273.558 174.267 273.162C176.159 272.766 178.131 273.138 179.749 274.196C182.563 276.039 183.619 279.473 182.423 282.752C181.803 284.455 180.804 287.691 181.015 290.351C181.466 295.74 184.815 297.907 187.77 298.175C190.669 298.273 192.695 296.655 193.216 295.459C193.511 294.713 193.258 294.277 193.103 294.108Z" fill="#231E15"/>
1993
+ <path d="M360.476 284.243C360.35 283.835 359.618 281.204 358.647 278.052L356.621 272.648C360.575 266.696 360.645 261.405 360.124 258.393C359.531 254.519 357.693 250.944 354.89 248.205C351.766 244.94 345.363 241.563 336.385 239.044L331.671 237.736C331.643 237.524 331.418 226.619 331.235 221.933C331.08 218.555 330.798 213.264 329.152 208.058C327.182 200.993 323.791 194.858 319.527 190.876C331.277 178.717 338.594 165.307 338.58 153.81C338.538 131.703 311.379 124.976 277.902 138.851L270.824 141.863C270.795 141.835 258.004 129.283 257.821 129.128C219.63 95.8334 100.327 228.476 138.49 260.687L146.835 267.737C144.581 273.775 143.781 280.259 144.499 286.664C145.414 295.543 149.973 304.029 157.375 310.6C164.411 316.82 173.684 320.788 182.648 320.774C197.494 354.998 231.408 375.965 271.175 377.161C313.842 378.427 349.641 358.403 364.67 322.435C365.641 319.916 369.806 308.546 369.806 298.513C369.792 288.409 364.093 284.229 360.476 284.243ZM185.913 311.149C184.613 311.381 183.293 311.48 181.973 311.445C169.083 311.079 155.166 299.483 153.787 285.735C152.253 270.537 160.02 258.829 173.783 256.071C175.415 255.72 177.414 255.537 179.552 255.635C187.264 256.085 198.606 261.996 201.209 278.784C203.517 293.63 199.858 308.785 185.913 311.149ZM171.545 246.953C163.179 248.499 155.744 253.244 150.817 260.18C148.045 257.873 142.909 253.426 142.008 251.681C134.635 237.693 150.043 210.478 160.823 195.111C187.405 157.145 229.086 128.424 248.393 133.603C251.517 134.503 261.902 146.563 261.902 146.563C261.902 146.563 242.623 157.244 224.724 172.16C200.646 190.735 182.423 217.697 171.545 246.953ZM306.792 305.464C306.937 305.403 307.057 305.295 307.134 305.157C307.211 305.019 307.239 304.86 307.214 304.704C307.205 304.61 307.178 304.519 307.133 304.436C307.088 304.353 307.027 304.28 306.954 304.221C306.88 304.162 306.796 304.118 306.705 304.092C306.614 304.066 306.519 304.059 306.426 304.071C306.426 304.071 286.246 307.054 267.179 300.089C269.247 293.348 274.792 295.754 283.137 296.444C296.108 297.209 309.116 295.802 321.623 292.279C330.25 289.788 341.592 284.905 350.401 277.953C353.384 284.497 354.425 291.674 354.425 291.674C354.425 291.674 356.719 291.265 358.647 292.447C360.476 293.573 361.799 295.895 360.898 301.89C359.027 313.119 354.271 322.224 346.235 330.611C341.236 336.036 335.277 340.492 328.659 343.754C324.983 345.691 321.151 347.32 317.205 348.623C286.964 358.487 256.006 347.638 246.029 324.321C245.224 322.535 244.556 320.691 244.03 318.804C239.781 303.438 243.383 285.032 254.655 273.408C255.372 272.676 256.09 271.804 256.09 270.706C256.09 269.806 255.499 268.835 255.007 268.131C251.066 262.418 237.374 252.666 240.132 233.795C242.088 220.23 253.951 210.689 265.012 211.252L267.826 211.421C272.611 211.702 276.79 212.307 280.73 212.49C287.344 212.758 293.268 211.801 300.304 205.947C302.683 203.949 304.582 202.246 307.791 201.711C308.128 201.627 308.973 201.359 310.647 201.416C312.365 201.485 314.032 202.015 315.474 202.949C321.103 206.693 321.905 215.783 322.214 222.439C322.383 226.225 322.848 235.414 322.988 238.031C323.354 244.054 324.944 244.912 328.125 245.954C329.94 246.573 331.615 246.995 334.077 247.713C341.521 249.781 345.968 251.934 348.754 254.65C350.198 256.049 351.13 257.893 351.4 259.885C352.315 266.316 346.432 274.252 330.925 281.457C313.954 289.324 293.367 291.322 279.154 289.732L274.173 289.169C262.774 287.649 256.315 302.34 263.14 312.402C267.545 318.889 279.52 323.11 291.523 323.11C319.006 323.139 340.142 311.402 348.023 301.242L348.642 300.356C349.008 299.765 348.712 299.469 348.22 299.779C341.817 304.169 313.279 321.619 282.771 316.384C282.771 316.384 279.056 315.765 275.678 314.442C273.005 313.429 267.362 310.811 266.686 305.042C291.27 312.683 306.792 305.478 306.792 305.464ZM220.671 194.971C230.127 184.051 241.765 174.538 252.206 169.219C252.558 169.022 252.938 169.43 252.741 169.754C251.46 172 250.476 174.403 249.814 176.902C249.73 177.282 250.138 177.592 250.461 177.353C256.963 172.934 268.248 168.192 278.155 167.601C278.251 167.584 278.351 167.601 278.436 167.65C278.521 167.698 278.586 167.775 278.621 167.866C278.656 167.957 278.658 168.058 278.627 168.151C278.596 168.244 278.533 168.323 278.451 168.375C276.809 169.634 275.342 171.105 274.088 172.751C273.891 173.032 274.074 173.44 274.426 173.44C281.378 173.483 291.186 175.903 297.56 179.491C297.982 179.745 297.673 180.575 297.209 180.462C287.527 178.253 271.724 176.564 255.288 180.575C240.597 184.149 229.396 189.666 221.248 195.618C220.826 195.899 220.333 195.351 220.671 194.971Z" fill="#231E15"/>
1994
+ </svg>`;
1995
+
1996
+ // lib/connections/mailchimp.js
1997
+ var base = (dc) => {
1998
+ if (!dc) throw new Error("This Mailchimp connection has no data centre stored, so there is no host to call");
1999
+ return "https://" + dc + ".api.mailchimp.com/3.0";
2000
+ };
2001
+ var mailchimp_default2 = {
2002
+ // OAUTH 2, authorization code. Every url below is quoted from
2003
+ // mailchimp.com/developer/marketing/guides/access-user-data-oauth-2/ rather
2004
+ // than remembered.
2005
+ //
2006
+ // THE METADATA CALL IS MAILCHIMP'S QUIRK and cannot be skipped: an access
2007
+ // token alone cannot call the Marketing API, because every account lives
2008
+ // behind a data-centre prefix (us1, us19...) that only GET
2009
+ // login.mailchimp.com/oauth2/metadata returns — and every subsequent request
2010
+ // needs it in the HOST. That is why auth.connect below is a real function:
2011
+ // the standard exchange does not know where to send anything afterwards.
2012
+ //
2013
+ // No PKCE. No scopes — the docs describe none. And no refresh token: "Mailchimp
2014
+ // Marketing access tokens do not expire, so you don't need to use a
2015
+ // refresh_token", so tokenSettings stores no expiry and isStale reads that as
2016
+ // nothing to refresh toward.
2017
+ //
2018
+ // auth.token stays false: the exchange is POST form-encoded with grant_type,
2019
+ // client_id, client_secret, redirect_uri and code, which is exactly the
2020
+ // runner's default — nothing to wrap.
2021
+ auth: {
2022
+ oauth: {
2023
+ client: {
2024
+ id: "MAILCHIMP_OAUTH_CLIENT_ID",
2025
+ secret: "MAILCHIMP_OAUTH_CLIENT_SECRET"
2026
+ },
2027
+ urls: {
2028
+ authorize: "https://login.mailchimp.com/oauth2/authorize",
2029
+ redirect: "/api/connection/mailchimp/callback",
2030
+ token: "https://login.mailchimp.com/oauth2/token"
2031
+ }
2032
+ },
2033
+ type: "oauth"
2034
+ },
2035
+ // EVERYTHING A MERCHANT READS. `errors` belongs in here rather than at the
2036
+ // top level because the connection DOCUMENT carries its own `errors` array
2037
+ // and the document is spread OVER the resolved manifest downstream — a
2038
+ // top-level one would be replaced by that array and never render.
2039
+ content: {
2040
+ confirm: "Disconnecting removes Drawbridge's stored Mailchimp access. You can also remove Drawbridge from the Authorized Apps page in your Mailchimp account. Your contacts stay in both Drawbridge and Mailchimp \u2014 neither list is deleted.",
2041
+ description: [
2042
+ "Drawbridge no longer sends email through Mailchimp. Notification email now sends from Drawbridge itself, and verifying a domain under Networking in your organization settings puts your own brand in the from line.",
2043
+ "This connection is becoming the way your Drawbridge contacts sync into a Mailchimp audience. Audience syncing is not live yet, so connecting today does nothing except choose the audience it will use when it ships."
2044
+ ],
2045
+ excerpt: "Sync your Drawbridge contacts into a Mailchimp audience.",
2046
+ guide: [
2047
+ "Press Connect. Drawbridge sends you to Mailchimp to approve access.",
2048
+ "Sign in to Mailchimp if you are not already, and choose the account to connect.",
2049
+ "You come back here to pick the audience your contacts should sync into."
2050
+ ]
2051
+ },
2052
+ // Mailchimp and SendGrid shared a group while they were SENDERS, where an org
2053
+ // picking two providers to send the same mail was meaningless. As contact
2054
+ // syncs they are destinations, and a merchant could reasonably keep several
2055
+ // up to date, so the exclusivity is gone.
2056
+ exclusive: false,
2057
+ feature: "organization:connection:mailchimp",
2058
+ fields: [
2059
+ {
2060
+ input: "select",
2061
+ key: "audience",
2062
+ label: "Mailchimp audience",
2063
+ message: "Contacts your campaigns collect are synced into this audience.",
2064
+ hook: "resources.audiences",
2065
+ required: true,
2066
+ // Mailchimp's /lists takes no name filter either — same reason.
2067
+ search: false
2068
+ }
2069
+ ],
2070
+ group: "contacts",
2071
+ // A HOOK'S VALUE IS ITS ANSWER. A key is stored and can be removed; nothing
2072
+ // else is built yet, because audience sync has not shipped. Every false here
2073
+ // is "not yet" rather than "never" — when the sync lands, probe and
2074
+ // contacts.sync are the first to flip.
2075
+ hooks: {
2076
+ auth: {
2077
+ // WHERE THE ACCOUNT LIVES. Not enrichment — without this the connection
2078
+ // is unusable, because the Marketing API host is per-account and only
2079
+ // this call knows it. The callback merges what this returns into the
2080
+ // stored settings, which is how `dc` reaches every later request.
2081
+ //
2082
+ // The header here is `OAuth <token>`, not Bearer — that is specific to
2083
+ // the metadata endpoint. Marketing API calls take Bearer; see the
2084
+ // audiences hook.
2085
+ connect: async ({ fetcher = fetch, tokens }) => {
2086
+ const response = await fetcher("https://login.mailchimp.com/oauth2/metadata", {
2087
+ headers: {
2088
+ authorization: "OAuth " + (tokens == null ? void 0 : tokens.accessToken)
2089
+ },
2090
+ signal: AbortSignal.timeout(15e3)
2091
+ });
2092
+ if (!response.ok) {
2093
+ throw Object.assign(
2094
+ new Error("Mailchimp would not say which data centre this account is on (" + response.status + ")"),
2095
+ { status: response.status }
2096
+ );
2097
+ }
2098
+ const body = await response.json();
2099
+ if (!(body == null ? void 0 : body.dc)) throw new Error("Mailchimp returned no data centre for this account");
2100
+ return { dc: body.dc };
2101
+ },
2102
+ // Nothing to call. A merchant revokes Drawbridge from Mailchimp's own
2103
+ // Authorized Apps page; the docs describe no revocation endpoint for us
2104
+ // to call on their behalf.
2105
+ disconnect: false,
2106
+ probe: false,
2107
+ scopes: false,
2108
+ // The plain exchange. Mailchimp takes the client as FORM FIELDS
2109
+ // (grant_type, client_id, client_secret, redirect_uri, code), which is
2110
+ // the runner's default — so no `basic : true` as Klaviyo needs.
2111
+ //
2112
+ // build() requires an oauth manifest to name this explicitly rather than
2113
+ // letting it default, which caught this file declaring `false` on the
2114
+ // first import after the conversion.
2115
+ token: authToken
2116
+ },
2117
+ commerce: false,
2118
+ contacts: { remove: false, sync: false },
2119
+ // Drawbridge sends its own notification email and SMS, and owns its own
2120
+ // segments — see the private `drawbridge` manifest. A vendor answering
2121
+ // these would be a second sender, which is the arrangement the platform
2122
+ // sender replaced.
2123
+ email: false,
2124
+ segment: false,
2125
+ sms: false,
2126
+ inbound: false,
2127
+ lifecycle: false,
2128
+ resources: {
2129
+ // The audiences a merchant can sync into, for the picker on their
2130
+ // connection.
2131
+ //
2132
+ // count DEFAULTS TO 10 and maxes at 1000 (Mailchimp's own OpenAPI spec),
2133
+ // so leaving it unset returns the first ten audiences and looks entirely
2134
+ // successful — the same silent truncation Klaviyo has, at a different
2135
+ // number. Paged against total_items so an account past a thousand still
2136
+ // resolves.
2137
+ audiences: async ({ cursor, fetcher = fetch, limit = 100, search, settings, token }) => {
2138
+ const dc = settings == null ? void 0 : settings.dc;
2139
+ const count = Math.min(limit, 1e3);
2140
+ const offset = Number(cursor || 0);
2141
+ const response = await fetcher(
2142
+ base(dc) + "/lists?count=" + count + "&offset=" + offset + "&fields=lists.id,lists.name,total_items",
2143
+ {
2144
+ headers: { authorization: "Bearer " + token },
2145
+ signal: AbortSignal.timeout(15e3)
2146
+ }
2147
+ );
2148
+ if (!response.ok) {
2149
+ throw Object.assign(
2150
+ new Error("Mailchimp refused the request (" + response.status + ")"),
2151
+ { status: response.status }
2152
+ );
2153
+ }
2154
+ const body = await response.json();
2155
+ const audiences = ((body == null ? void 0 : body.lists) || []).map((list) => ({ id: list.id, title: (list == null ? void 0 : list.name) || list.id }));
2156
+ const term = String((search == null ? void 0 : search.value) || "").trim().toLowerCase();
2157
+ const items = term ? audiences.filter((entry) => entry.title.toLowerCase().includes(term)) : audiences;
2158
+ const nextOffset = offset + count;
2159
+ const more = nextOffset < Number((body == null ? void 0 : body.total_items) || 0);
2160
+ return {
2161
+ items,
2162
+ pageInfo: {
2163
+ endCursor: more ? String(nextOffset) : null,
2164
+ hasNextPage: more
2165
+ }
2166
+ };
2167
+ },
2168
+ prices: false,
2169
+ products: false,
2170
+ promotions: false
2171
+ },
2172
+ // Drawbridge posts to a merchant's own endpoint, never through a vendor.
2173
+ webhook: false
2174
+ },
2175
+ icon: mailchimp_default,
2176
+ // The OAuth client this deployment registered. Without both, the vendor drops
2177
+ // out of availableConnections rather than offering a Connect button that
2178
+ // cannot complete.
2179
+ requires: [
2180
+ "MAILCHIMP_OAUTH_CLIENT_ID",
2181
+ "MAILCHIMP_OAUTH_CLIENT_SECRET"
2182
+ ],
2183
+ slug: "mailchimp",
2184
+ // A key with no audience chosen is authenticated and inert. Mailchimp also
2185
+ // needs its merge fields created on that audience before any Drawbridge total
2186
+ // can be written to a member — unlike Klaviyo, its custom fields are not
2187
+ // schemaless — so the audience must be picked before lifecycle.register has
2188
+ // anything to register against.
2189
+ status: (data2) => {
2190
+ var _a;
2191
+ return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.audience) ? data2.status : "pending";
2192
+ },
2193
+ // No steps: audience sync has not shipped, so this vendor contributes nothing
2194
+ // to a workflow yet. An empty steps object is the honest declaration — the
2195
+ // catalog renders the connection, and no builder offers a step it cannot run.
2196
+ steps: {},
2197
+ tasks: (data2) => {
2198
+ var _a;
2199
+ return [
2200
+ ...((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.audience) ? [] : [
2201
+ {
2202
+ message: "Choose which Mailchimp audience your contacts should sync into. Until you do, nothing is being synced.",
2203
+ title: "Choose an audience"
2204
+ }
2205
+ ],
2206
+ {
2207
+ message: "Contact syncing to Mailchimp audiences has not shipped yet, and this connection no longer sends your email. Nothing is being sent to Mailchimp right now.",
2208
+ title: "Audience sync not available yet",
2209
+ type: "warning"
2210
+ }
2211
+ ];
2212
+ },
2213
+ title: "Mailchimp"
2214
+ };
2215
+
2216
+ // lib/connections/icons/shopify.js
2217
+ var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
2218
+ <rect width="500" height="500" fill="white"/>
2219
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M309.524 407.192L308.799 128.423C306.921 126.545 303.258 127.112 301.827 127.531L292.29 130.487C291.113 126.613 289.585 122.854 287.726 119.258C280.959 106.337 271.069 99.5052 259.096 99.4866H259.059C258.259 99.4866 257.469 99.5609 256.67 99.626L256.577 99.6353C256.231 99.2089 255.871 98.7935 255.499 98.3897C250.293 92.8125 243.601 90.0889 235.588 90.3213C220.139 90.7675 204.755 101.941 192.271 121.786C183.487 135.757 176.823 153.298 174.917 166.878L144.493 176.313C135.542 179.129 135.263 179.408 134.082 187.858C133.199 194.253 109.766 375.69 109.766 375.69L306.159 409.692L309.524 407.192ZM245.181 103.065C242.569 101.346 239.511 100.546 235.885 100.621C212.033 101.308 191.23 138.611 185.923 163.467L208.771 156.384L212.851 155.119C215.845 139.336 223.355 122.957 233.181 112.416C236.616 108.639 240.671 105.477 245.172 103.065H245.181ZM224.145 151.615L256.94 141.446C257.042 132.894 256.112 120.252 251.836 111.329C247.282 113.207 243.452 116.497 240.7 119.444C233.329 127.373 227.315 139.466 224.155 151.615H224.145ZM267.211 138.267L282.455 133.536C280.02 125.616 274.238 112.342 262.517 110.111C266.161 119.527 267.099 130.431 267.211 138.267Z" fill="#95BF47"/>
2220
+ <path d="M353.528 149.156C352.356 149.063 329.657 148.709 329.657 148.709C329.657 148.709 310.666 130.249 308.789 128.362C308.062 127.691 307.141 127.268 306.158 127.153V409.64L391.257 388.456C391.257 388.456 356.53 153.366 356.307 151.758C356.199 151.075 355.866 150.448 355.361 149.976C354.856 149.505 354.216 149.216 353.528 149.156Z" fill="#5E8E3E"/>
2221
+ <path d="M258.993 193.019L249.103 230.052C249.103 230.052 238.079 225.023 225 225.85C205.833 227.059 205.628 239.171 205.824 242.21C206.865 258.756 250.376 262.381 252.821 301.171C254.745 331.688 236.656 352.574 210.592 354.21C179.313 356.19 162.089 337.711 162.089 337.711L168.716 309.472C168.716 309.472 186.052 322.569 199.921 321.686C208.993 321.119 212.228 313.738 211.903 308.514C210.536 286.921 175.102 288.185 172.862 252.695C170.985 222.811 190.57 192.554 233.803 189.821C250.46 188.762 258.993 193.028 258.993 193.028" fill="white"/>
2222
+ </svg>`;
2223
+
2224
+ // lib/connections/inbound.js
2225
+ import { createHmac, timingSafeEqual } from "crypto";
2226
+ var verifySignature = ({ body, descriptor, headers }) => {
2227
+ const provided = headers[descriptor.headers.signature];
2228
+ if (!provided) {
2229
+ throw Object.assign(new Error("Missing webhook signature"), { status: 401 });
2230
+ }
2231
+ const digest = createHmac(descriptor.signature.algorithm, process.env[descriptor.signature.secret]).update(body).digest(descriptor.signature.encoding);
2232
+ const digestBuffer = Buffer.from(digest, descriptor.signature.encoding);
2233
+ const providedBuffer = Buffer.from(provided, descriptor.signature.encoding);
2234
+ if (digestBuffer.length !== providedBuffer.length || !timingSafeEqual(digestBuffer, providedBuffer)) {
2235
+ throw Object.assign(new Error("Invalid webhook signature"), { status: 401 });
2236
+ }
2237
+ return JSON.parse(body.toString());
2238
+ };
2239
+ var readEventHeader = ({ descriptor, headers }) => headers[descriptor.headers.event];
2240
+
2241
+ // lib/connections/shopify.js
2242
+ var inbound = {
2243
+ headers: {
2244
+ event: "x-shopify-topic",
2245
+ id: "x-shopify-webhook-id",
2246
+ shop: "x-shopify-shop-domain",
2247
+ signature: "x-shopify-hmac-sha256"
2248
+ },
2249
+ signature: {
2250
+ algorithm: "sha256",
2251
+ encoding: "base64",
2252
+ secret: "SHOPIFY_API_SECRET"
2253
+ }
2254
+ };
2255
+ var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
2256
+ "customers/data_request",
2257
+ "customers/redact",
2258
+ "shop/redact"
2259
+ ]);
2260
+ var shopify_default2 = {
2261
+ // INSTALL, not oauth. The grant is an OAuth grant, but the merchant never
2262
+ // sees a consent screen we sent them to -- they start at the App Store, and
2263
+ // the install completes inside Shopify admin without redirecting back. A
2264
+ // Connect button here would be lying about where connecting happens.
2265
+ auth: {
2266
+ type: "install"
2267
+ },
2268
+ // EVERYTHING A MERCHANT READS.
2269
+ //
2270
+ // `errors` is in here rather than at the top level, and that is not a
2271
+ // preference: the connection DOCUMENT carries its own `errors` array of
2272
+ // scope-drift entries, and the document is spread OVER the resolved manifest
2273
+ // downstream — a top-level one would be replaced by that array and never
2274
+ // render.
2275
+ //
2276
+ // `connect` no longer exists as a container. Its other member was `redirect`,
2277
+ // which is a URL and now sits with the vendor's other addresses.
2278
+ content: {
2279
+ confirm: "Disconnecting deactivates all products from this store, drafts any advertisements that use them, disables Shopify steps in your workflows until you reconnect, and stops revenue tracking for this organization.",
2280
+ description: [
2281
+ "Installing the Drawbridge app from the Shopify App Store links your store to a single Drawbridge organization and makes your product catalog available inside Drawbridge, so you can feature products in your campaigns and advertisements.",
2282
+ "Drawbridge attributes orders that originate from your campaigns \u2014 matched through cart parameters and lead-mapped discount codes \u2014 so you can see the revenue each campaign drives.",
2283
+ "On connect, Drawbridge registers webhooks for product and order updates to keep your catalog and revenue in sync. Disconnecting removes those webhooks and unlinks the resources."
2284
+ ],
2285
+ errors: {
2286
+ connect: {
2287
+ conflict: "This store is already connected to another Drawbridge organization.",
2288
+ currency: "This store settles in a currency we can't bill yet. Connect a store with a supported settlement currency.",
2289
+ invalid: "We couldn't verify the install. Please try connecting again from the Shopify App Store."
2290
+ }
2291
+ },
2292
+ excerpt: "Connect your Shopify store to feature products in your campaigns and track conversions.",
2293
+ guide: [
2294
+ "Open the Drawbridge listing on the Shopify App Store.",
2295
+ "Install the app on the store you want to connect. It opens in Shopify admin and stays there.",
2296
+ "Choose a plan when Shopify asks. The connection shows Pending until you do, then Active.",
2297
+ "Come back here \u2014 the connections list updates on its own once the install lands."
2298
+ ],
2299
+ // Names where the link GOES rather than what it does: installing happens on
2300
+ // the App Store listing, and the dashboard must never imply a store can be
2301
+ // linked from inside it.
2302
+ redirect: {
2303
+ env: "SHOPIFY_APP_LISTING_URL",
2304
+ title: "View on the Shopify App Store"
2305
+ }
2306
+ },
2307
+ // ONE STORE PER ORGANIZATION. Two Shopify stores on one org would give every
2308
+ // attributed order two possible sources.
2309
+ exclusive: true,
2310
+ feature: "organization:connection:shopify",
2311
+ fields: [
2312
+ {
2313
+ // `shop` on the connection record wins when present — it is written by
2314
+ // the install, while settings.domain is the stored copy.
2315
+ from: "shop",
2316
+ key: "domain",
2317
+ label: "Store domain"
2318
+ }
2319
+ ],
2320
+ // Was `category : 'commerce'` AND `group : 'ecommerce'` — two words for one
2321
+ // fact, which left nobody able to say which one a page read.
2322
+ group: "commerce",
2323
+ // verify and event lean entirely on the shared HMAC helper — Shopify's scheme
2324
+ // is exactly the shape it covers, so there is nothing vendor-specific to
2325
+ // write for either. receive is the one hook that genuinely differs by
2326
+ // channel: /events buffers whatever arrives with the shop domain stamped on;
2327
+ // /compliance enforces the topic allowlist above, because answering one late
2328
+ // is a legal deadline rather than a retry.
2329
+ hooks: {
2330
+ auth: {
2331
+ // The install completes inside Shopify admin; the api's callback stores
2332
+ // what it hands back. auth.probe is false deliberately: the health check
2333
+ // re-registers rather than answering "is this token still good", and
2334
+ // scope drift is its own hook because a token can be perfectly valid
2335
+ // while the grant is too narrow.
2336
+ //
2337
+ // connect and disconnect are FALSE rather than `{}`: there is nothing to
2338
+ // call on either side. The install already hands the callback everything
2339
+ // it stores, and a Shopify grant is withdrawn by UNINSTALLING the app in
2340
+ // Shopify admin — which Drawbridge learns about from the app_uninstalled
2341
+ // webhook rather than by asking. `{}` claimed a body implemented
2342
+ // elsewhere; none exists, and none could.
2343
+ connect: false,
2344
+ disconnect: false,
2345
+ probe: false,
2346
+ // WHETHER THE GRANT IS STILL WIDE ENOUGH. A token can be perfectly valid
2347
+ // and still too narrow — a deploy that adds a scope leaves every existing
2348
+ // install short of it, and no webhook fires to say so.
2349
+ //
2350
+ // The comparison is the vendor's, so it belongs here. Reading WHICH
2351
+ // scopes a store granted is not: that lives in the `shop` collection and
2352
+ // needs a controller, which is precisely what a hook in a published
2353
+ // package must not be handed. The caller reads the grant and passes the
2354
+ // string; this answers what is missing from it.
2355
+ //
2356
+ // `shopify` is injected for the same reason it is everywhere else — this
2357
+ // package cannot import @drawbridge/shopify, which depends on it.
2358
+ scopes: ({ scope, shopify }) => scope ? shopify.oauth.missingScopes(scope) : null,
2359
+ // Shopify's install grant is exchanged inside its own app flow, not
2360
+ // through the shared OAuth runner.
2361
+ token: false
2362
+ },
2363
+ // Implemented in drawbridge-sync, which owns the attribution and the
2364
+ // controllers it needs. Declared here so the steps below can point at them:
2365
+ // a step naming a hook the vendor does not implement is a workflow that
2366
+ // accepts the step and then silently does nothing.
2367
+ commerce: {
2368
+ code: {},
2369
+ customer: {},
2370
+ order: {},
2371
+ product: {}
2372
+ },
2373
+ contacts: { remove: false, sync: false },
2374
+ // verify and event lean entirely on the shared HMAC helper — Shopify's
2375
+ // scheme is exactly the shape it covers, so there is nothing vendor-specific
2376
+ // to write for either. receive is the one hook that genuinely differs by
2377
+ // channel: /events buffers whatever arrives with the shop domain stamped on;
2378
+ // /compliance enforces the topic allowlist above, because answering one late
2379
+ // is a legal deadline rather than a retry.
2380
+ // Drawbridge sends its own notification email and SMS, and owns its own
2381
+ // segments — see the private `drawbridge` manifest. A vendor answering
2382
+ // these would be a second sender, which is the arrangement the platform
2383
+ // sender replaced.
2384
+ email: false,
2385
+ segment: false,
2386
+ sms: false,
2387
+ inbound: {
2388
+ event: (args) => readEventHeader({ ...args, descriptor: inbound }),
2389
+ process: {},
2390
+ receive: ({ channel, event, headers, payload }) => {
2391
+ if (channel === "compliance" && !COMPLIANCE_TOPICS.has(event)) {
2392
+ throw Object.assign(new Error("Unrecognized compliance topic: " + event), { status: 401 });
2393
+ }
2394
+ return {
2395
+ // Compliance payloads already carry shop_domain in the body — Shopify's
2396
+ // own GDPR shape. The app-level event stream does not; that domain
2397
+ // lives only in the header, so it is stamped on here rather than left
2398
+ // for drawbridge-sync to reach into headers nobody hands it.
2399
+ data: channel === "compliance" ? payload : { ...payload, shop_domain: headers[inbound.headers.shop] || null },
2400
+ provider: { id: headers[inbound.headers.id] || null }
2401
+ };
2402
+ },
2403
+ verify: (args) => verifySignature({ ...args, descriptor: inbound })
2404
+ },
2405
+ lifecycle: { cleanup: {}, health: {}, register: {}, rehydrate: {} },
2406
+ resources: {
2407
+ audiences: false,
2408
+ // Shopify has no separate price resource — a price belongs to a product
2409
+ // variant and arrives with it, so there is nothing for prices to answer
2410
+ // that products does not already.
2411
+ prices: false,
2412
+ // WHAT THE VENDOR ANSWERS, shaped for a picker. Both of these were api
2413
+ // ROUTES — /organization/:organization/shopify/products and
2414
+ // .../connection/:id/shopify/discounts — vendor-named urls in a service
2415
+ // that is supposed to have none, reachable only by knowing the path.
2416
+ // They are the same two questions every other vendor answers through
2417
+ // resources.*, so they answer them the same way now.
2418
+ //
2419
+ // `shopify` is INJECTED: this package cannot import @drawbridge/shopify,
2420
+ // which depends on it. What arrives is the SDK's pure HTTP namespaces
2421
+ // and nothing else — no controller, no collection access. Resolving the
2422
+ // credential is the caller's job because it is Drawbridge's job: the
2423
+ // admin token refreshes and writes itself back, which is service work,
2424
+ // not vendor work.
2425
+ products: async ({ cursor, limit = 100, search, settings, shopify, sort }) => {
2426
+ var _a, _b, _c, _d;
2427
+ const products = await shopify.storefront.getProducts({
2428
+ cursor,
2429
+ domain: settings == null ? void 0 : settings.domain,
2430
+ limit: Number(limit),
2431
+ search: (search == null ? void 0 : search.value) || null,
2432
+ sort,
2433
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
2434
+ });
2435
+ return {
2436
+ items: ((products == null ? void 0 : products.edges) || []).map((edge) => edge.node),
2437
+ pageInfo: {
2438
+ endCursor: ((_a = products == null ? void 0 : products.pageInfo) == null ? void 0 : _a.endCursor) || null,
2439
+ hasNextPage: Boolean((_b = products == null ? void 0 : products.pageInfo) == null ? void 0 : _b.hasNextPage),
2440
+ hasPreviousPage: Boolean((_c = products == null ? void 0 : products.pageInfo) == null ? void 0 : _c.hasPreviousPage),
2441
+ startCursor: ((_d = products == null ? void 0 : products.pageInfo) == null ? void 0 : _d.startCursor) || null
2442
+ }
2443
+ };
2444
+ },
2445
+ promotions: async ({ cursor, limit = 100, search, settings, shopify }) => {
2446
+ var _a, _b;
2447
+ const discounts = await shopify.admin.getDiscounts({
2448
+ adminAccessToken: settings == null ? void 0 : settings.adminAccessToken,
2449
+ cursor,
2450
+ domain: settings == null ? void 0 : settings.domain,
2451
+ limit: Number(limit),
2452
+ search: (search == null ? void 0 : search.value) || null
2453
+ });
2454
+ return {
2455
+ // The GLOBAL id is what Shopify returns and the bare id is what a
2456
+ // picker stores, which is why the tail is taken here rather than by
2457
+ // each caller that happened to remember.
2458
+ items: ((discounts == null ? void 0 : discounts.edges) || []).map((edge) => {
2459
+ var _a2, _b2, _c;
2460
+ return {
2461
+ id: String(((_a2 = edge == null ? void 0 : edge.node) == null ? void 0 : _a2.id) || "").split("/").pop(),
2462
+ title: (_c = (_b2 = edge == null ? void 0 : edge.node) == null ? void 0 : _b2.codeDiscount) == null ? void 0 : _c.title
2463
+ };
2464
+ }),
2465
+ pageInfo: {
2466
+ endCursor: ((_a = discounts == null ? void 0 : discounts.pageInfo) == null ? void 0 : _a.endCursor) || null,
2467
+ hasNextPage: Boolean((_b = discounts == null ? void 0 : discounts.pageInfo) == null ? void 0 : _b.hasNextPage)
2468
+ }
2469
+ };
2470
+ }
2471
+ },
2472
+ // Drawbridge posts to a merchant's own endpoint, never through a vendor.
2473
+ webhook: false
2474
+ },
2475
+ icon: shopify_default,
2476
+ inbound,
2477
+ // THE DEEP LINK into this store's Drawbridge app inside Shopify admin.
2478
+ //
2479
+ // Here rather than in drawbridge-api, which had `slug === 'shopify' && {...}`
2480
+ // in the shared resolver — a hardcoded vendor branch in code every vendor runs
2481
+ // through, which is the arrangement these manifests exist to remove.
2482
+ //
2483
+ // Undefined until a shop is linked, so the Manage button only appears on a
2484
+ // connected connection. The app handle is NAMED by `requires` and read from
2485
+ // the env the resolver passes, never from process.env here.
2486
+ manage: (data2, env) => {
2487
+ var _a;
2488
+ const shop = (data2 == null ? void 0 : data2.shop) || ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.domain);
2489
+ return shop ? "https://admin.shopify.com/store/" + String(shop).replace(".myshopify.com", "") + "/apps/" + (env == null ? void 0 : env.SHOPIFY_APP_HANDLE) : void 0;
2490
+ },
2491
+ // A pre-launch integration: it only surfaces once the App Store listing
2492
+ // exists and the app is fully configured. Requiring all four means it can
2493
+ // never render half-configured — and absence of any one excludes the
2494
+ // connection AND every step below it.
2495
+ requires: [
2496
+ "SHOPIFY_API_KEY",
2497
+ "SHOPIFY_API_SECRET",
2498
+ "SHOPIFY_APP_LISTING_URL",
2499
+ "SHOPIFY_APP_HANDLE"
2500
+ ],
2501
+ slug: "shopify",
2502
+ // The install is the whole configuration — Shopify hands back the shop and
2503
+ // there is nothing further to choose. `shop` absent means the install did not
2504
+ // finish, which is a credential problem rather than a setup one, so the
2505
+ // stored status already says so.
2506
+ // Nothing to add — no setting can make this connection unusable, so the
2507
+ // credential's own verdict stands.
2508
+ status: (data2) => data2 == null ? void 0 : data2.status,
2509
+ // Step types name the CAPABILITY, not this vendor. A second store platform
2510
+ // implements the same four commerce steps, and the connection on the step
2511
+ // says which store it runs against — so a merchant sees one "Create
2512
+ // customer", not one per platform. The three connection.* steps are not
2513
+ // commerce at all: any vendor holding a rotating credential needs them.
2514
+ // Step types name the CAPABILITY, not this vendor. A second store platform
2515
+ // implements the same commerce steps, and the connection on the step says
2516
+ // which store it runs against — so a merchant sees one "Create customer", not
2517
+ // one per platform.
2518
+ //
2519
+ // Nested for readability and flattened to the stored name, at whatever depth:
2520
+ // steps.commerce.customer.insert is `step.commerce.customer.insert` on a
2521
+ // workflow document, and those strings cannot be renamed without a backfill.
2522
+ //
2523
+ // EVERY LEAF IS A FUNCTION so a step can read the merchant's own connection.
2524
+ // The bodies these point at still live in drawbridge-sync; moving them is the
2525
+ // next unit, and commerce.order.record is the one that decides whether the
2526
+ // shape holds — 569 lines and 15 controller calls.
2527
+ steps: {
2528
+ commerce: {
2529
+ code: {
2530
+ issue: () => ({
2531
+ hook: "commerce.code",
2532
+ key: "Issue a discount code",
2533
+ queue: "connection",
2534
+ settings: {
2535
+ discount: {
2536
+ required: true,
2537
+ shape: {
2538
+ id: { required: true, type: "string" }
2539
+ },
2540
+ type: "object"
2541
+ }
2542
+ },
2543
+ triggers: ["lead.insert"],
2544
+ usage: { actions: 1 }
2545
+ })
2546
+ },
2547
+ customer: {
2548
+ insert: () => ({
2549
+ hook: "commerce.customer",
2550
+ key: "Create customer",
2551
+ queue: "connection",
2552
+ settings: {},
2553
+ triggers: ["lead.insert"],
2554
+ usage: { actions: 1 }
2555
+ })
2556
+ },
2557
+ // SYSTEM STEPS: dispatched by drawbridge-sync itself rather than offered
2558
+ // in the builder, so they carry no trigger and no usage. Declared because
2559
+ // the routing table and the system-workflow descriptions both read here.
2560
+ order: {
2561
+ record: () => ({
2562
+ description: "Records an order and billing charge when a purchase is made via a Drawbridge campaign link.",
2563
+ hook: "commerce.order",
2564
+ key: "Shopify Order Tracking",
2565
+ queue: "connection",
2566
+ system: true
2567
+ })
2568
+ },
2569
+ product: {
2570
+ sync: () => ({
2571
+ description: "Syncs Shopify product data on webhook updates.",
2572
+ hook: "commerce.product",
2573
+ key: "Shopify Product Sync",
2574
+ queue: "connection",
2575
+ system: true
2576
+ })
2577
+ }
2578
+ },
2579
+ connection: {
2580
+ // Not a webhook monitor, despite the name it once carried. Webhooks are
2581
+ // declarative — declared in the app's toml, applied by Shopify to every
2582
+ // install — so nothing registers or checks them here. This rotates the
2583
+ // access token before Shopify's idle window closes, and reconciles the
2584
+ // scopes the store granted against the ones the app now needs.
2585
+ health: {
2586
+ check: () => ({
2587
+ description: "Keeps store access working \u2014 refreshes the access token before it goes stale and reports when the store's approved permissions fall behind.",
2588
+ hook: "lifecycle.health",
2589
+ key: "Shopify Connection Health",
2590
+ queue: "connection",
2591
+ system: true
2592
+ })
2593
+ },
2594
+ // Audit-only. The "Shopify Token Activity" system workflow lists these
2595
+ // for descriptive grouping, but its audit step docs are written manually
2596
+ // at OAuth time — the workflow is never dispatched. Routing is declared
2597
+ // defensively so that if it ever IS dispatched, the job lands on a real
2598
+ // queue and the handler lookup misses cleanly instead of throwing
2599
+ // "Unknown step type".
2600
+ token: {
2601
+ exchange: () => ({
2602
+ description: "Records the token exchange that completed an install. Audit only \u2014 never dispatched.",
2603
+ key: "Shopify Token Exchange",
2604
+ queue: "connection",
2605
+ system: true
2606
+ }),
2607
+ refresh: () => ({
2608
+ description: "Records a token rotation. Audit only \u2014 never dispatched.",
2609
+ key: "Shopify Token Refresh",
2610
+ queue: "connection",
2611
+ system: true
2612
+ })
2613
+ }
2614
+ }
2615
+ },
2616
+ // Shopify sits pending between the install landing and the merchant choosing a
2617
+ // plan, and nothing on our side can move it — so the card says what they need
2618
+ // to go and do rather than showing Pending with no next step.
2619
+ //
2620
+ // Scope drift is NOT here: drawbridge-sync writes it onto the connection
2621
+ // document, and the document's own warnings render beside these.
2622
+ tasks: (data2) => (data2 == null ? void 0 : data2.status) === "pending" ? [
2623
+ {
2624
+ message: "Open the Drawbridge app in your Shopify admin and choose a plan. The connection activates once Shopify confirms it.",
2625
+ title: "Choose a plan in Shopify"
2626
+ }
2627
+ ] : [],
2628
+ title: "Shopify"
2629
+ };
2630
+
2631
+ // lib/connections/webhook.js
2632
+ import crypto from "crypto";
2633
+
2634
+ // lib/safe-http.js
2635
+ import dns2 from "dns";
2636
+ import * as http2 from "http";
2637
+ import * as https2 from "https";
2638
+
2639
+ // lib/axios.js
2640
+ import axiosLib from "axios";
2641
+ import dns from "dns";
2642
+ import * as http from "http";
2643
+ import * as https from "https";
2644
+ import net from "net";
2645
+ var dnsLookup = dns.promises.lookup;
2646
+ var isBlockedIPv4 = (ip) => {
2647
+ const parts = ip.split(".").map(Number);
2648
+ if (parts.length !== 4 || parts.some((n) => Number.isNaN(n) || n < 0 || n > 255)) return true;
2649
+ const [a, b] = parts;
2650
+ if (a === 0) return true;
2651
+ if (a === 10) return true;
2652
+ if (a === 127) return true;
2653
+ if (a === 169 && b === 254) return true;
2654
+ if (a === 172 && b >= 16 && b <= 31) return true;
2655
+ if (a === 192 && b === 168) return true;
2656
+ if (a === 100 && b >= 64 && b <= 127) return true;
2657
+ if (a === 192 && b === 0) return true;
2658
+ if (a === 198 && (b === 18 || b === 19)) return true;
2659
+ if (a === 198 && b === 51) return true;
2660
+ if (a === 203 && b === 0) return true;
2661
+ if (a >= 224) return true;
2662
+ return false;
2663
+ };
2664
+ var isBlockedIPv6 = (ip) => {
2665
+ const lower = ip.toLowerCase();
2666
+ if (lower === "::1" || lower === "::") return true;
2667
+ if (lower.startsWith("fc") || lower.startsWith("fd")) return true;
2668
+ if (/^fe[89ab]/.test(lower)) return true;
2669
+ if (lower.startsWith("ff")) return true;
2670
+ if (lower.startsWith("::ffff:")) {
2671
+ const v4 = lower.slice(7);
2672
+ return isBlockedIPv4(v4);
2673
+ }
2674
+ ;
2675
+ return false;
2676
+ };
2677
+ var isBlockedIP = (ip) => {
2678
+ const version = net.isIP(ip);
2679
+ if (version === 4) return isBlockedIPv4(ip);
2680
+ if (version === 6) return isBlockedIPv6(ip);
2681
+ return true;
2682
+ };
2683
+ var axios = axiosLib.create({
2684
+ timeout: 3e4,
2685
+ httpAgent: new http.Agent({ keepAlive: true, maxSockets: 128 }),
2686
+ httpsAgent: new https.Agent({ keepAlive: true, maxSockets: 128 })
2687
+ });
2688
+
2689
+ // lib/safe-http.js
2690
+ var DEFAULT_TIMEOUT_MS2 = 15e3;
2691
+ var resolveSafeHost = async (url) => {
2692
+ const parsed = new URL(url);
2693
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
2694
+ throw new Error("Only http(s) URLs are allowed");
2695
+ }
2696
+ const records = await dns2.promises.lookup(parsed.hostname, { all: true });
2697
+ if (!(records == null ? void 0 : records.length)) {
2698
+ throw new Error("Host could not be resolved");
2699
+ }
2700
+ for (const record of records) {
2701
+ if (isBlockedIP(record.address)) {
2702
+ throw new Error("Host resolves to a blocked IP range");
2703
+ }
2704
+ }
2705
+ return { parsed, records };
2706
+ };
2707
+ var pinnedAgent = async (url) => {
2708
+ const { parsed, records } = await resolveSafeHost(url);
2709
+ const pinned = records[0];
2710
+ const lookup2 = (hostname, options, callback) => {
2711
+ if (options == null ? void 0 : options.all) {
2712
+ callback(null, [{ address: pinned.address, family: pinned.family }]);
2713
+ } else {
2714
+ callback(null, pinned.address, pinned.family);
2715
+ }
2716
+ };
2717
+ return {
2718
+ protocol: parsed.protocol,
2719
+ agent: parsed.protocol === "https:" ? new https2.Agent({ lookup: lookup2 }) : new http2.Agent({ lookup: lookup2 })
2720
+ };
2721
+ };
2722
+ var safeRequest = async ({
2723
+ body,
2724
+ headers = {},
2725
+ method = "GET",
2726
+ query,
2727
+ timeout = DEFAULT_TIMEOUT_MS2,
2728
+ type = "json",
2729
+ url
2730
+ }) => {
2731
+ const full = new URL(url);
2732
+ if (query) {
2733
+ Object.entries(query).forEach(([key, value]) => full.searchParams.set(key, value));
2734
+ }
2735
+ const { protocol, agent } = await pinnedAgent(full.toString());
2736
+ const isForm = type === "form";
2737
+ try {
2738
+ const response = await axios({
2739
+ method,
2740
+ url: full.toString(),
2741
+ headers: {
2742
+ "Content-Type": isForm ? "application/x-www-form-urlencoded" : "application/json",
2743
+ ...headers
2744
+ },
2745
+ ...body !== void 0 && {
2746
+ data: isForm ? new URLSearchParams(body).toString() : body
2747
+ },
2748
+ timeout,
2749
+ maxRedirects: 0,
2750
+ httpAgent: protocol === "http:" ? agent : void 0,
2751
+ httpsAgent: protocol === "https:" ? agent : void 0,
2752
+ responseType: "json",
2753
+ validateStatus: (status) => status >= 200 && status < 300
2754
+ });
2755
+ return response.data || null;
2756
+ } catch (error) {
2757
+ if (error == null ? void 0 : error.response) {
2758
+ const normalized = new Error(
2759
+ typeof error.response.data === "string" ? error.response.data : error.message || "Request failed"
2760
+ );
2761
+ normalized.status = error.response.status;
2762
+ normalized.response = error.response.data;
2763
+ throw normalized;
2764
+ }
2765
+ throw error;
2766
+ }
2767
+ };
2768
+
2769
+ // lib/connections/webhook.js
2770
+ var webhook_default = {
2771
+ // Connecting GENERATES the secret rather than storing one the merchant typed,
2772
+ // so the buttons say what actually happens.
2773
+ actions: {
2774
+ create: "Connect",
2775
+ update: "Regenerate secret"
2776
+ },
2777
+ // GENERATED. There is no third party and nothing to authenticate against --
2778
+ // connecting mints a secret rather than proving a credential.
2779
+ auth: {
2780
+ type: "generated"
2781
+ },
2782
+ // EVERYTHING A MERCHANT READS. `errors` would belong here too — the
2783
+ // connection DOCUMENT carries its own `errors` array and is spread OVER the
2784
+ // resolved manifest downstream, so a top-level one is replaced by that array.
2785
+ content: {
2786
+ confirm: "Disconnecting stops Drawbridge from sending signed webhook payloads to your endpoint.",
2787
+ description: [
2788
+ "Drawbridge can POST event payloads to your endpoint as activity happens in your account, so your own systems can react in real time.",
2789
+ "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."
2790
+ ],
2791
+ excerpt: "Sign outgoing webhook payloads with an HMAC secret to verify authenticity.",
2792
+ guide: [
2793
+ "Press Connect. Drawbridge generates a signing secret and shows it here.",
2794
+ "Copy the secret into your own endpoint.",
2795
+ "On each request, compute HMAC-SHA256 of the raw body using the secret and compare it against the X-Drawbridge-Signature header before acting on the payload."
2796
+ ]
2797
+ },
2798
+ // Nothing to be exclusive with — there is no second webhook vendor, and a
2799
+ // merchant with two endpoints is a step-level choice rather than a second
2800
+ // connection.
2801
+ exclusive: false,
2802
+ feature: "organization:connection:webhook",
2803
+ fields: [
2804
+ {
2805
+ // No `input`: Drawbridge generates this, the merchant never types it.
2806
+ // No `redact` either — it is shared with the merchant's own endpoint
2807
+ // rather than being a third-party credential, so it round-trips for
2808
+ // them to copy and configure.
2809
+ copy: true,
2810
+ key: "secret",
2811
+ label: "Signing secret"
2812
+ }
2813
+ ],
2814
+ group: "developer",
2815
+ // OUTBOUND ONLY. inbound.* is false because the direction is the point: we
2816
+ // sign and POST to the merchant's endpoint, they never call us. Every other
2817
+ // false follows from there being no third party to authenticate against —
2818
+ // connect generates a secret rather than proving a credential.
2819
+ hooks: {
2820
+ auth: {
2821
+ // FALSE, NOT {}. There is no vendor here at all — connecting mints a
2822
+ // secret and disconnecting clears it, both done by the api's own
2823
+ // handler. `{}` would promise a body implemented elsewhere, and none
2824
+ // exists or could.
2825
+ connect: false,
2826
+ disconnect: false,
2827
+ probe: false,
2828
+ scopes: false,
2829
+ // Nothing to mint. Connecting generates a secret; there is no vendor.
2830
+ token: false
2831
+ },
2832
+ commerce: false,
2833
+ contacts: { remove: false, sync: false },
2834
+ // Drawbridge sends its own notification email and SMS, and owns its own
2835
+ // segments — see the private `drawbridge` manifest. A vendor answering
2836
+ // these would be a second sender, which is the arrangement the platform
2837
+ // sender replaced.
2838
+ email: false,
2839
+ segment: false,
2840
+ sms: false,
2841
+ inbound: false,
2842
+ lifecycle: false,
2843
+ resources: {
2844
+ audiences: false,
2845
+ prices: false,
2846
+ products: false,
2847
+ promotions: false
2848
+ },
2849
+ // THE BODY IS HERE, not in drawbridge-sync. It needs `crypto` and an HTTP
2850
+ // client and nothing else — no controller, no queue, no database — so
2851
+ // there was never a reason for it to live in another repo.
2852
+ //
2853
+ // That is the rule the whole split runs on: a hook lives in sync only if it
2854
+ // needs Drawbridge's own database, sockets or queues. This one does not.
2855
+ webhook: {
2856
+ send: async ({ context, controller, request: send2 = safeRequest, settings, step }) => {
2857
+ const { headers = {}, method = "POST", url } = step.settings || {};
2858
+ const request2 = { method, url: url || null };
2859
+ if (!url) return { message: "Outgoing webhook URL is not configured for this step.", request: request2, response: { skipped: true }, skipped: true };
2860
+ const lead = (context == null ? void 0 : context.lead) ? await controller.get({ collection: "lead", query: { id: context.lead } }) : null;
2861
+ const body = lead || context;
2862
+ request2.body = body;
2863
+ const outgoing = { ...headers };
2864
+ if (settings == null ? void 0 : settings.secret) {
2865
+ outgoing["X-Drawbridge-Signature"] = "sha256=" + crypto.createHmac("sha256", settings.secret).update(JSON.stringify(body)).digest("hex");
2866
+ }
2867
+ const response = await send2({ body, headers: outgoing, method, url });
2868
+ return { message: "Webhook POSTed to " + url + ".", request: request2, response: response || { delivered: true } };
2869
+ }
2870
+ }
2871
+ },
2872
+ // Borrowed: this is the Drawbridge mark, because Webhooks has none of its own.
2873
+ // It is the one card that reads wrong — our logo among vendor logos — and it
2874
+ // wants a mark of its own when there is one.
2875
+ icon: drawbridge_default,
2876
+ // Gated on the encryption secret: without it the signing secret could not be
2877
+ // stored safely, so the connection must not be offered at all.
2878
+ requires: ["ENCRYPT_CONNECTION_SECRET"],
2879
+ // Outbound only. inbound.* is false because the direction is the point: we
2880
+ // sign and POST to the merchant's endpoint, they never call us. Every other
2881
+ // false follows from there being no third party to authenticate against —
2882
+ // connect generates a secret rather than proving a credential.
2883
+ slug: "webhook",
2884
+ // The destination url is supplied per step, not per connection, so there is
2885
+ // nothing to finish here — generating the secret IS connecting, and no
2886
+ // setting can make this connection unusable. The credential's own verdict
2887
+ // stands.
2888
+ status: (data2) => data2 == null ? void 0 : data2.status,
2889
+ steps: {
2890
+ webhook: {
2891
+ send: () => ({
2892
+ hook: "webhook.send",
2893
+ key: "Send webhook",
2894
+ queue: "webhook",
2895
+ settings: {
2896
+ url: { format: "url", required: true, type: "string" }
2897
+ },
2898
+ triggers: ["lead.insert", "lead.delete"],
2899
+ // Replaces `billable : true`, which fed BILLABLE_STEP_TYPES, which set
2900
+ // workflow.billable at save, which sync then checked against a usage
2901
+ // the handler returned — three hops for one fact, two of which could
2902
+ // disagree silently.
2903
+ usage: { actions: 1 }
2904
+ })
2905
+ }
2906
+ },
2907
+ // The card the connection page raises. Before connecting it explains what
2908
+ // pressing Connect will do; afterwards it states the verification the
2909
+ // merchant's own endpoint has to perform, because a signed payload nobody
2910
+ // checks is an unsigned payload.
2911
+ tasks: ({ settings }) => (settings == null ? void 0 : settings.secret) ? [
2912
+ {
2913
+ message: "Compute HMAC-SHA256( secret, body ) and compare against the X-Drawbridge-Signature header to confirm each payload.",
2914
+ title: "Requests must be verified",
2915
+ type: "warning"
2916
+ }
2917
+ ] : [
2918
+ {
2919
+ message: "Connect to generate a signing secret. Drawbridge signs every webhook it sends with it.",
2920
+ title: "Webhook signing"
2921
+ }
2922
+ ],
2923
+ title: "Webhooks"
2924
+ };
2925
+
2926
+ // lib/connections/index.js
2927
+ var QUEUES = ["connection", "notification", "segment", "webhook"];
2928
+ var implemented = (hooks, path) => {
2929
+ const hook = path.split(".").reduce((node, key) => node == null ? void 0 : node[key], hooks);
2930
+ return typeof hook === "function" || !!hook && typeof hook === "object";
2931
+ };
2932
+ var leaves = (node, path = []) => Object.entries(node || {}).flatMap(
2933
+ ([key, value]) => typeof value === "function" ? [[[...path, key].join("."), value]] : value && typeof value === "object" ? leaves(value, [...path, key]) : []
2934
+ );
2935
+ var build = (manifest) => {
2936
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
2937
+ if (!(manifest == null ? void 0 : manifest.slug)) throw new Error("A connection needs a slug");
2938
+ if (!(manifest == null ? void 0 : manifest.title)) throw new Error(manifest.slug + " needs a title");
2939
+ if (!(manifest == null ? void 0 : manifest.private) && !(manifest == null ? void 0 : manifest.feature)) throw new Error(manifest.slug + " needs a plan feature key");
2940
+ if (!((_a = manifest == null ? void 0 : manifest.content) == null ? void 0 : _a.excerpt)) throw new Error(manifest.slug + " needs content.excerpt for its card");
2941
+ if (!Array.isArray((_b = manifest == null ? void 0 : manifest.content) == null ? void 0 : _b.description) || !manifest.content.description.length) {
2942
+ throw new Error(manifest.slug + " needs content.description \u2014 an array of paragraphs for its page");
2943
+ }
2944
+ for (const field2 of manifest.fields || []) {
2945
+ if (!(field2 == null ? void 0 : field2.key) || !(field2 == null ? void 0 : field2.label)) {
2946
+ throw new Error(manifest.slug + " declares a field with no key or label");
2947
+ }
2948
+ if (field2.input && !INPUTS.includes(field2.input)) {
2949
+ throw new Error(manifest.slug + "." + field2.key + " declares an unknown input: " + field2.input + " \u2014 one of " + INPUTS.join(", "));
2950
+ }
2951
+ if (field2.input === "select" && !(field2.options || []).length && !field2.hook) {
2952
+ throw new Error(manifest.slug + "." + field2.key + " is a select and must declare options or a hook");
2953
+ }
2954
+ if (field2.hook) {
2955
+ if (!HOOK_NAMES.includes(field2.hook)) {
2956
+ throw new Error(manifest.slug + "." + field2.key + " names an unknown hook: " + field2.hook);
2957
+ }
2958
+ if (!field2.hook.startsWith("resources.")) {
2959
+ throw new Error(manifest.slug + "." + field2.key + " reads from " + field2.hook + " \u2014 a picker may only read resources.*");
2960
+ }
2961
+ if (!implemented(manifest.hooks, field2.hook)) {
2962
+ throw new Error(manifest.slug + "." + field2.key + " reads " + field2.hook + ", which this vendor does not implement");
2963
+ }
2964
+ }
2965
+ }
2966
+ if (typeof (manifest == null ? void 0 : manifest.icon) !== "string" || !manifest.icon.includes("<svg")) {
2967
+ throw new Error(manifest.slug + " needs an icon \u2014 the svg markup itself, not a path to one");
2968
+ }
2969
+ if (!manifest.icon.includes("viewBox")) {
2970
+ throw new Error(manifest.slug + " icon has no viewBox, so it cannot scale");
2971
+ }
2972
+ if (manifest.icon.includes("<image")) {
2973
+ throw new Error(manifest.slug + " icon wraps a raster \u2014 re-export it as vector shapes");
2974
+ }
2975
+ if (!GROUPS.includes(manifest == null ? void 0 : manifest.group)) {
2976
+ throw new Error(manifest.slug + " needs a group \u2014 one of " + GROUPS.join(", "));
2977
+ }
2978
+ if ((_c = manifest == null ? void 0 : manifest.connect) == null ? void 0 : _c.type) {
2979
+ throw new Error(manifest.slug + " declares connect.type \u2014 that is auth.type now");
2980
+ }
2981
+ if (!AUTH_TYPES.includes((_d = manifest == null ? void 0 : manifest.auth) == null ? void 0 : _d.type)) {
2982
+ throw new Error(manifest.slug + " needs auth.type \u2014 one of " + AUTH_TYPES.join(", "));
2983
+ }
2984
+ if (manifest.auth.type === "oauth") {
2985
+ for (const field2 of OAUTH_FIELDS) {
2986
+ if (!((_e = manifest.auth.oauth) == null ? void 0 : _e[field2])) {
2987
+ throw new Error(manifest.slug + " is oauth and must declare auth.oauth." + field2);
2988
+ }
2989
+ }
2990
+ if (typeof ((_g = (_f = manifest.hooks) == null ? void 0 : _f.auth) == null ? void 0 : _g.token) !== "function") {
2991
+ throw new Error(manifest.slug + " is oauth and must implement hooks.auth.token \u2014 point it at authToken() or wrap it");
2992
+ }
2993
+ for (const url of OAUTH_URLS) {
2994
+ if (!((_i = (_h = manifest.auth.oauth) == null ? void 0 : _h.urls) == null ? void 0 : _i[url])) {
2995
+ throw new Error(manifest.slug + " is oauth and must declare auth.oauth.urls." + url);
2996
+ }
2997
+ }
2998
+ if (manifest.auth.oauth.urls.redirect !== "/api/connection/" + manifest.slug + "/callback") {
2999
+ throw new Error(
3000
+ manifest.slug + " declares auth.oauth.urls.redirect " + manifest.auth.oauth.urls.redirect + " but the only callback route is /api/connection/" + manifest.slug + "/callback"
3001
+ );
3002
+ }
3003
+ }
3004
+ if (implemented(manifest.hooks, "inbound.event") && !((_k = (_j = manifest.inbound) == null ? void 0 : _j.headers) == null ? void 0 : _k.event)) {
3005
+ throw new Error(manifest.slug + " implements inbound.event but declares no inbound.headers.event");
3006
+ }
3007
+ if (implemented(manifest.hooks, "inbound.verify") && !((_m = (_l = manifest.inbound) == null ? void 0 : _l.headers) == null ? void 0 : _m.signature)) {
3008
+ throw new Error(manifest.slug + " implements inbound.verify but declares no inbound.headers.signature");
3009
+ }
3010
+ if (typeof (manifest == null ? void 0 : manifest.status) !== "function") {
3011
+ throw new Error(manifest.slug + " must declare status( data ) \u2014 return null to accept the connection's own status, or { message, status } to override it");
3012
+ }
3013
+ if (!Array.isArray((_n = manifest == null ? void 0 : manifest.content) == null ? void 0 : _n.guide) || !manifest.content.guide.length) {
3014
+ throw new Error(manifest.slug + " needs content.guide \u2014 an array of steps for its page");
3015
+ }
3016
+ if (typeof (manifest == null ? void 0 : manifest.status) !== "function") {
3017
+ throw new Error(manifest.slug + " must declare status( data ) \u2014 one of " + STATUSES.join(", "));
3018
+ }
3019
+ const status = manifest.status({});
3020
+ if (status != null && !STATUSES.includes(status)) {
3021
+ throw new Error(manifest.slug + " status() returned " + status + " \u2014 must be one of " + STATUSES.join(", "));
3022
+ }
3023
+ for (const [domain, verbs] of Object.entries(HOOKS)) {
3024
+ for (const verb of verbs) {
3025
+ const hook = (_p = (_o = manifest.hooks) == null ? void 0 : _o[domain]) == null ? void 0 : _p[verb];
3026
+ if (((_q = manifest.hooks) == null ? void 0 : _q[domain]) === false) continue;
3027
+ if (hook !== false && !implemented({ [domain]: { [verb]: hook } }, domain + "." + verb)) {
3028
+ throw new Error(manifest.slug + " must answer hooks." + domain + "." + verb + " \u2014 false, a function, or {} if another repo implements it");
3029
+ }
3030
+ }
3031
+ }
3032
+ for (const [domain, verbs] of Object.entries(manifest.hooks || {})) {
3033
+ if (!HOOKS[domain]) throw new Error(manifest.slug + " implements an unknown hook domain: " + domain);
3034
+ for (const verb of Object.keys(verbs === false ? {} : verbs)) {
3035
+ if (!HOOKS[domain].includes(verb)) {
3036
+ throw new Error(manifest.slug + " implements an unknown hook: " + domain + "." + verb);
3037
+ }
3038
+ }
3039
+ }
3040
+ for (const [name, step] of leaves(manifest.steps)) {
3041
+ const type = "step." + name;
3042
+ if (!STEPS[name]) {
3043
+ throw new Error(manifest.slug + " declares an unknown step: " + type + " \u2014 add it to STEPS in contract.js");
3044
+ }
3045
+ const declared = step({});
3046
+ if (!(declared == null ? void 0 : declared.key)) throw new Error(manifest.slug + " step " + type + " needs a key \u2014 the label the builder shows");
3047
+ if (!QUEUES.includes(declared == null ? void 0 : declared.queue)) {
3048
+ throw new Error(manifest.slug + " step " + type + " needs a queue \u2014 one of " + QUEUES.join(", "));
3049
+ }
3050
+ if (declared.hook && !implemented(manifest.hooks, declared.hook)) {
3051
+ throw new Error(manifest.slug + " step " + type + " points at hook " + declared.hook + ", which this vendor does not implement");
3052
+ }
3053
+ }
3054
+ return Object.freeze({
3055
+ ...manifest,
3056
+ fields: Object.freeze(manifest.fields || []),
3057
+ hooks: Object.freeze(manifest.hooks || {}),
3058
+ inbound: Object.freeze(manifest.inbound || {}),
3059
+ requires: Object.freeze(manifest.requires || []),
3060
+ steps: Object.freeze(manifest.steps || {})
3061
+ });
3062
+ };
3063
+ var connections = Object.freeze({
3064
+ attentive: build(attentive_default2),
3065
+ drawbridge: build(drawbridge_default2),
3066
+ klaviyo: build(klaviyo_default2),
3067
+ mailchimp: build(mailchimp_default2),
3068
+ shopify: build(shopify_default2),
3069
+ webhook: build(webhook_default)
3070
+ });
3071
+ (() => {
3072
+ const owners = {};
3073
+ for (const [slug, manifest] of Object.entries(connections)) {
3074
+ for (const [name] of leaves(manifest.steps)) {
3075
+ const type = "step." + name;
3076
+ if (owners[type]) {
3077
+ throw new Error("Step " + type + " is declared by both " + owners[type] + " and " + slug);
3078
+ }
3079
+ owners[type] = slug;
3080
+ }
3081
+ }
3082
+ })();
3083
+ var publicSettingsBySlug = Object.fromEntries(
3084
+ Object.entries(connections).map(([slug, manifest]) => [
3085
+ slug,
3086
+ manifest.fields.filter((field2) => !field2.redact).map((field2) => field2.key)
3087
+ ])
3088
+ );
3089
+ var mergeSettings = ({ existing, incoming }) => {
3090
+ if (!existing || typeof existing !== "object") return incoming;
3091
+ const merged = { ...existing };
3092
+ for (const [key, value] of Object.entries(incoming || {})) {
3093
+ if (value !== void 0 && value !== null && value !== "") {
3094
+ merged[key] = value;
3095
+ }
3096
+ ;
3097
+ }
3098
+ ;
3099
+ return merged;
3100
+ };
3101
+ var publicConnectionKeys = Object.freeze([
3102
+ "actions",
3103
+ // API-COMPOSED, not manifest-declared: the api's resolve() builds it from
3104
+ // auth.type, content.redirect and the manifest's manage() — the client reads
3105
+ // connect.type to choose entered-vs-installed, connect.redirect for the App
3106
+ // Store link, connect.manage for the admin deep link. It was dropped from
3107
+ // this list when the manifests stopped declaring it, which stripped the
3108
+ // composed object from every response and broke all three.
3109
+ "connect",
3110
+ // EVERYTHING A MERCHANT READS, in one key: confirm, description, errors,
3111
+ // excerpt, guide, and any vendor redirect copy.
3112
+ "content",
3113
+ "createdAt",
3114
+ // The connection DOCUMENT's own errors array — scope-drift entries written by
3115
+ // drawbridge-sync. NOT the manifest's error copy, which is content.errors:
3116
+ // the document is spread OVER the resolved manifest downstream, so the two
3117
+ // sharing this key means the array silently wins.
3118
+ "errors",
3119
+ "fields",
3120
+ "group",
3121
+ "id",
3122
+ "image",
3123
+ "settings",
3124
+ "shop",
3125
+ "slug",
3126
+ "status",
3127
+ "tasks",
3128
+ "title",
3129
+ "updatedAt",
3130
+ "warnings"
3131
+ ]);
3132
+
3133
+ // lib/encrypt.js
3134
+ import crypto3 from "crypto";
3135
+
3136
+ // lib/token.js
3137
+ import crypto2 from "crypto";
3138
+ var generate = (bytes = 32, encoding = "base64url") => {
3139
+ const buf = crypto2.randomBytes(bytes);
3140
+ return encoding ? buf.toString(encoding) : buf;
3141
+ };
3142
+
3143
+ // lib/encrypt.js
3144
+ var ALGORITHM = "aes-256-gcm";
3145
+ var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
3146
+ var encrypt = (value) => {
3147
+ const iv = generate(12, null);
3148
+ const cipher = crypto3.createCipheriv(ALGORITHM, getKey(), iv);
3149
+ const data2 = Buffer.concat([
3150
+ cipher.update(JSON.stringify(value), "utf8"),
3151
+ cipher.final()
3152
+ ]);
3153
+ const tag = cipher.getAuthTag();
3154
+ return [iv, tag, data2].map((b) => b.toString("hex")).join(":");
3155
+ };
3156
+ var decrypt = (value) => {
3157
+ if (typeof value !== "string") return value;
3158
+ const [ivHex, tagHex, dataHex] = value.split(":");
3159
+ const decipher = crypto3.createDecipheriv(
3160
+ ALGORITHM,
3161
+ getKey(),
3162
+ Buffer.from(ivHex, "hex")
3163
+ );
3164
+ decipher.setAuthTag(Buffer.from(tagHex, "hex"));
3165
+ const result = Buffer.concat([
3166
+ decipher.update(Buffer.from(dataHex, "hex")),
3167
+ decipher.final()
3168
+ ]);
3169
+ return JSON.parse(result.toString("utf8"));
3170
+ };
3171
+
3172
+ // lib/providers.js
3173
+ var FIELDS = {
3174
+ attentive: [
3175
+ { input: "text", key: "clientId", env: "ATTENTIVE_OAUTH_CLIENT_ID", label: "Client ID", required: true },
3176
+ { input: "password", key: "clientSecret", env: "ATTENTIVE_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
3177
+ ],
3178
+ drawbridge: [
3179
+ { input: "email", key: "accountSender", env: "SENDGRID_FROM_ADDRESS", label: "Account sender", message: "Verification codes and security alerts send from here.", required: true },
3180
+ { input: "password", key: "apiKey", env: "SENDGRID_API_KEY", label: "SendGrid API key", redact: true, required: true },
3181
+ // NOT required. The CRM sync is best-effort internal tooling and no-ops
3182
+ // without a token — requiring it would make the whole drawbridge provider
3183
+ // read not-live over something no merchant ever sees.
3184
+ { input: "password", key: "hubspotToken", env: "HUBSPOT_ACCESS_TOKEN", label: "HubSpot access token", message: "Drawbridge's own CRM portal. Internal \u2014 no merchant sees this.", redact: true },
3185
+ // Optional: SENDGRID_SEND_FROM_ADDRESS is not boot-required in sync
3186
+ // either. Unset, it degrades to the account sender rather than
3187
+ // refusing to start.
3188
+ { input: "email", key: "leadSender", env: "SENDGRID_SEND_FROM_ADDRESS", label: "Lead sender", message: "The default for lead-facing mail when a merchant has not verified their own domain." },
3189
+ { input: "text", key: "smsFrom", env: "TWILIO_ACCOUNT_FROM", label: "SMS number", required: true },
3190
+ { input: "password", key: "smsSid", env: "TWILIO_ACCOUNT_SID", label: "Twilio account SID", redact: true, required: true },
3191
+ { input: "password", key: "smsToken", env: "TWILIO_AUTH_TOKEN", label: "Twilio auth token", redact: true, required: true }
3192
+ ],
3193
+ klaviyo: [
3194
+ { input: "text", key: "clientId", env: "KLAVIYO_OAUTH_CLIENT_ID", label: "Client ID", required: true },
3195
+ { input: "password", key: "clientSecret", env: "KLAVIYO_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
3196
+ ],
3197
+ mailchimp: [
3198
+ { input: "text", key: "clientId", env: "MAILCHIMP_OAUTH_CLIENT_ID", label: "Client ID", required: true },
3199
+ { input: "password", key: "clientSecret", env: "MAILCHIMP_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
3200
+ ],
3201
+ shopify: [
3202
+ { input: "text", key: "apiKey", env: "SHOPIFY_API_KEY", label: "API key", required: true },
3203
+ { input: "password", key: "apiSecret", env: "SHOPIFY_API_SECRET", label: "API secret", redact: true, required: true },
3204
+ { input: "text", key: "appHandle", env: "SHOPIFY_APP_HANDLE", label: "App handle", required: true },
3205
+ { input: "text", key: "listingUrl", env: "SHOPIFY_APP_LISTING_URL", label: "App listing URL", required: true }
3206
+ ]
3207
+ };
3208
+ var providerFields = (slug) => Object.hasOwn(FIELDS, slug) ? FIELDS[slug] : [];
3209
+ var providerSlugs = () => Object.keys(FIELDS).sort();
3210
+ var isLive = (slug, settings) => {
3211
+ const fields2 = providerFields(slug);
3212
+ if (!fields2.length) return false;
3213
+ return fields2.filter((field2) => field2.required).every((field2) => Boolean(settings == null ? void 0 : settings[field2.key]));
3214
+ };
3215
+ var mask = (value) => {
3216
+ if (!value) return null;
3217
+ if (String(value).length < 12) return "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";
3218
+ return String(value).slice(0, 3) + "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022" + String(value).slice(-4);
3219
+ };
3220
+ var cacheKey = (slug) => ["provider", slug];
3221
+ var providerSettings = async ({ cache, controller, slug }) => {
3222
+ const read = async () => controller.get({
3223
+ collection: "provider",
3224
+ query: { slug }
3225
+ });
3226
+ const row = cache ? await cache.use(cacheKey(slug), read, 30) : await read();
3227
+ return (row == null ? void 0 : row.settings) ? decrypt(row.settings) : {};
3228
+ };
3229
+ var saveProviderSettings = async ({ authenticated, cache, clear, controller, settings, slug }) => {
3230
+ const fields2 = providerFields(slug);
3231
+ if (!fields2.length) return null;
3232
+ const existing = await controller.get({
3233
+ collection: "provider",
3234
+ query: { slug }
3235
+ });
3236
+ const stored = (existing == null ? void 0 : existing.settings) ? decrypt(existing.settings) : {};
3237
+ const merged = mergeSettings({
3238
+ existing: stored,
3239
+ incoming: Object.fromEntries(fields2.map((field2) => [field2.key, settings == null ? void 0 : settings[field2.key]]))
3240
+ });
3241
+ for (const key of Array.isArray(clear) ? clear : []) {
3242
+ if (fields2.some((field2) => field2.key === key)) delete merged[key];
3243
+ }
3244
+ const result = await controller.update({
3245
+ authenticated,
3246
+ collection: "provider",
3247
+ data: {
3248
+ $set: {
3249
+ settings: encrypt(merged)
3250
+ }
3251
+ },
3252
+ options: {
3253
+ upsert: true
3254
+ },
3255
+ query: { slug }
3256
+ });
3257
+ await cache.delete(cacheKey(slug));
3258
+ return result;
3259
+ };
3260
+ var providerEnvNames = () => new Set(
3261
+ providerSlugs().flatMap((slug) => providerFields(slug)).map((field2) => field2.env).filter(Boolean)
3262
+ );
3263
+ var providerCredentials = async ({ cache, controller }) => {
3264
+ const credentials2 = {};
3265
+ for (const slug of providerSlugs()) {
3266
+ const settings = await providerSettings({ cache, controller, slug });
3267
+ for (const field2 of providerFields(slug)) {
3268
+ const value = settings == null ? void 0 : settings[field2.key];
3269
+ if (field2.env && value) credentials2[field2.env] = value;
3270
+ }
3271
+ }
3272
+ return credentials2;
3273
+ };
3274
+ var hydrateEnvironment = async ({ cache, controller, env = process.env }) => {
3275
+ const credentials2 = await providerCredentials({ cache, controller });
3276
+ for (const name of providerEnvNames()) delete env[name];
3277
+ Object.assign(env, credentials2);
3278
+ return Object.keys(credentials2).sort();
3279
+ };
3280
+ export {
3281
+ cacheKey,
3282
+ hydrateEnvironment,
3283
+ isLive,
3284
+ mask,
3285
+ providerCredentials,
3286
+ providerEnvNames,
3287
+ providerFields,
3288
+ providerSettings,
3289
+ providerSlugs,
3290
+ saveProviderSettings
3291
+ };