@drawbridge/drawbridge-utils 0.0.105 → 0.0.107

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,1228 @@
1
+ export { consentUrl, exchange, pkcePair, refresh } from './oauth.cjs';
2
+ import 'node:crypto';
3
+
4
+ // THE HOOK VOCABULARY. Closed, and every connection answers all of it.
5
+ //
6
+ // A vendor does not get to be silent about a hook. It declares `true` where it
7
+ // implements one and `false` where it does not, and `build()` rejects a manifest
8
+ // that leaves any entry out. That is what makes the connections COMPARABLE: the
9
+ // table of vendors against hooks has no empty cells, so "does Shopify do
10
+ // catalog.products" is answered by the manifest rather than by reading sync.
11
+ //
12
+ // The alternative — carry only the hooks you implement, and let the caller
13
+ // filter — is what drawbridge-growth does, and it drifts: 26 of its 35 hooks are
14
+ // implemented by exactly one vendor, and nothing tells you whether the other
15
+ // twelve considered that hook and declined or never knew it existed.
16
+ //
17
+ // `false` is a DECISION, recorded. It is not the same as a hook that is
18
+ // supported and returned nothing, and it is not the same as a connection that
19
+ // is not currently connected. All three are different answers to "why is there
20
+ // no data", and an operator debugging an empty result needs to tell them apart.
21
+ const HOOKS = Object.freeze({
22
+
23
+ // Proving and holding the credential.
24
+ auth : Object.freeze([
25
+ // Accept what the merchant supplied — a form submission or an OAuth
26
+ // callback — and store what is needed to call the vendor later.
27
+ 'connect',
28
+ // Is the stored credential still good? Answered by the cheapest real call
29
+ // the vendor offers, never by inspecting what we stored: a key that was
30
+ // revoked at the vendor still looks perfect in our database.
31
+ 'probe',
32
+ // Which permissions we asked for and no longer hold. Distinct from probe:
33
+ // the credential can be valid and the grant still be too narrow.
34
+ 'scopes',
35
+ // Revoke at the vendor and drop what we hold.
36
+ 'disconnect'
37
+ ]),
38
+
39
+ // What happens around connecting and disconnecting, beyond the credential.
40
+ lifecycle : Object.freeze([
41
+ // Post-connect setup: register the vendor's webhooks, create the system
42
+ // workflows that describe them.
43
+ 'register',
44
+ // Re-pull vendor state we mirror, after a reconnect or on a schedule.
45
+ 'rehydrate',
46
+ // Undo `register` — deregister webhooks, release anything reserved.
47
+ 'cleanup'
48
+ ]),
49
+
50
+ // Receiving from the vendor.
51
+ inbound : Object.freeze([
52
+ // Prove the request came from the vendor. Signature schemes differ per
53
+ // vendor, which is exactly why this is a hook and not one shared function.
54
+ 'verify',
55
+ // Name the event, from wherever this vendor puts it.
56
+ 'topic',
57
+ // Do the work the event implies.
58
+ 'handle'
59
+ ]),
60
+
61
+ // Vendor data a campaign draws on. Named for what every store platform has,
62
+ // not for what Shopify calls it: Shopify says discounts, Stripe says coupons
63
+ // and promotion codes, BigCommerce says coupons and promotions.
64
+ catalog : Object.freeze([
65
+ 'products',
66
+ // Shopify folds price into the product variant; Stripe makes Price a
67
+ // first-class object beside Product. Declared so a vendor that separates
68
+ // them has somewhere to answer.
69
+ 'prices',
70
+ 'promotions'
71
+ ])
72
+
73
+ });
74
+
75
+ // Flat 'domain.verb' names, which is how a manifest declares support and how a
76
+ // caller asks for one.
77
+ const HOOK_NAMES = Object.freeze(
78
+ Object.entries( HOOKS ).flatMap( ( [ domain, verbs ] ) => verbs.map( ( verb ) => domain + '.' + verb ) )
79
+ );
80
+
81
+ // Why a hook produced nothing. Returned by the call surface rather than an empty
82
+ // array, because "not supported", "not connected" and "supported, found nothing"
83
+ // lead to three different next actions and collapsing them loses the one that
84
+ // matters.
85
+ const OUTCOMES = Object.freeze({
86
+ answered : 'answered',
87
+ disconnected : 'disconnected',
88
+ failed : 'failed',
89
+ // Declared supported, implemented in a consumer rather than in this package —
90
+ // sync owns the step handlers and lifecycle jobs. Different from unsupported,
91
+ // which means the vendor cannot do it at all.
92
+ unimplemented : 'unimplemented',
93
+ unsupported : 'unsupported'
94
+ });
95
+
96
+ // HOW A VENDOR IS CONNECTED. Four kinds, because the merchant's experience of
97
+ // each is genuinely different and the dashboard renders from this:
98
+ //
99
+ // keys they paste a credential in (Mailchimp today)
100
+ // oauth they consent at the vendor and come back (Mailchimp next, Klaviyo)
101
+ // install they install an app at the vendor (Shopify)
102
+ // generated Drawbridge mints it, nobody types anything (Webhooks)
103
+ //
104
+ // `install` is separate from `oauth` on purpose. Both end in a token, but the
105
+ // merchant never sees a consent screen we sent them to — they start at the
106
+ // vendor's app store — and a dashboard that offers a Connect button for one is
107
+ // lying about the other.
108
+ const AUTH_TYPES = Object.freeze([ 'generated', 'install', 'keys', 'oauth' ]);
109
+
110
+ // WHAT KIND OF VENDOR THIS IS. Closed, because a card list that works at three
111
+ // connections stops working the day every CMS joins it, and a category nobody
112
+ // spelled right is a filter chip that silently shows nothing.
113
+ const CATEGORIES = Object.freeze([ 'commerce', 'contacts', 'developer', 'messaging' ]);
114
+
115
+ // WHAT AN OAUTH VENDOR MUST DECLARE, so one implementation serves all of them
116
+ // rather than one module per vendor.
117
+ //
118
+ // authorize the consent url
119
+ // token the exchange/refresh url
120
+ // client the ENV VAR NAMES holding our own id and secret, never the values
121
+ // redirect our callback path — DECLARED, never derived from the slug. It is
122
+ // registered in the vendor's console and they refuse anything that
123
+ // does not byte-match, so it is a fact about someone else's records
124
+ // rather than a string this code gets to compute.
125
+ // scopes what we ask for
126
+ // params vendor quirks (Google wants access_type=offline)
127
+ // pkce Klaviyo's OAuth 2.1 REQUIRES a code_verifier/code_challenge pair;
128
+ // most vendors do not. A flag rather than a Klaviyo module.
129
+ const OAUTH_FIELDS = Object.freeze([ 'authorize', 'client', 'redirect', 'token' ]);
130
+
131
+ // HOW A FIELD IS EDITED. Closed, because the dashboard renders one form for
132
+ // every connection and it can only render what it has a component for. An open
133
+ // list means a vendor declares `kind : "toggle"`, the form falls through to a
134
+ // text box, and a merchant types the word true into it.
135
+ //
136
+ // text a line of text
137
+ // password a secret — masked, and never returned once stored
138
+ // email text, validated as an address
139
+ // url text, validated as a url
140
+ // number a numeric field
141
+ // textarea multi-line, for things like an allow-list or a template
142
+ // select a fixed choice; the field must also declare `options`
143
+ // checkbox on or off
144
+ //
145
+ // A field with NO input is not editable at all: it is read-only on the page,
146
+ // which is how a generated secret and an installed store domain are shown.
147
+ const INPUTS = Object.freeze([
148
+ 'checkbox',
149
+ 'email',
150
+ 'number',
151
+ 'password',
152
+ 'select',
153
+ 'text',
154
+ 'textarea',
155
+ 'url'
156
+ ]);
157
+
158
+ // Klaviyo, exported from the brand kit and left as authored — the fills are the
159
+ // vendor's own mark, not a recolour.
160
+ //
161
+ // A .js wrapper around otherwise untouched SVG so `node --test` can run against
162
+ // lib/ directly. A bare .svg import would need a bundler loader and force the
163
+ // tests onto dist/, which is a worse trade than one line of wrapper.
164
+ var icon$3 = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
165
+ <rect width="500" height="500" fill="white"/>
166
+ <path d="M365.047 327.038H134.954V172.964H365.047L316.856 250.001L365.047 327.038Z" fill="#232121"/>
167
+ </svg>`;
168
+
169
+ // Klaviyo — contact and event sync, over OAuth.
170
+ //
171
+ // THE FIRST VENDOR ADDED AS A MANIFEST AND NOTHING ELSE. No form component, no
172
+ // connect route, no consent builder, no token exchange: the shared runner in
173
+ // oauth.js reads the descriptor below and does all of it. That is the test of
174
+ // whether this exercise worked, and the things it forced out are the interesting
175
+ // part — clientAuth and pkce both exist because Klaviyo needs them and Google
176
+ // does not.
177
+ var klaviyo = {
178
+ // OAuth 2.1, and PKCE is REQUIRED rather than recommended: Klaviyo refuses an
179
+ // exchange without a code_verifier matching the challenge the consent
180
+ // carried. Most vendors treat it as optional hardening; this one does not,
181
+ // which is why it is a descriptor flag and not a global.
182
+ //
183
+ // clientAuth is the other thing Klaviyo does differently. The token endpoint
184
+ // wants HTTP Basic — base64( client_id : client_secret ) in an Authorization
185
+ // header — and rejects the same pair sent as form fields, which is how every
186
+ // Google product wants it.
187
+ auth : {
188
+ oauth : {
189
+ authorize : 'https://a.klaviyo.com/oauth/authorize',
190
+ // NAMES the env vars holding OUR application's client. One identity,
191
+ // every merchant — the token is the merchant's and arrives from their
192
+ // own consent, which is what stops one organization reading another's
193
+ // data.
194
+ client : {
195
+ id : 'KLAVIYO_OAUTH_CLIENT_ID',
196
+ secret : 'KLAVIYO_OAUTH_CLIENT_SECRET'
197
+ },
198
+ clientAuth : 'basic',
199
+ pkce : true,
200
+ // DECLARED, never derived from the slug. It is registered in Klaviyo's
201
+ // app settings and they refuse anything that does not byte-match, so
202
+ // it is a fact about someone else's records rather than a string this
203
+ // code computes. Deriving one from a provider key produced
204
+ // redirect_uri_mismatch on a connection nobody had touched.
205
+ redirect : '/api/connection/klaviyo/callback',
206
+ // Space separated. accounts:read is required by Klaviyo on every app
207
+ // and must stay in the list; the rest are what a contact sync needs.
208
+ scopes : 'accounts:read lists:read lists:write profiles:read profiles:write',
209
+ token : 'https://a.klaviyo.com/oauth/token'
210
+ },
211
+ type : 'oauth'
212
+ },
213
+ category : 'contacts',
214
+ confirm : 'Disconnecting revokes Drawbridge\'s access to your Klaviyo account. Your profiles and lists stay in both Klaviyo and Drawbridge — neither is deleted.',
215
+ connect : {
216
+ errors : {
217
+ denied : 'The Klaviyo authorization was declined, so nothing was connected.',
218
+ invalid : 'We couldn\'t complete the Klaviyo connection. Try connecting again.'
219
+ }
220
+ },
221
+ description : [
222
+ '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.',
223
+ '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.',
224
+ '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.'
225
+ ],
226
+ excerpt : 'Sync the contacts your campaigns collect into a Klaviyo list.',
227
+ feature : 'organization:connection:klaviyo',
228
+ // Nothing typed. The consent returns the grant, and the account it belongs to
229
+ // is read back from Klaviyo rather than asked for.
230
+ fields : [
231
+ {
232
+ key : 'account',
233
+ label : 'Klaviyo account'
234
+ }
235
+ ],
236
+ icon: icon$3,
237
+ label : 'klaviyo',
238
+ requires : [
239
+ 'KLAVIYO_OAUTH_CLIENT_ID',
240
+ 'KLAVIYO_OAUTH_CLIENT_SECRET'
241
+ ],
242
+ setup : [
243
+ 'Press Connect. Drawbridge sends you to Klaviyo to approve access.',
244
+ 'Sign in to Klaviyo if you are not already, and choose the account to connect.',
245
+ 'Approve the permissions Klaviyo lists. You are returned here and the connection shows Active.',
246
+ 'You can revoke access at any time from Klaviyo, under Integrations.'
247
+ ],
248
+ slug : 'klaviyo',
249
+ // No steps yet. The sync itself is unbuilt, and a step offered in the builder
250
+ // that nothing runs is worse than no step at all — the merchant configures it
251
+ // and waits for something that never happens.
252
+ steps : {},
253
+ supports : {
254
+ 'auth.connect' : true,
255
+ 'auth.disconnect' : true,
256
+ // The refresh mint IS the probe: a revoked or rotated grant fails there in
257
+ // Klaviyo's own words rather than as an empty sync three steps later.
258
+ 'auth.probe' : true,
259
+ // Klaviyo scopes are fixed at app level and re-consented, not drifted.
260
+ 'auth.scopes' : false,
261
+ 'catalog.prices' : false,
262
+ 'catalog.products' : false,
263
+ 'catalog.promotions' : false,
264
+ 'inbound.handle' : false,
265
+ 'inbound.topic' : false,
266
+ 'inbound.verify' : false,
267
+ 'lifecycle.cleanup' : false,
268
+ 'lifecycle.register' : false,
269
+ 'lifecycle.rehydrate' : false
270
+ },
271
+ title : 'Klaviyo'
272
+ };
273
+
274
+ // Mailchimp, exported from the brand kit and left as authored — the fills are the
275
+ // vendor's own mark, not a recolour.
276
+ //
277
+ // A .js wrapper around otherwise untouched SVG so `node --test` can run against
278
+ // lib/ directly. A bare .svg import would need a bundler loader and force the
279
+ // tests onto dist/, which is a worse trade than one line of wrapper.
280
+ var icon$2 = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
281
+ <rect width="500" height="500" fill="#FFE01B"/>
282
+ <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"/>
283
+ <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"/>
284
+ </svg>`;
285
+
286
+ // Mailchimp — contact sync, not a sender.
287
+ //
288
+ // Deliberately no `group`. Mailchimp and SendGrid shared one while they were
289
+ // SENDERS, where an org picking two providers to send the same mail was
290
+ // meaningless. As contact syncs they are destinations, and a merchant could
291
+ // reasonably keep several up to date, so the exclusivity is gone.
292
+ var mailchimp = {
293
+ // Keys TODAY. Mailchimp integrations authenticate with OAuth 2 (authorization
294
+ // code) and that is where this goes, so the endpoints are recorded here
295
+ // rather than researched again later:
296
+ //
297
+ // authorize https://login.mailchimp.com/oauth2/authorize
298
+ // token https://login.mailchimp.com/oauth2/token
299
+ // metadata https://login.mailchimp.com/oauth2/metadata
300
+ //
301
+ // The metadata call is Mailchimp's quirk and cannot be skipped: the access
302
+ // token alone is not enough to call the Marketing API, because every account
303
+ // lives behind a data-centre prefix (us1, us19...) that only that call
304
+ // returns and every subsequent request needs in its host. No PKCE.
305
+ //
306
+ // Switching is filling in auth.oauth and moving the apiKey field out. It is
307
+ // still a publish -- a manifest change always is -- but a value change
308
+ // rather than a shape one.
309
+ auth : {
310
+ type : 'keys'
311
+ },
312
+ category : 'contacts',
313
+ confirm : 'Disconnecting removes your stored Mailchimp key. Your contacts stay in both Drawbridge and Mailchimp — neither list is deleted.',
314
+ description : [
315
+ '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.',
316
+ 'This connection is becoming the way your Drawbridge contacts sync into a Mailchimp audience. Audience syncing is not live yet, so a key stored here does nothing today.'
317
+ ],
318
+ excerpt : 'Sync your Drawbridge contacts into a Mailchimp audience.',
319
+ feature : 'organization:connection:mailchimp',
320
+ fields : [
321
+ {
322
+ input : 'password',
323
+ key : 'apiKey',
324
+ label : 'Mailchimp API key',
325
+ message : 'Your Mailchimp API key',
326
+ placeholder : '••••••••••••••••••••••••••••••••-us1',
327
+ redact : true,
328
+ required : true
329
+ }
330
+ ],
331
+ icon: icon$2,
332
+ label : 'mailchimp',
333
+ // Uniform surface, honest answers. A key is stored and can be removed; nothing
334
+ // else is built yet, because audience sync has not shipped. Every false here
335
+ // is "not yet", not "never" — when the sync lands, probe and catalog become
336
+ // the first two to flip.
337
+ supports : {
338
+ 'auth.connect' : true,
339
+ 'auth.disconnect' : true,
340
+ 'auth.probe' : false,
341
+ 'auth.scopes' : false,
342
+ 'catalog.prices' : false,
343
+ 'catalog.products' : false,
344
+ 'catalog.promotions' : false,
345
+ 'inbound.handle' : false,
346
+ 'inbound.topic' : false,
347
+ 'inbound.verify' : false,
348
+ 'lifecycle.cleanup' : false,
349
+ 'lifecycle.register' : false,
350
+ 'lifecycle.rehydrate' : false
351
+ },
352
+ setup : [
353
+ 'In Mailchimp, open Account & billing, then Extras, then API keys.',
354
+ 'Create a key and copy it.',
355
+ 'Paste it here. The key ends in a data-centre suffix like -us19, which tells Drawbridge which Mailchimp server your account is on.'
356
+ ],
357
+ slug : 'mailchimp',
358
+ // No steps: audience sync has not shipped, so this vendor contributes nothing
359
+ // to a workflow yet. An empty steps object is the honest declaration — the
360
+ // catalog renders the connection, and no builder offers a step it cannot run.
361
+ steps : {},
362
+ tasks : () => [
363
+ {
364
+ 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.',
365
+ title : 'Audience sync not available yet',
366
+ type : 'warning'
367
+ }
368
+ ],
369
+ title : 'Mailchimp'
370
+ };
371
+
372
+ // Shopify, exported from the brand kit and left as authored — the fills are the
373
+ // vendor's own mark, not a recolour.
374
+ //
375
+ // A .js wrapper around otherwise untouched SVG so `node --test` can run against
376
+ // lib/ directly. A bare .svg import would need a bundler loader and force the
377
+ // tests onto dist/, which is a worse trade than one line of wrapper.
378
+ var icon$1 = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
379
+ <rect width="500" height="500" fill="white"/>
380
+ <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"/>
381
+ <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"/>
382
+ <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"/>
383
+ </svg>`;
384
+
385
+ // Shopify — installed from the App Store, never connected with keys.
386
+ var shopify = {
387
+ // INSTALL, not oauth. The grant is an OAuth grant, but the merchant never
388
+ // sees a consent screen we sent them to -- they start at the App Store, and
389
+ // the install completes inside Shopify admin without redirecting back. A
390
+ // Connect button here would be lying about where connecting happens.
391
+ auth : {
392
+ type : 'install'
393
+ },
394
+ category : 'commerce',
395
+ 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.',
396
+ // How connecting is DESCRIBED — the copy and destination. What kind of connect
397
+ // it is lives in auth.type, once, so the two cannot disagree.
398
+ //
399
+ // The redirect title is copy: it names where the link GOES rather than what it
400
+ // does, since installing happens on the App Store listing and the dashboard
401
+ // must never imply a store can be linked from inside it.
402
+ connect : {
403
+ errors : {
404
+ conflict : 'This store is already connected to another Drawbridge organization.',
405
+ currency : 'This store settles in a currency we can\'t bill yet. Connect a store with a supported settlement currency.',
406
+ invalid : 'We couldn\'t verify the install. Please try connecting again from the Shopify App Store.'
407
+ },
408
+ redirect : {
409
+ env : 'SHOPIFY_APP_LISTING_URL',
410
+ title : 'View on the Shopify App Store'
411
+ }
412
+ },
413
+ description : [
414
+ '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.',
415
+ 'Drawbridge attributes orders that originate from your campaigns — matched through cart parameters and lead-mapped discount codes — so you can see the revenue each campaign drives.',
416
+ '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 catalog.'
417
+ ],
418
+ excerpt : 'Connect your Shopify store to feature products in your campaigns and track conversions.',
419
+ feature : 'organization:connection:shopify',
420
+ fields : [
421
+ {
422
+ // `shop` on the connection record wins when present — it is written by
423
+ // the install, while settings.domain is the stored copy.
424
+ from : 'shop',
425
+ key : 'domain',
426
+ label : 'Store domain'
427
+ }
428
+ ],
429
+ group : 'ecommerce',
430
+ // WHERE THIS VENDOR PUTS THINGS ON AN INBOUND REQUEST. Header names are facts
431
+ // about someone else's product, so they belong beside the rest of the vendor
432
+ // rather than as string literals in a route — which is where they were, and
433
+ // is why a second inbound vendor meant a second route file.
434
+ //
435
+ // `signature` describes an HMAC scheme the shared verifier can run: hash the
436
+ // raw body with the named secret and compare, constant-time, against the
437
+ // header. Vendors whose scheme is not that shape — Stripe signs a timestamped
438
+ // payload — declare no signature block and implement inbound.verify instead.
439
+ // That is why verify is a hook and not config.
440
+ inbound : {
441
+ headers : {
442
+ id : 'x-shopify-webhook-id',
443
+ shop : 'x-shopify-shop-domain',
444
+ signature : 'x-shopify-hmac-sha256',
445
+ topic : 'x-shopify-topic'
446
+ },
447
+ signature : {
448
+ algorithm : 'sha256',
449
+ encoding : 'base64',
450
+ secret : 'SHOPIFY_API_SECRET'
451
+ }
452
+ },
453
+ icon: icon$1,
454
+ label : 'shopify',
455
+ // A pre-launch integration: it only surfaces once the App Store listing
456
+ // exists and the app is fully configured. Requiring all four means it can
457
+ // never render half-configured — and absence of any one excludes the
458
+ // connection AND every step below it.
459
+ requires : [
460
+ 'SHOPIFY_API_KEY',
461
+ 'SHOPIFY_API_SECRET',
462
+ 'SHOPIFY_APP_LISTING_URL',
463
+ 'SHOPIFY_APP_HANDLE'
464
+ ],
465
+ // The only vendor implementing most of the surface, which is why it was the
466
+ // one every slug branch in three repos was written for.
467
+ //
468
+ // auth.probe is false deliberately: the health check re-registers webhooks
469
+ // rather than answering "is this token still good", and scope drift is its own
470
+ // hook because a token can be perfectly valid while the grant is too narrow.
471
+ supports : {
472
+ 'auth.connect' : true,
473
+ 'auth.disconnect' : true,
474
+ 'auth.probe' : false,
475
+ 'auth.scopes' : true,
476
+ // Shopify has no separate price resource — a price belongs to a product
477
+ // variant and arrives with it, so there is nothing for prices to answer
478
+ // that products does not already.
479
+ 'catalog.prices' : false,
480
+ 'catalog.products' : true,
481
+ 'catalog.promotions' : true,
482
+ 'inbound.handle' : true,
483
+ 'inbound.topic' : true,
484
+ 'inbound.verify' : true,
485
+ 'lifecycle.cleanup' : true,
486
+ 'lifecycle.register' : true,
487
+ 'lifecycle.rehydrate' : true
488
+ },
489
+ setup : [
490
+ 'Open the Drawbridge listing on the Shopify App Store.',
491
+ 'Install the app on the store you want to connect. It opens in Shopify admin and stays there.',
492
+ 'Choose a plan when Shopify asks. The connection shows Pending until you do, then Active.',
493
+ 'Come back here — the connections list updates on its own once the install lands.'
494
+ ],
495
+ slug : 'shopify',
496
+ // Step types name the CAPABILITY, not this vendor. A second store platform
497
+ // implements the same four commerce steps, and the connection on the step
498
+ // says which store it runs against — so a merchant sees one "Create
499
+ // customer", not one per platform. The three connection.* steps are not
500
+ // commerce at all: any vendor holding a rotating credential needs them.
501
+ steps : {
502
+ 'step.commerce.customer.insert' : {
503
+ billable : true,
504
+ key : 'Create customer',
505
+ queue : 'connection',
506
+ returns : [
507
+ { key : 'shopifyCustomerId', label : 'Shopify Customer ID' }
508
+ ],
509
+ settings : {},
510
+ triggers : [ 'lead.insert' ]
511
+ },
512
+ 'step.commerce.code.issue' : {
513
+ billable : true,
514
+ key : 'Issue a discount code',
515
+ queue : 'connection',
516
+ returns : [
517
+ { key : 'shopifyDiscountCode', label : 'Shopify Discount Code' },
518
+ { key : 'shopifyDiscountId', label : 'Shopify Discount ID' }
519
+ ],
520
+ settings : {
521
+ discount : {
522
+ required : true,
523
+ shape : {
524
+ id : { required : true, type : 'string' }
525
+ },
526
+ type : 'object'
527
+ }
528
+ },
529
+ triggers : [ 'lead.insert' ]
530
+ },
531
+ // System steps: dispatched by sync itself rather than offered in the
532
+ // builder, so they carry no trigger. They are declared because the
533
+ // routing table and the system-workflow descriptions both read from here.
534
+ // Not a webhook monitor, despite the name it carried. Webhooks are
535
+ // declarative — declared in the app's toml, applied by Shopify to every
536
+ // install — so nothing registers or checks them here. This rotates the
537
+ // access token before Shopify's idle window closes, and reconciles the
538
+ // scopes the store granted against the ones the app now needs.
539
+ 'step.connection.health.check' : {
540
+ description : 'Keeps store access working — refreshes the access token before it goes stale and reports when the store\'s approved permissions fall behind.',
541
+ key : 'Shopify Connection Health',
542
+ queue : 'connection',
543
+ system : true
544
+ },
545
+ 'step.commerce.order.record' : {
546
+ description : 'Records an order and billing charge when a purchase is made via a Drawbridge campaign link.',
547
+ key : 'Shopify Order Tracking',
548
+ queue : 'connection',
549
+ system : true
550
+ },
551
+ 'step.commerce.product.sync' : {
552
+ description : 'Syncs Shopify product data on webhook updates.',
553
+ key : 'Shopify Product Sync',
554
+ queue : 'connection',
555
+ system : true
556
+ },
557
+ // Audit-only. The "Shopify Token Activity" system workflow lists these for
558
+ // descriptive grouping, but its audit step docs are written manually at
559
+ // OAuth time — the workflow is never dispatched. Routing is declared
560
+ // defensively so that if it ever IS dispatched, the job lands on a real
561
+ // queue and the handler lookup misses cleanly instead of throwing
562
+ // "Unknown step type".
563
+ 'step.connection.token.exchange' : {
564
+ key : 'Shopify Token Exchange',
565
+ queue : 'connection',
566
+ system : true
567
+ },
568
+ 'step.connection.token.refresh' : {
569
+ key : 'Shopify Token Refresh',
570
+ queue : 'connection',
571
+ system : true
572
+ }
573
+ },
574
+ title : 'Shopify'
575
+ };
576
+
577
+ // Drawbridge, exported from the brand kit and left as authored — the fills are the
578
+ // vendor's own mark, not a recolour.
579
+ //
580
+ // A .js wrapper around otherwise untouched SVG so `node --test` can run against
581
+ // lib/ directly. A bare .svg import would need a bundler loader and force the
582
+ // tests onto dist/, which is a worse trade than one line of wrapper.
583
+ var icon = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
584
+ <rect width="500" height="500" fill="#BAEC5F"/>
585
+ <g clip-path="url(#clip0_2115_2832)">
586
+ <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"/>
587
+ <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"/>
588
+ </g>
589
+ <defs>
590
+ <clipPath id="clip0_2115_2832">
591
+ <rect width="220" height="284" fill="white" transform="translate(140 108)"/>
592
+ </clipPath>
593
+ </defs>
594
+ </svg>`;
595
+
596
+ // Webhooks — the only connection with no third party behind it. Connecting
597
+ // generates a signing secret rather than asking for a credential, which is why
598
+ // its one field declares no `input`.
599
+ var webhook = {
600
+ // Connecting GENERATES the secret rather than storing one the merchant typed,
601
+ // so the buttons say what actually happens.
602
+ actions : {
603
+ create : 'Connect',
604
+ update : 'Regenerate secret'
605
+ },
606
+ // GENERATED. There is no third party and nothing to authenticate against --
607
+ // connecting mints a secret rather than proving a credential.
608
+ auth : {
609
+ type : 'generated'
610
+ },
611
+ category : 'developer',
612
+ confirm : 'Disconnecting stops Drawbridge from sending signed webhook payloads to your endpoint.',
613
+ description : [
614
+ 'Drawbridge can POST event payloads to your endpoint as activity happens in your account, so your own systems can react in real time.',
615
+ '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.'
616
+ ],
617
+ excerpt : 'Sign outgoing webhook payloads with an HMAC secret to verify authenticity.',
618
+ feature : 'organization:connection:webhook',
619
+ fields : [
620
+ {
621
+ // No `input`: Drawbridge generates this, the merchant never types it.
622
+ // No `redact` either — it is shared with the merchant's own endpoint
623
+ // rather than being a third-party credential, so it round-trips for
624
+ // them to copy and configure.
625
+ copy : true,
626
+ key : 'secret',
627
+ label : 'Signing secret'
628
+ }
629
+ ],
630
+ // Borrowed: this is the Drawbridge mark, because Webhooks has none of its own.
631
+ // It is the one card that reads wrong — our logo among vendor logos — and it
632
+ // wants a mark of its own when there is one.
633
+ icon,
634
+ label : 'webhook',
635
+ // Gated on the encryption secret: without it the signing secret could not be
636
+ // stored safely, so the connection must not be offered at all.
637
+ requires : [ 'ENCRYPT_CONNECTION_SECRET' ],
638
+ // Outbound only. inbound.* is false because the direction is the point: we
639
+ // sign and POST to the merchant's endpoint, they never call us. Every other
640
+ // false follows from there being no third party to authenticate against —
641
+ // connect generates a secret rather than proving a credential.
642
+ supports : {
643
+ 'auth.connect' : true,
644
+ 'auth.disconnect' : true,
645
+ 'auth.probe' : false,
646
+ 'auth.scopes' : false,
647
+ 'catalog.prices' : false,
648
+ 'catalog.products' : false,
649
+ 'catalog.promotions' : false,
650
+ 'inbound.handle' : false,
651
+ 'inbound.topic' : false,
652
+ 'inbound.verify' : false,
653
+ 'lifecycle.cleanup' : false,
654
+ 'lifecycle.register' : false,
655
+ 'lifecycle.rehydrate' : false
656
+ },
657
+ setup : [
658
+ 'Press Connect. Drawbridge generates a signing secret and shows it here.',
659
+ 'Copy the secret into your own endpoint.',
660
+ '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.'
661
+ ],
662
+ slug : 'webhook',
663
+ steps : {
664
+ 'step.webhook.send' : {
665
+ billable : true,
666
+ key : 'Send webhook',
667
+ queue : 'webhook',
668
+ returns : [],
669
+ settings : {
670
+ url : { format : 'url', required : true, type : 'string' }
671
+ },
672
+ triggers : [ 'lead.insert', 'lead.delete' ]
673
+ }
674
+ },
675
+ // The card the connection page raises. Before connecting it explains what
676
+ // pressing Connect will do; afterwards it states the verification the
677
+ // merchant's own endpoint has to perform, because a signed payload nobody
678
+ // checks is an unsigned payload.
679
+ tasks : ({ settings }) => ( settings?.secret
680
+ ? [
681
+ {
682
+ message : 'Compute HMAC-SHA256( secret, body ) and compare against the X-Drawbridge-Signature header to confirm each payload.',
683
+ title : 'Requests must be verified',
684
+ type : 'warning'
685
+ }
686
+ ]
687
+ : [
688
+ {
689
+ message : 'Connect to generate a signing secret. Drawbridge signs every webhook it sends with it.',
690
+ title : 'Webhook signing'
691
+ }
692
+ ]
693
+ ),
694
+ title : 'Webhooks'
695
+ };
696
+
697
+ // Every connection, one file each, and this is the whole registry.
698
+ //
699
+ // It lives in utils rather than in the api because BOTH sides need it and they
700
+ // cannot import each other. The api renders the catalog, validates step settings
701
+ // and redacts stored values; sync routes a step to a queue and runs it. Before
702
+ // this, adding one vendor meant editing nine places across two repos and a third
703
+ // for the form, and the two halves could disagree — a step the api would happily
704
+ // persist that sync had no route for is a workflow that silently never runs.
705
+ //
706
+ // WHAT LIVES HERE is everything true about a vendor regardless of environment:
707
+ // its copy, the fields it stores, and the steps it contributes. WHAT DOES NOT is
708
+ // anything that reads process.env — image origins, OAuth redirect urls, whether
709
+ // the integration is configured at all. Those are deployment facts, they differ
710
+ // per environment, and a package baked at publish time is the wrong place for
711
+ // them. A manifest names what it needs (`requires`) and the api resolves it.
712
+ //
713
+ // WHAT SYNC OWNS is the step HANDLERS. They need vendor SDKs, a queue, a
714
+ // controller and a logger, and putting those behind a published package would
715
+ // make every consumer carry them. The manifest declares the step and sync
716
+ // implements it — and because the declaration is the source of truth, a declared
717
+ // step with no handler is a failing test rather than a workflow that quietly
718
+ // does nothing.
719
+
720
+ // The queues sync runs. A step routes to exactly one, and naming them here is
721
+ // what lets sync derive its routing table instead of maintaining a parallel copy
722
+ // that can fall out of step with the catalog.
723
+ const QUEUES = [ 'connection', 'notification', 'segment', 'webhook' ];
724
+
725
+ // WHAT A CONNECTION MUST DECLARE. Thrown at import rather than discovered by a
726
+ // merchant looking at a broken card, or by a workflow that accepted a step it
727
+ // could never run.
728
+ const build = ( manifest ) => {
729
+
730
+ if( ! manifest?.slug ) throw new Error( 'A connection needs a slug' );
731
+ if( ! manifest?.title ) throw new Error( manifest.slug + ' needs a title' );
732
+ if( ! manifest?.feature ) throw new Error( manifest.slug + ' needs a plan feature key' );
733
+ if( ! manifest?.excerpt ) throw new Error( manifest.slug + ' needs an excerpt for its card' );
734
+
735
+ if( ! Array.isArray( manifest?.description ) || ! manifest.description.length ){
736
+
737
+ throw new Error( manifest.slug + ' needs a description — an array of paragraphs for its page' );
738
+
739
+ }
740
+
741
+ for( const field of manifest.fields || [] ){
742
+
743
+ if( ! field?.key || ! field?.label ){
744
+
745
+ throw new Error( manifest.slug + ' declares a field with no key or label' );
746
+
747
+ }
748
+
749
+ // An editable field must name an input the form can actually render. A
750
+ // kind nobody implemented falls through to a text box, which is how a
751
+ // merchant ends up typing the word true into a toggle.
752
+ if( field.input && ! INPUTS.includes( field.input ) ){
753
+
754
+ throw new Error( manifest.slug + '.' + field.key + ' declares an unknown input: ' + field.input + ' — one of ' + INPUTS.join( ', ' ) );
755
+
756
+ }
757
+
758
+ // A choice with nothing to choose from renders an empty dropdown, which
759
+ // looks like a loading state that never resolves.
760
+ if( field.input === 'select' && ! ( field.options || [] ).length ){
761
+
762
+ throw new Error( manifest.slug + '.' + field.key + ' is a select and must declare options' );
763
+
764
+ }
765
+
766
+ }
767
+
768
+ // THE ICON RIDES WITH THE MANIFEST, so a vendor cannot name an asset nobody
769
+ // added — which is what the old arrangement allowed, with the markup in one
770
+ // repo and the file in another.
771
+ //
772
+ // Checked for the three things that actually break a card:
773
+ // it must be an svg a filename here means the file is elsewhere again
774
+ // it must carry a viewBox without one it will not scale into the 50px tile
775
+ // it must not wrap a raster Figma exports a placed bitmap inside an <svg>
776
+ // shell, which looks like a vector, weighs 90KB and
777
+ // blurs exactly like the png it actually is
778
+ if( typeof manifest?.icon !== 'string' || ! manifest.icon.includes( '<svg' ) ){
779
+
780
+ throw new Error( manifest.slug + ' needs an icon — the svg markup itself, not a path to one' );
781
+
782
+ }
783
+
784
+ if( ! manifest.icon.includes( 'viewBox' ) ){
785
+
786
+ throw new Error( manifest.slug + ' icon has no viewBox, so it cannot scale' );
787
+
788
+ }
789
+
790
+ if( manifest.icon.includes( '<image' ) ){
791
+
792
+ throw new Error( manifest.slug + ' icon wraps a raster — re-export it as vector shapes' );
793
+
794
+ }
795
+
796
+ if( ! CATEGORIES.includes( manifest?.category ) ){
797
+
798
+ throw new Error( manifest.slug + ' needs a category — one of ' + CATEGORIES.join( ', ' ) );
799
+
800
+ }
801
+
802
+ // One field says how a vendor is connected, and it is auth.type. `connect`
803
+ // carries the COPY around connecting (errors, where a link goes); a `type`
804
+ // there too is a second answer to one question, and two answers drift.
805
+ if( manifest?.connect?.type ){
806
+
807
+ throw new Error( manifest.slug + ' declares connect.type — that is auth.type now' );
808
+
809
+ }
810
+
811
+ if( ! AUTH_TYPES.includes( manifest?.auth?.type ) ){
812
+
813
+ throw new Error( manifest.slug + ' needs auth.type — one of ' + AUTH_TYPES.join( ', ' ) );
814
+
815
+ }
816
+
817
+ // An oauth vendor declares the whole flow, so one implementation serves all
818
+ // of them. Half a descriptor is worse than none: it looks connectable and
819
+ // fails at the callback, which is the point a merchant has already left the
820
+ // dashboard and consented.
821
+ if( manifest.auth.type === 'oauth' ){
822
+
823
+ for( const field of OAUTH_FIELDS ){
824
+
825
+ if( ! manifest.auth.oauth?.[ field ] ){
826
+
827
+ throw new Error( manifest.slug + ' is oauth and must declare auth.oauth.' + field );
828
+
829
+ }
830
+
831
+ }
832
+
833
+ }
834
+
835
+ // A vendor that receives from the outside must say where it puts the event
836
+ // name. Without it the receiver has nothing to dispatch on, and the failure
837
+ // is a request accepted and dropped rather than an error.
838
+ if( manifest.supports?.[ 'inbound.topic' ] && ! manifest.inbound?.headers?.topic ){
839
+
840
+ throw new Error( manifest.slug + ' supports inbound.topic but declares no inbound.headers.topic' );
841
+
842
+ }
843
+
844
+ if( manifest.supports?.[ 'inbound.verify' ] && ! manifest.inbound?.headers?.signature ){
845
+
846
+ throw new Error( manifest.slug + ' supports inbound.verify but declares no inbound.headers.signature' );
847
+
848
+ }
849
+
850
+ // How to get the credential, in the merchant's words. A connection page that
851
+ // cannot say where to find an API key sends somebody to a vendor's docs
852
+ // written for a different integration.
853
+ if( ! Array.isArray( manifest?.setup ) || ! manifest.setup.length ){
854
+
855
+ throw new Error( manifest.slug + ' needs a setup guide — an array of steps for its page' );
856
+
857
+ }
858
+
859
+ // HOOKS A MANIFEST CAN CARRY ITSELF.
860
+ //
861
+ // Not every hook can live here — a step handler needs a queue, a controller
862
+ // and vendor SDKs, and putting those behind a published package makes every
863
+ // consumer carry them. But the hooks that are pure or plain HTTP can, and
864
+ // auth.connect is the one that matters most: it is the only vendor-specific
865
+ // step in an OAuth callback, so putting it here is what lets ONE route serve
866
+ // every OAuth vendor instead of one route each.
867
+ //
868
+ // Keyed flat ('auth.connect') to match the vocabulary and the supports map,
869
+ // so the three cannot drift apart in naming.
870
+ for( const [ name, hook ] of Object.entries( manifest.hooks || {} ) ){
871
+
872
+ if( ! HOOK_NAMES.includes( name ) ){
873
+
874
+ throw new Error( manifest.slug + ' implements an unknown hook: ' + name );
875
+
876
+ }
877
+
878
+ if( typeof hook !== 'function' ){
879
+
880
+ throw new Error( manifest.slug + ' declares hook ' + name + ' but it is not a function' );
881
+
882
+ }
883
+
884
+ // Implementing a hook you declared unsupported is the support matrix
885
+ // lying, and the matrix is what a caller reads to decide whether to
886
+ // bother asking. Caught here rather than discovered as a hook that is
887
+ // never called.
888
+ if( manifest.supports?.[ name ] !== true ){
889
+
890
+ throw new Error( manifest.slug + ' implements ' + name + ' but declares supports[ \'' + name + '\' ] false' );
891
+
892
+ }
893
+
894
+ }
895
+
896
+ // THE UNIFORM SURFACE. Every connection answers every hook in the vocabulary,
897
+ // with true where it implements one and false where it deliberately does not.
898
+ // A missing entry is rejected rather than defaulted, because a default is
899
+ // exactly the silence this exists to remove: it would be impossible to tell a
900
+ // vendor that declined a hook from one written before the hook existed.
901
+ const supports = manifest.supports || {};
902
+
903
+ for( const name of HOOK_NAMES ){
904
+
905
+ if( typeof supports[ name ] !== 'boolean' ){
906
+
907
+ throw new Error( manifest.slug + ' must declare supports[ \'' + name + '\' ] as true or false' );
908
+
909
+ }
910
+
911
+ }
912
+
913
+ for( const name of Object.keys( supports ) ){
914
+
915
+ if( ! HOOK_NAMES.includes( name ) ){
916
+
917
+ throw new Error( manifest.slug + ' declares an unknown hook: ' + name );
918
+
919
+ }
920
+
921
+ }
922
+
923
+ for( const [ type, step ] of Object.entries( manifest.steps || {} ) ){
924
+
925
+ if( ! type.startsWith( 'step.' ) ){
926
+
927
+ throw new Error( manifest.slug + ' declares a step type that is not step.<domain>.<verb>: ' + type );
928
+
929
+ }
930
+
931
+ if( ! step?.key ) throw new Error( manifest.slug + ' step ' + type + ' needs a key — the label the builder shows' );
932
+
933
+ if( ! QUEUES.includes( step?.queue ) ){
934
+
935
+ throw new Error( manifest.slug + ' step ' + type + ' needs a queue — one of ' + QUEUES.join( ', ' ) );
936
+
937
+ }
938
+
939
+ }
940
+
941
+ return Object.freeze({
942
+ ...manifest,
943
+ fields : Object.freeze( manifest.fields || [] ),
944
+ hooks : Object.freeze( manifest.hooks || {} ),
945
+ inbound : Object.freeze( manifest.inbound || {} ),
946
+ setup : Object.freeze( manifest.setup || [] ),
947
+ supports : Object.freeze( supports ),
948
+ requires : Object.freeze( manifest.requires || [] ),
949
+ steps : Object.freeze( manifest.steps || {} )
950
+ });
951
+
952
+ };
953
+
954
+ const connections = Object.freeze({
955
+ klaviyo : build( klaviyo ),
956
+ mailchimp : build( mailchimp ),
957
+ shopify : build( shopify ),
958
+ webhook : build( webhook )
959
+ });
960
+
961
+ // A step type belongs to exactly one vendor.
962
+ //
963
+ // This is checked because the current naming HIDES the problem rather than
964
+ // solving it: every commerce step is namespaced by vendor
965
+ // (step.shopify.customer.insert), so a collision is impossible only for as long
966
+ // as that holds. The moment a capability is named for what it does rather than
967
+ // who does it — step.commerce.customer.insert, which is where this should go —
968
+ // two vendors declaring it would silently collapse into one entry in stepQueues
969
+ // and one of them would route nowhere.
970
+ //
971
+ // Fail at import instead. When the neutral names land, this is the guard that
972
+ // makes the ambiguity visible on the first line of the first test run.
973
+ ( () => {
974
+
975
+ const owners = {};
976
+
977
+ for( const [ slug, manifest ] of Object.entries( connections ) ){
978
+
979
+ for( const type of Object.keys( manifest.steps ) ){
980
+
981
+ if( owners[ type ] ){
982
+
983
+ throw new Error( 'Step ' + type + ' is declared by both ' + owners[ type ] + ' and ' + slug );
984
+
985
+ }
986
+
987
+ owners[ type ] = slug;
988
+
989
+ }
990
+
991
+ }
992
+
993
+ })();
994
+
995
+ // The vendors whose environment is actually configured. Every consumer asks this
996
+ // the same way, so "is Shopify available" has one answer rather than one per
997
+ // repo — the api gated it on four env vars and sync inferred it from a different
998
+ // signal, which is how the two drifted.
999
+ const availableConnections = ( env = {} ) => Object.fromEntries(
1000
+ Object.entries( connections ).filter(
1001
+ ( [ , manifest ] ) => manifest.requires.every( ( name ) => Boolean( env[ name ] ) )
1002
+ )
1003
+ );
1004
+
1005
+ // Per-slug allowlist of stored setting keys safe to return in an API response.
1006
+ // DERIVED from each vendor's own field declaration — a field is public unless it
1007
+ // says `redact : true`. An unknown slug gets an empty allowlist, so a leftover
1008
+ // document for a withdrawn vendor redacts entirely on its way out.
1009
+ const publicSettingsBySlug = Object.fromEntries(
1010
+ Object.entries( connections ).map( ( [ slug, manifest ] ) => [
1011
+ slug,
1012
+ manifest.fields.filter( ( field ) => ! field.redact ).map( ( field ) => field.key )
1013
+ ] )
1014
+ );
1015
+
1016
+ // Every step every configured vendor contributes, flattened and stamped with the
1017
+ // slug that owns it. The api builds its workflow catalog from this and sync
1018
+ // builds its routing table from it, so a step cannot exist on one side only.
1019
+ const connectionSteps = ( env = {} ) => Object.entries( availableConnections( env ) )
1020
+ .flatMap( ( [ slug, manifest ] ) => Object.entries( manifest.steps )
1021
+ .map( ( [ type, step ] ) => ({ ...step, slug, type }) )
1022
+ );
1023
+
1024
+ // Which vendors implement a given hook. The uniform surface makes this total —
1025
+ // every vendor appears in exactly one of the two lists, never neither.
1026
+ const hookSupport = ( name ) => ({
1027
+ no : Object.keys( connections ).filter( ( slug ) => ! connections[ slug ].supports[ name ] ),
1028
+ yes : Object.keys( connections ).filter( ( slug ) => connections[ slug ].supports[ name ] )
1029
+ });
1030
+
1031
+ // A vendor's fields, described for the dashboard. Served so one generic form
1032
+ // covers every vendor — a new connection needs no new component.
1033
+ //
1034
+ // EVERY field, not only the editable ones. A field without an `input` is not
1035
+ // absent from the page, it is READ-ONLY there: the webhook signing secret is
1036
+ // displayed with a copy button, the Shopify store domain as text. The form
1037
+ // decides which of the two a field is; this only describes it.
1038
+ //
1039
+ // Safe to send for secret fields because a descriptor is a key and a label. The
1040
+ // VALUE is withheld independently by whatever redacts stored settings, and a
1041
+ // test asserts no descriptor ever carries one.
1042
+ const connectFields = ( slug ) => ( connections[ slug ]?.fields || [] )
1043
+ .map( ({ copy, from, input, key, label, message, options, placeholder, redact, required }) => ({
1044
+ ...( copy && { copy : true }),
1045
+ ...( from && { from }),
1046
+ ...( input && { input }),
1047
+ key,
1048
+ label,
1049
+ ...( message && { message }),
1050
+ ...( options && { options }),
1051
+ ...( placeholder && { placeholder }),
1052
+ required : Boolean( required ),
1053
+ // A UI hint, not a leak: the form uses it to stop requiring the field once
1054
+ // the connection exists, and to say "leave blank to keep" — because the GET
1055
+ // response deliberately never returns the stored value.
1056
+ secret : Boolean( redact )
1057
+ }) );
1058
+
1059
+ // Run a vendor's hook, or say why it did not run.
1060
+ //
1061
+ // ONE CALL SURFACE. A route, a worker or a form handler asks for a hook by name
1062
+ // and never names a vendor — which is what lets a variable endpoint like
1063
+ // /connection/:slug/callback serve every vendor that declares one.
1064
+ //
1065
+ // The four outcomes are the point. "unsupported", "unimplemented", "failed" and
1066
+ // a result are different answers to why there is no data, and collapsing them is
1067
+ // how "this vendor cannot do that" becomes indistinguishable from "it broke".
1068
+ const runHook = async ( slug, name, args = {} ) => {
1069
+
1070
+ const manifest = connections[ slug ];
1071
+
1072
+ if( ! manifest ) return { outcome : OUTCOMES.unsupported, reason : 'no such connection: ' + slug };
1073
+
1074
+ if( ! manifest.supports?.[ name ] ) return { outcome : OUTCOMES.unsupported, reason : slug + ' does not implement ' + name };
1075
+
1076
+ const hook = manifest.hooks?.[ name ];
1077
+
1078
+ // Declared supported, implemented somewhere else. Sync owns the step handlers
1079
+ // and lifecycle jobs, so this is a legitimate answer here rather than a fault
1080
+ // — the caller in that repo has its own registry.
1081
+ if( typeof hook !== 'function' ){
1082
+
1083
+ return { outcome : OUTCOMES.unimplemented, reason : slug + ' implements ' + name + ' outside this package' };
1084
+
1085
+ }
1086
+
1087
+ try {
1088
+
1089
+ return { outcome : OUTCOMES.answered, result : await hook( args ) };
1090
+
1091
+ } catch ( error ) {
1092
+
1093
+ return { error : error?.message || 'failed', outcome : OUTCOMES.failed };
1094
+
1095
+ }
1096
+
1097
+ };
1098
+
1099
+ // step type → queue name. Sync's router reads this instead of a hand-kept map.
1100
+ const stepQueues = ( env = {} ) => Object.fromEntries(
1101
+ connectionSteps( env ).map( ( step ) => [ step.type, step.queue ] )
1102
+ );
1103
+
1104
+ // Merchant-facing scope-drift copy.
1105
+ //
1106
+ // THIS IS A CROSS-REPO CONTRACT. drawbridge-sync writes it onto the connection
1107
+ // document (reconcileConnectionScopes) and drawbridge-api reads the same text
1108
+ // back out, so the two repos each held a copy of one string and a change to
1109
+ // either produced a connection whose message changed as the document converged.
1110
+ // One copy, here, because neither repo can import the other.
1111
+ const scopesMessage = 'Shopify permissions are out of date. Open the Drawbridge app in your Shopify admin to approve the updated permissions.';
1112
+
1113
+ // Merge incoming settings into stored ones. Keys whose incoming value is empty
1114
+ // are PRESERVED, which is how "leave blank to keep your current key" works —
1115
+ // the GET response never returns a secret, so blank has to mean keep rather
1116
+ // than clear.
1117
+ const mergeSettings = ({ existing, incoming }) => {
1118
+
1119
+ if( ! existing || typeof existing !== 'object' ) return incoming;
1120
+
1121
+ const merged = { ...existing };
1122
+
1123
+ for( const [ key, value ] of Object.entries( incoming || {} ) ){
1124
+
1125
+ if( value !== undefined && value !== null && value !== '' ){
1126
+
1127
+ merged[ key ] = value;
1128
+
1129
+ }
1130
+ }
1131
+ return merged;
1132
+
1133
+ };
1134
+
1135
+ // Project stored settings to the keys that are safe to return, per slug.
1136
+ //
1137
+ // THE SECURITY BOUNDARY. It derives from each vendor's own field declaration —
1138
+ // public unless the field says `redact` — so a credential added to a form
1139
+ // cannot be forgotten here. An unknown slug gets an empty allowlist, so a
1140
+ // leftover document for a withdrawn vendor redacts entirely on its way out.
1141
+ const redactSettings = ({ slug, settings }) => {
1142
+
1143
+ if( ! settings || typeof settings !== 'object' ) return settings;
1144
+
1145
+ const allowed = publicSettingsBySlug[ slug ] || [];
1146
+
1147
+ return Object.fromEntries(
1148
+ Object.entries( settings ).filter( ( [ key ] ) => allowed.includes( key ) )
1149
+ );
1150
+
1151
+ };
1152
+
1153
+ // Connection-record fields safe to return in an API response. Defense in depth:
1154
+ // anything absent here is stripped, so an internal field added to the document
1155
+ // later does not reach a browser by default.
1156
+ //
1157
+ // `docs` and `links` were listed and set by no vendor and read by nothing —
1158
+ // dropped rather than carried forward as keys that look supported.
1159
+ const publicConnectionKeys = Object.freeze([
1160
+ 'actions',
1161
+ 'category',
1162
+ 'confirm',
1163
+ 'connect',
1164
+ 'createdAt',
1165
+ 'errors',
1166
+ 'description',
1167
+ 'excerpt',
1168
+ 'fields',
1169
+ 'group',
1170
+ 'id',
1171
+ 'image',
1172
+ 'label',
1173
+ 'setup',
1174
+ 'settings',
1175
+ 'shop',
1176
+ 'slug',
1177
+ 'status',
1178
+ 'tasks',
1179
+ 'title',
1180
+ 'updatedAt',
1181
+ 'warnings'
1182
+ ]);
1183
+
1184
+ const projectConnection = ( record ) => {
1185
+
1186
+ if( ! record || typeof record !== 'object' ) return record;
1187
+
1188
+ return publicConnectionKeys.reduce(
1189
+ ( accumulator, key ) => {
1190
+
1191
+ if( record[ key ] !== undefined ){
1192
+
1193
+ accumulator[ key ] = record[ key ];
1194
+
1195
+ }
1196
+ return accumulator;
1197
+
1198
+ },
1199
+ {}
1200
+ );
1201
+
1202
+ };
1203
+
1204
+ // Resolve a manifest against its stored data: any field declared as a function
1205
+ // is called with the data, everything else passes through. This lets a field
1206
+ // pivot on database state — webhook `tasks` depend on whether a secret exists —
1207
+ // while leaving static metadata directly readable.
1208
+ //
1209
+ // Catalog wiring is dropped rather than resolved. `fields` in particular must
1210
+ // never reach the output under that name: the connection DOCUMENT's own
1211
+ // `settings` is spread over this downstream, and two different things sharing a
1212
+ // key is how a redaction quietly stops applying.
1213
+ const resolveConnection = ( item, data ) => {
1214
+
1215
+ if( ! item ) return item;
1216
+
1217
+ return Object.fromEntries(
1218
+ Object.entries( item )
1219
+ .filter( ( [ key ] ) => ! [ 'auth', 'enabled', 'fields', 'inbound', 'requires', 'steps', 'supports' ].includes( key ) )
1220
+ .map( ( [ key, value ] ) => [
1221
+ key,
1222
+ ( typeof value === 'function' ? value( data ) : value )
1223
+ ] )
1224
+ );
1225
+
1226
+ };
1227
+
1228
+ export { AUTH_TYPES, CATEGORIES, HOOKS, HOOK_NAMES, INPUTS, OAUTH_FIELDS, OUTCOMES, availableConnections, build, connectFields, connectionSteps, connections, hookSupport, mergeSettings, projectConnection, publicConnectionKeys, publicSettingsBySlug, redactSettings, resolveConnection, runHook, scopesMessage, stepQueues };