@superdurable/connector-intuit-mailchimp 0.0.0-stage → 0.1.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,829 @@
1
+ import {
2
+ CampaignSchema,
3
+ ConfigSchema,
4
+ Connection,
5
+ ConnectorID,
6
+ GetMemberBranch,
7
+ GetMemberBranchDefect,
8
+ GetMemberBranchFound,
9
+ GetMemberBranchInvalidResponse,
10
+ GetMemberBranchNotFound,
11
+ GetMemberBranchProviderRejected,
12
+ GetMemberDefinition,
13
+ GetMemberInputSchema,
14
+ GetMemberMetadata,
15
+ ListMembersBranch,
16
+ ListMembersBranchDefect,
17
+ ListMembersBranchInvalidResponse,
18
+ ListMembersBranchListed,
19
+ ListMembersBranchNotFound,
20
+ ListMembersBranchProviderRejected,
21
+ ListMembersDefinition,
22
+ ListMembersInputSchema,
23
+ ListMembersMetadata,
24
+ ListMembersOutputSchema,
25
+ MarketingPermissionInputSchema,
26
+ MemberSchema,
27
+ ProviderID,
28
+ SendCampaignBranch,
29
+ SendCampaignBranchAlreadySent,
30
+ SendCampaignBranchDefect,
31
+ SendCampaignBranchInvalidResponse,
32
+ SendCampaignBranchNotFound,
33
+ SendCampaignBranchNotSendable,
34
+ SendCampaignBranchProviderRejected,
35
+ SendCampaignBranchSent,
36
+ SendCampaignBranchUncertain,
37
+ SendCampaignDefinition,
38
+ SendCampaignInputSchema,
39
+ SendCampaignMetadata,
40
+ SendCampaignOutputSchema,
41
+ UpdateMemberTagsBranch,
42
+ UpdateMemberTagsBranchDefect,
43
+ UpdateMemberTagsBranchInvalidResponse,
44
+ UpdateMemberTagsBranchNotFound,
45
+ UpdateMemberTagsBranchProviderRejected,
46
+ UpdateMemberTagsBranchUpdated,
47
+ UpdateMemberTagsDefinition,
48
+ UpdateMemberTagsInputSchema,
49
+ UpdateMemberTagsMetadata,
50
+ UpdateMemberTagsOutputSchema,
51
+ UpsertMemberBranch,
52
+ UpsertMemberBranchDefect,
53
+ UpsertMemberBranchInvalidResponse,
54
+ UpsertMemberBranchProviderRejected,
55
+ UpsertMemberBranchUpserted,
56
+ UpsertMemberDefinition,
57
+ UpsertMemberInputSchema,
58
+ UpsertMemberMetadata,
59
+ UpsertMemberOutputSchema,
60
+ decodeCredentials,
61
+ newConnection,
62
+ newConnectionWithOperations,
63
+ newProjectConnection
64
+ } from "./chunk-FFHIGEZ2.js";
65
+
66
+ // src/schema.ts
67
+ import { z } from "zod";
68
+ var ListMembersInputSchema2 = ListMembersInputSchema.safeExtend({
69
+ changedSince: z.string().nullable().optional(),
70
+ optedInSince: z.string().nullable().optional()
71
+ });
72
+
73
+ // src/generated/steps.ts
74
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
75
+ function newGetMemberStep(configuration) {
76
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
77
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
78
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getMember(), connection: connection.reference, branches: [
79
+ goToBranch("found", found),
80
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
81
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
82
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
83
+ ...defect ? [goToBranch("defect", defect)] : []
84
+ ] });
85
+ }
86
+ function newListMembersStep(configuration) {
87
+ const { connection, connectionName, listed, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
88
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
89
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listMembers(), connection: connection.reference, branches: [
90
+ goToBranch("listed", listed),
91
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
92
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
93
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
94
+ ...defect ? [goToBranch("defect", defect)] : []
95
+ ] });
96
+ }
97
+ function newUpsertMemberStep(configuration) {
98
+ const { connection, connectionName, upserted, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
99
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
100
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.upsertMember(), connection: connection.reference, branches: [
101
+ goToBranch("upserted", upserted),
102
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
103
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
104
+ ...defect ? [goToBranch("defect", defect)] : []
105
+ ] });
106
+ }
107
+ function newUpdateMemberTagsStep(configuration) {
108
+ const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
109
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
110
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateMemberTags(), connection: connection.reference, branches: [
111
+ goToBranch("updated", updated),
112
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
113
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
114
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
115
+ ...defect ? [goToBranch("defect", defect)] : []
116
+ ] });
117
+ }
118
+ function newSendCampaignStep(configuration) {
119
+ const { connection, connectionName, sent, alreadySent, notSendable, notFound, providerRejected, invalidResponse, uncertain, defect, ...stepConfiguration } = configuration;
120
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
121
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.sendCampaign(), connection: connection.reference, branches: [
122
+ goToBranch("sent", sent),
123
+ ...alreadySent ? [goToBranch("alreadySent", alreadySent)] : [],
124
+ ...notSendable ? [goToBranch("notSendable", notSendable)] : [],
125
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
126
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
127
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
128
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : [],
129
+ ...defect ? [goToBranch("defect", defect)] : []
130
+ ] });
131
+ }
132
+
133
+ // src/project.ts
134
+ import { SecretString } from "@superdurable/connectors-sdk";
135
+ import { z as z2 } from "zod";
136
+
137
+ // src/client.ts
138
+ import { AddressRefusal, BodyTooLargeError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
139
+
140
+ // src/operations.ts
141
+ import { createHash } from "crypto";
142
+ import { newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry, zeroReceipt } from "@superdurable/connectors-sdk";
143
+
144
+ // src/go-parity.ts
145
+ import { isIP } from "net";
146
+ var atomCharacter = /[\x21-\x7e]/;
147
+ var atomSpecials = /* @__PURE__ */ new Set([...'()<>[]:;@\\,"']);
148
+ function isGoBareEmailAddress(value) {
149
+ const separator = value.indexOf("@");
150
+ if (separator <= 0 || separator !== value.lastIndexOf("@")) return false;
151
+ const local = value.slice(0, separator);
152
+ const domain = value.slice(separator + 1);
153
+ const isAtom = (part) => !!part && !part.startsWith(".") && !part.endsWith(".") && !part.includes("..") && [...part].every((character) => {
154
+ const code = character.codePointAt(0);
155
+ return code >= 128 ? !(code >= 55296 && code <= 57343) : atomCharacter.test(character) && !atomSpecials.has(character);
156
+ });
157
+ if (!isAtom(local)) return false;
158
+ if (domain.startsWith("[") && domain.endsWith("]")) return isIP(domain.slice(1, -1)) !== 0;
159
+ return isAtom(domain);
160
+ }
161
+ function goSimpleLower(value) {
162
+ return [...value].map((character) => character === "\u0130" ? "i" : character.toLowerCase()).join("");
163
+ }
164
+ function goTrimSpace(value) {
165
+ return value.replace(/^\p{White_Space}+|\p{White_Space}+$/gu, "");
166
+ }
167
+ function goRFC3339UTC(value) {
168
+ const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{1,2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|[+-]\d{2}:\d{2})$/.exec(value);
169
+ if (!match) throw new Error("invalid timestamp");
170
+ const year = Number(match[1]);
171
+ const month = Number(match[2]);
172
+ const day = Number(match[3]);
173
+ const hour = Number(match[4]);
174
+ const minute = Number(match[5]);
175
+ const second = Number(match[6]);
176
+ const fractionText = match[7];
177
+ const zone = match[8];
178
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
179
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
180
+ if (month < 1 || month > 12 || day < 1 || day > days[month - 1] || hour > 23 || minute > 59 || second > 59) throw new Error("invalid timestamp");
181
+ const offsetHours = zone === "Z" ? 0 : Number(zone.slice(1, 3));
182
+ const offsetMinutes = zone === "Z" ? 0 : Number(zone.slice(4));
183
+ if (offsetHours > 24 || offsetMinutes > 60) throw new Error("invalid timestamp");
184
+ const instant = /* @__PURE__ */ new Date(0);
185
+ instant.setUTCFullYear(year, month - 1, day);
186
+ instant.setUTCHours(hour, minute, second);
187
+ instant.setTime(instant.getTime() - (zone.startsWith("-") ? -1 : 1) * (offsetHours * 60 + offsetMinutes) * 6e4);
188
+ if (Number.isNaN(instant.getTime()) || instant.getUTCFullYear() < 0 || instant.getUTCFullYear() > 9999) throw new Error("invalid timestamp");
189
+ const fraction = fractionText?.slice(0, 9).replace(/0+$/, "");
190
+ return instant.toISOString().slice(0, 19) + (fraction ? `.${fraction}` : "") + "Z";
191
+ }
192
+
193
+ // src/operations.ts
194
+ var emptyMember = { subscriberHash: "", emailAddress: "", status: "", tagCount: 0, listId: "" };
195
+ var emptyPage = { members: [], totalItems: 0 };
196
+ var emptyUpsert = { member: emptyMember };
197
+ var emptyTags = { subscriberHash: "" };
198
+ var emptyCampaign = { id: "", type: "", status: "", recipientCount: 0, emailsSent: 0 };
199
+ var emptySend = { campaign: emptyCampaign };
200
+ var readableStatuses = /* @__PURE__ */ new Set(["subscribed", "unsubscribed", "pending", "transactional", "cleaned", "archived"]);
201
+ var writableStatuses = /* @__PURE__ */ new Set(["subscribed", "unsubscribed", "pending", "transactional"]);
202
+ var memberFields = "members.id,members.email_address,members.contact_id,members.full_name,members.web_id,members.email_type,members.status,members.merge_fields,members.vip,members.language,members.timestamp_signup,members.timestamp_opt,members.last_changed,members.tags_count,members.tags,members.list_id,list_id,total_items";
203
+ var campaignFields = "id,web_id,type,status,emails_sent,create_time,send_time,settings.title,settings.subject_line,recipients.list_id,recipients.list_name,recipients.recipient_count";
204
+ var GetMemberOperation = class {
205
+ /** Bind the client. */
206
+ constructor(client) {
207
+ this.client = client;
208
+ }
209
+ client;
210
+ /** Return the manifest definition. */
211
+ definition() {
212
+ return GetMemberDefinition;
213
+ }
214
+ /** Read by Mailchimp subscriber hash. */
215
+ async invoke(call, input) {
216
+ const operation = "getMember";
217
+ const validation = validateMemberAddress(input.listId, input.emailAddress);
218
+ if (validation) return newQueryBranch("defect", emptyMember, zeroReceipt(), mailchimpFailure(operation, "VALIDATION", validation));
219
+ const connection = await this.client.resolveConnection(call);
220
+ if (!connection) return credentialQueryDefect(operation, emptyMember);
221
+ const hash = subscriberHash(input.emailAddress);
222
+ const result = await this.client.exchange(call, connection, operation, "GET", memberPath(input.listId, hash));
223
+ const receipt = this.client.receipt(call, result, hash);
224
+ const classified = queryExchange(result, receipt, emptyMember, true);
225
+ if (classified) return classified;
226
+ try {
227
+ return newQueryBranch("found", decodeMember(result.body, hash), receipt);
228
+ } catch {
229
+ return newQueryBranch("invalidResponse", emptyMember, receipt, mailchimpFailure(operation, "PROTOCOL", "Mailchimp returned an invalid contact"));
230
+ }
231
+ }
232
+ };
233
+ var ListMembersOperation = class {
234
+ /** Bind the client. */
235
+ constructor(client) {
236
+ this.client = client;
237
+ }
238
+ client;
239
+ /** Return the manifest definition. */
240
+ definition() {
241
+ return ListMembersDefinition;
242
+ }
243
+ /** Read one page with optional status and time filters. */
244
+ async invoke(call, input) {
245
+ const operation = "listMembers";
246
+ const validation = validateListInput(input);
247
+ if (validation) return newQueryBranch("defect", emptyPage, zeroReceipt(), mailchimpFailure(operation, "VALIDATION", validation));
248
+ const connection = await this.client.resolveConnection(call);
249
+ if (!connection) return credentialQueryDefect(operation, emptyPage);
250
+ const pageSize = input.pageSize || 100;
251
+ const query = new URLSearchParams({ count: String(pageSize), offset: String(input.offset ?? 0), sort_field: "last_changed", sort_dir: "ASC", fields: memberFields });
252
+ if (input.status) query.set("status", input.status);
253
+ if (input.changedSince) query.set("since_last_changed", formatMailchimpTime(input.changedSince));
254
+ if (input.optedInSince) query.set("since_timestamp_opt", formatMailchimpTime(input.optedInSince));
255
+ const result = await this.client.exchange(call, connection, operation, "GET", `/lists/${input.listId}/members`, query);
256
+ const receipt = this.client.receipt(call, result, input.listId);
257
+ const classified = queryExchange(result, receipt, emptyPage, true);
258
+ if (classified) return classified;
259
+ try {
260
+ const page = parseObject(result.body);
261
+ const wires = page.members ?? [];
262
+ if (!Array.isArray(wires) || !Number.isInteger(page.total_items) || Number(page.total_items) < 0 || wires.length > pageSize) throw new Error("invalid page");
263
+ const members = wires.map((wire) => decodeMemberObject(wire, ""));
264
+ const totalItems = Number(page.total_items);
265
+ const offset = (input.offset ?? 0) + members.length;
266
+ return newQueryBranch("listed", { members, totalItems, ...members.length > 0 && offset < totalItems ? { nextOffset: offset } : {} }, receipt);
267
+ } catch {
268
+ return newQueryBranch("invalidResponse", emptyPage, receipt, mailchimpFailure(operation, "PROTOCOL", "Mailchimp returned an invalid page of contacts"));
269
+ }
270
+ }
271
+ };
272
+ var UpsertMemberOperation = class {
273
+ /** Bind the client. */
274
+ constructor(client) {
275
+ this.client = client;
276
+ }
277
+ client;
278
+ /** Return the manifest definition. */
279
+ definition() {
280
+ return UpsertMemberDefinition;
281
+ }
282
+ /** Use the stable Call ID for receipt correlation. */
283
+ idempotencyKey(callId) {
284
+ return callId;
285
+ }
286
+ /** Write one contact without changing an existing subscription unless requested. */
287
+ async invoke(call, input) {
288
+ const operation = "upsertMember";
289
+ const validation = validateUpsertInput(input);
290
+ if (validation) return newMutationBranch("defect", emptyUpsert, zeroReceipt(), mailchimpFailure(operation, "VALIDATION", validation));
291
+ const connection = await this.client.resolveConnection(call);
292
+ if (!connection) return credentialMutationDefect(operation, emptyUpsert);
293
+ const hash = subscriberHash(input.emailAddress);
294
+ const body = {
295
+ email_address: input.emailAddress,
296
+ status_if_new: input.statusIfNew,
297
+ ...input.status ? { status: input.status } : {},
298
+ ...input.mergeFields && Object.keys(input.mergeFields).length ? { merge_fields: input.mergeFields } : {},
299
+ ...input.marketingPermissions?.length ? { marketing_permissions: input.marketingPermissions.map((permission) => ({ marketing_permission_id: permission.marketingPermissionId, enabled: permission.isEnabled })) } : {}
300
+ };
301
+ const query = input.shouldSkipMergeValidation ? new URLSearchParams({ skip_merge_validation: "true" }) : void 0;
302
+ const result = await this.client.exchange(call, connection, operation, "PUT", memberPath(input.listId, hash), query, body);
303
+ const receipt = this.client.receipt(call, result, hash);
304
+ const classified = mutationExchange(result, receipt, emptyUpsert, false);
305
+ if (classified) return classified;
306
+ try {
307
+ return newMutationBranch("upserted", { member: decodeMember(result.body, hash) }, receipt);
308
+ } catch {
309
+ return newMutationBranch("invalidResponse", emptyUpsert, receipt, mailchimpFailure(operation, "PROTOCOL", "Mailchimp accepted the contact but returned an invalid contact"));
310
+ }
311
+ }
312
+ };
313
+ var UpdateMemberTagsOperation = class {
314
+ /** Bind the client. */
315
+ constructor(client) {
316
+ this.client = client;
317
+ }
318
+ client;
319
+ /** Return the manifest definition. */
320
+ definition() {
321
+ return UpdateMemberTagsDefinition;
322
+ }
323
+ /** Use the stable Call ID for receipt correlation. */
324
+ idempotencyKey(callId) {
325
+ return callId;
326
+ }
327
+ /** Declare tag states for one contact. */
328
+ async invoke(call, input) {
329
+ const operation = "updateMemberTags";
330
+ const validation = validateTagsInput(input);
331
+ if (validation) return newMutationBranch("defect", emptyTags, zeroReceipt(), mailchimpFailure(operation, "VALIDATION", validation));
332
+ const connection = await this.client.resolveConnection(call);
333
+ if (!connection) return credentialMutationDefect(operation, emptyTags);
334
+ const hash = subscriberHash(input.emailAddress);
335
+ const tags = [...(input.addTags ?? []).map((name) => ({ name, status: "active" })), ...(input.removeTags ?? []).map((name) => ({ name, status: "inactive" }))];
336
+ const body = { tags, ...input.shouldSuppressAutomations ? { is_syncing: true } : {} };
337
+ const result = await this.client.exchange(call, connection, operation, "POST", `${memberPath(input.listId, hash)}/tags`, void 0, body);
338
+ const receipt = this.client.receipt(call, result, hash);
339
+ const classified = mutationExchange(result, receipt, emptyTags, true);
340
+ if (classified) return classified;
341
+ return newMutationBranch("updated", {
342
+ subscriberHash: hash,
343
+ ...input.addTags?.length ? { activeTags: input.addTags } : {},
344
+ ...input.removeTags?.length ? { inactiveTags: input.removeTags } : {}
345
+ }, receipt);
346
+ }
347
+ };
348
+ var SendCampaignOperation = class {
349
+ /** Bind the client. */
350
+ constructor(client) {
351
+ this.client = client;
352
+ }
353
+ client;
354
+ /** Return the manifest definition. */
355
+ definition() {
356
+ return SendCampaignDefinition;
357
+ }
358
+ /** Use the stable Call ID for receipt correlation. */
359
+ idempotencyKey(callId) {
360
+ return callId;
361
+ }
362
+ /** Read status, checkpoint dispatch, and send only a draft. */
363
+ async invoke(call, input) {
364
+ const operation = "sendCampaign";
365
+ const validation = validateResourceID("campaignId", input.campaignId) || (input.expectedListId ? validateResourceID("expectedListId", input.expectedListId) : "");
366
+ if (validation) return newMutationBranch("defect", emptySend, zeroReceipt(), mailchimpFailure(operation, "VALIDATION", validation));
367
+ const connection = await this.client.resolveConnection(call);
368
+ if (!connection) return credentialMutationDefect(operation, emptySend);
369
+ const query = new URLSearchParams({ fields: campaignFields });
370
+ let earlier = false;
371
+ try {
372
+ const previous = call.context.hasLastHeartbeatValue() ? call.context.getLastHeartbeatValue() : void 0;
373
+ earlier = previous !== void 0 && previous !== null;
374
+ } catch {
375
+ earlier = true;
376
+ }
377
+ const read = await this.client.exchange(call, connection, operation, "GET", `/campaigns/${input.campaignId}`, query);
378
+ const readReceipt = this.client.receipt(call, read, input.campaignId);
379
+ if (earlier) {
380
+ if (read.outcome === "succeeded") {
381
+ try {
382
+ const campaign2 = decodeCampaign(read.body, input.campaignId);
383
+ if (campaign2.status === "sending" || campaign2.status === "sent") return newMutationBranch("alreadySent", { campaign: campaign2 }, readReceipt);
384
+ return newMutationUncertain({ campaign: campaign2 }, mailchimpFailure(operation, "TRANSPORT", "an earlier attempt may have sent the campaign"), readReceipt);
385
+ } catch {
386
+ }
387
+ }
388
+ return newMutationUncertain(emptySend, mailchimpFailure(operation, "TRANSPORT", "an earlier attempt may have sent the campaign and its status could not be read"), readReceipt);
389
+ }
390
+ const classified = mutationExchange(read, readReceipt, emptySend, true);
391
+ if (classified) return classified;
392
+ let campaign;
393
+ try {
394
+ campaign = decodeCampaign(read.body, input.campaignId);
395
+ } catch {
396
+ return newMutationBranch("invalidResponse", emptySend, readReceipt, mailchimpFailure(operation, "PROTOCOL", "Mailchimp returned an invalid campaign, so it was not sent"));
397
+ }
398
+ const output = { campaign };
399
+ if (campaign.status === "sending" || campaign.status === "sent") return newMutationBranch("alreadySent", output, readReceipt);
400
+ const blocker = campaign.status !== "save" ? "the campaign is not a draft" : !["regular", "plaintext", "absplit", "variate"].includes(campaign.type) ? "the campaign type does not send immediately" : input.expectedListId && campaign.listId !== input.expectedListId ? "the campaign targets another audience than expectedListId" : "";
401
+ if (blocker) return newMutationBranch("notSendable", output, readReceipt, mailchimpFailure(operation, "CONFLICT", `${blocker}; nothing was sent`));
402
+ try {
403
+ await call.context.recordHeartbeat({ mailchimpDispatchedCallId: call.id });
404
+ } catch {
405
+ return newMutationRetry(mailchimpFailure(operation, "AVAILABILITY", "Dex did not record the dispatch checkpoint; nothing was sent"));
406
+ }
407
+ const sent = await this.client.exchange(call, connection, operation, "POST", `/campaigns/${input.campaignId}/actions/send`);
408
+ const receipt = this.client.receipt(call, sent, input.campaignId);
409
+ if (sent.outcome === "succeeded") return newMutationBranch("sent", output, receipt);
410
+ if (sent.outcome === "rateLimited" || sent.outcome === "notSent") {
411
+ try {
412
+ await call.context.recordHeartbeat(void 0);
413
+ } catch {
414
+ }
415
+ return newMutationRetry(sent.failure, sent.retryAfterMs);
416
+ }
417
+ if (sent.outcome === "unavailable" || sent.outcome === "invalid") return newMutationUncertain(output, sent.failure, receipt);
418
+ if (sent.outcome === "defect") return newMutationBranch("defect", output, receipt, sent.failure);
419
+ return newMutationBranch(sent.outcome === "notFound" ? "notFound" : "providerRejected", output, receipt, sent.failure);
420
+ }
421
+ };
422
+ function queryExchange(exchange, receipt, zero, hasNotFound) {
423
+ if (exchange.outcome === "succeeded") return void 0;
424
+ if (["rateLimited", "notSent", "unavailable"].includes(exchange.outcome)) return newQueryRetry(exchange.failure, exchange.retryAfterMs);
425
+ const branch = exchange.outcome === "notFound" && hasNotFound ? "notFound" : exchange.outcome === "invalid" ? "invalidResponse" : exchange.outcome === "defect" ? "defect" : "providerRejected";
426
+ return newQueryBranch(branch, zero, receipt, exchange.failure);
427
+ }
428
+ function mutationExchange(exchange, receipt, zero, hasNotFound) {
429
+ if (exchange.outcome === "succeeded") return void 0;
430
+ if (["rateLimited", "notSent", "unavailable"].includes(exchange.outcome)) return newMutationRetry(exchange.failure, exchange.retryAfterMs);
431
+ const branch = exchange.outcome === "notFound" && hasNotFound ? "notFound" : exchange.outcome === "invalid" ? "invalidResponse" : exchange.outcome === "defect" ? "defect" : "providerRejected";
432
+ return newMutationBranch(branch, zero, receipt, exchange.failure);
433
+ }
434
+ function credentialQueryDefect(operation, zero) {
435
+ return newQueryBranch("defect", zero, zeroReceipt(), mailchimpFailure(operation, "AUTHENTICATION", "connection credentials are unavailable"));
436
+ }
437
+ function credentialMutationDefect(operation, zero) {
438
+ return newMutationBranch("defect", zero, zeroReceipt(), mailchimpFailure(operation, "AUTHENTICATION", "connection credentials are unavailable"));
439
+ }
440
+ function validateResourceID(name, value) {
441
+ return /^[A-Za-z0-9]{1,64}$/.test(value) ? "" : `${name} must be a Mailchimp ID of 1 to 64 letters and digits`;
442
+ }
443
+ function validateEmail(value) {
444
+ if (!value || Buffer.byteLength(value) > 254) return "emailAddress must be one email address of at most 254 bytes";
445
+ if (!isGoBareEmailAddress(value)) return "emailAddress must be one bare email address such as jane@example.com";
446
+ return "";
447
+ }
448
+ function validateMemberAddress(listID, email) {
449
+ return validateResourceID("listId", listID) || validateEmail(email);
450
+ }
451
+ function subscriberHash(email) {
452
+ return createHash("md5").update(goSimpleLower(email), "utf8").digest("hex");
453
+ }
454
+ function memberPath(listID, hash) {
455
+ return `/lists/${listID}/members/${hash}`;
456
+ }
457
+ function validateListInput(input) {
458
+ if (validateResourceID("listId", input.listId)) return validateResourceID("listId", input.listId);
459
+ if (input.status && !readableStatuses.has(input.status)) return "status is not a Mailchimp contact status";
460
+ if (input.pageSize !== void 0 && (!Number.isInteger(input.pageSize) || input.pageSize < 0 || input.pageSize > 1e3)) return "pageSize must be 1 to 1000, or zero for 100";
461
+ if (input.offset !== void 0 && (!Number.isInteger(input.offset) || input.offset < 0 || input.offset > 2147483647)) return "offset must be a non-negative number of contacts";
462
+ for (const bound of [input.changedSince, input.optedInSince]) {
463
+ if (!bound) continue;
464
+ try {
465
+ if (timestamp(bound) === "0001-01-01T00:00:00Z") return "time bound is invalid";
466
+ } catch {
467
+ return "time bound is invalid";
468
+ }
469
+ }
470
+ return "";
471
+ }
472
+ function formatMailchimpTime(value) {
473
+ return timestamp(value).slice(0, 19) + "+00:00";
474
+ }
475
+ function validateUpsertInput(input) {
476
+ const addressError = validateMemberAddress(input.listId, input.emailAddress);
477
+ if (addressError) return addressError;
478
+ if (!writableStatuses.has(input.statusIfNew)) return "statusIfNew is required";
479
+ if (input.status && !writableStatuses.has(input.status)) return "status is invalid";
480
+ if ((input.status === "subscribed" || input.status === "pending") && !input.isResubscribeAllowed) return "isResubscribeAllowed is required";
481
+ if (input.mergeFields) {
482
+ if (Object.keys(input.mergeFields).length > 30) return "mergeFields holds at most 30 fields";
483
+ for (const [tag, value] of Object.entries(input.mergeFields)) {
484
+ if (!/^[A-Z0-9_]{1,50}$/.test(tag)) return `merge tag ${tag} is invalid`;
485
+ const validText = (text2) => Buffer.byteLength(text2) <= 1024 && !/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/.test(text2);
486
+ if (typeof value === "string" && validText(value)) continue;
487
+ if (typeof value === "number" && Number.isFinite(value)) continue;
488
+ if (value && typeof value === "object" && !Array.isArray(value) && Object.entries(value).every(([key, text2]) => /^[a-z][a-z0-9_]{0,31}$/.test(key) && typeof text2 === "string" && validText(text2))) continue;
489
+ return `merge field ${tag} is invalid`;
490
+ }
491
+ }
492
+ if ((input.marketingPermissions?.length ?? 0) > 20) return "marketingPermissions holds at most 20 permissions";
493
+ const seen = /* @__PURE__ */ new Set();
494
+ for (const permission of input.marketingPermissions ?? []) {
495
+ const invalid = validateResourceID("marketingPermissionId", permission.marketingPermissionId);
496
+ if (invalid) return invalid;
497
+ if (seen.has(permission.marketingPermissionId)) return "marketing permission repeats";
498
+ seen.add(permission.marketingPermissionId);
499
+ }
500
+ return "";
501
+ }
502
+ function validateTagsInput(input) {
503
+ const addressError = validateMemberAddress(input.listId, input.emailAddress);
504
+ if (addressError) return addressError;
505
+ const tags = [...input.addTags ?? [], ...input.removeTags ?? []];
506
+ if (!tags.length || tags.length > 50) return "addTags and removeTags must hold 1 to 50 tags together";
507
+ const seen = /* @__PURE__ */ new Set();
508
+ for (const tag of tags) {
509
+ if (!tag || Buffer.byteLength(tag) > 100 || goTrimSpace(tag) !== tag || /[\u0000-\u001f\u007f-\u009f]/.test(tag)) return "tag name is invalid";
510
+ const lower = goSimpleLower(tag);
511
+ if (seen.has(lower)) return "tag appears more than once";
512
+ seen.add(lower);
513
+ }
514
+ return "";
515
+ }
516
+ function parseObject(body) {
517
+ const value = JSON.parse(Buffer.from(body).toString("utf8"));
518
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid object");
519
+ return value;
520
+ }
521
+ function text(object2, key) {
522
+ const value = object2[key];
523
+ if (value === void 0 || value === null) return "";
524
+ if (typeof value !== "string") throw new Error(`invalid ${key}`);
525
+ return value;
526
+ }
527
+ function number(object2, key) {
528
+ const value = object2[key];
529
+ if (value === void 0 || value === null) return 0;
530
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new Error(`invalid ${key}`);
531
+ return value;
532
+ }
533
+ function boolean(object2, key) {
534
+ const value = object2[key];
535
+ if (value === void 0 || value === null) return false;
536
+ if (typeof value !== "boolean") throw new Error(`invalid ${key}`);
537
+ return value;
538
+ }
539
+ function object(object2, key) {
540
+ const value = object2[key];
541
+ if (value === void 0 || value === null) return {};
542
+ if (typeof value !== "object" || Array.isArray(value)) throw new Error(`invalid ${key}`);
543
+ return value;
544
+ }
545
+ function timestamp(value) {
546
+ return value ? goRFC3339UTC(value) : void 0;
547
+ }
548
+ function decodeMember(body, hash) {
549
+ return decodeMemberObject(parseObject(body), hash);
550
+ }
551
+ function decodeMemberObject(value, expectedHash) {
552
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid contact");
553
+ const wire = value;
554
+ const id = text(wire, "id");
555
+ if (!/^[0-9a-f]{32}$/.test(id) || expectedHash && id !== expectedHash || !text(wire, "email_address") || !text(wire, "status")) throw new Error("invalid contact");
556
+ if (wire.tags !== void 0 && wire.tags !== null && !Array.isArray(wire.tags)) throw new Error("invalid tags");
557
+ const tags = Array.isArray(wire.tags) ? wire.tags.map((value2) => text(object({ tag: value2 }, "tag"), "name")) : [];
558
+ const mergeFields = wire.merge_fields === void 0 || wire.merge_fields === null ? void 0 : object(wire, "merge_fields");
559
+ return {
560
+ subscriberHash: id,
561
+ emailAddress: text(wire, "email_address"),
562
+ status: text(wire, "status"),
563
+ tagCount: number(wire, "tags_count"),
564
+ listId: text(wire, "list_id"),
565
+ ...text(wire, "contact_id") ? { contactId: text(wire, "contact_id") } : {},
566
+ ...text(wire, "full_name") ? { fullName: text(wire, "full_name") } : {},
567
+ ...text(wire, "email_type") ? { emailType: text(wire, "email_type") } : {},
568
+ ...mergeFields && Object.keys(mergeFields).length ? { mergeFields } : {},
569
+ ...tags.length ? { tags } : {},
570
+ ...boolean(wire, "vip") ? { isVip: true } : {},
571
+ ...text(wire, "language") ? { language: text(wire, "language") } : {},
572
+ ...number(wire, "web_id") ? { webId: number(wire, "web_id") } : {},
573
+ ...timestamp(text(wire, "timestamp_signup")) ? { signedUpAt: timestamp(text(wire, "timestamp_signup")) } : {},
574
+ ...timestamp(text(wire, "timestamp_opt")) ? { optedInAt: timestamp(text(wire, "timestamp_opt")) } : {},
575
+ ...timestamp(text(wire, "last_changed")) ? { lastChangedAt: timestamp(text(wire, "last_changed")) } : {}
576
+ };
577
+ }
578
+ function decodeCampaign(body, expectedID) {
579
+ const wire = parseObject(body);
580
+ const settings = object(wire, "settings");
581
+ const recipients = object(wire, "recipients");
582
+ if (text(wire, "id") !== expectedID || !text(wire, "status") || !text(wire, "type")) throw new Error("invalid campaign");
583
+ return {
584
+ id: expectedID,
585
+ type: text(wire, "type"),
586
+ status: text(wire, "status"),
587
+ recipientCount: number(recipients, "recipient_count"),
588
+ emailsSent: number(wire, "emails_sent"),
589
+ ...number(wire, "web_id") ? { webId: number(wire, "web_id") } : {},
590
+ ...text(settings, "title") ? { title: text(settings, "title") } : {},
591
+ ...text(settings, "subject_line") ? { subjectLine: text(settings, "subject_line") } : {},
592
+ ...text(recipients, "list_id") ? { listId: text(recipients, "list_id") } : {},
593
+ ...text(recipients, "list_name") ? { listName: text(recipients, "list_name") } : {},
594
+ ...timestamp(text(wire, "create_time")) ? { createdAt: timestamp(text(wire, "create_time")) } : {},
595
+ ...timestamp(text(wire, "send_time")) ? { sentAt: timestamp(text(wire, "send_time")) } : {}
596
+ };
597
+ }
598
+
599
+ // src/client.ts
600
+ function mailchimpFailure(operation, kind, message) {
601
+ return { kind, provider: "mailchimp", operation, message };
602
+ }
603
+ var MailchimpClient = class {
604
+ maxResponseBytes;
605
+ credentials;
606
+ apiBaseURL;
607
+ send;
608
+ now;
609
+ /** Validate configuration and retain immutable dependencies. */
610
+ constructor(config, credentials, options = {}) {
611
+ if (!credentials) throw new TypeError("Mailchimp credential provider is required");
612
+ const maximum = config.maxResponseBytes ?? 4194304;
613
+ if (!Number.isSafeInteger(maximum) || maximum < 1) throw new TypeError("Mailchimp response limit must be positive");
614
+ this.maxResponseBytes = maximum;
615
+ this.credentials = credentials;
616
+ this.apiBaseURL = options.apiBaseURL ? validateBaseURL(options.apiBaseURL) : void 0;
617
+ this.send = options.send ?? sendProviderRequest;
618
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
619
+ }
620
+ /** Bind the contact read. */
621
+ getMember() {
622
+ return new GetMemberOperation(this);
623
+ }
624
+ /** Bind the audience page read. */
625
+ listMembers() {
626
+ return new ListMembersOperation(this);
627
+ }
628
+ /** Bind the contact upsert. */
629
+ upsertMember() {
630
+ return new UpsertMemberOperation(this);
631
+ }
632
+ /** Bind the tag update. */
633
+ updateMemberTags() {
634
+ return new UpdateMemberTagsOperation(this);
635
+ }
636
+ /** Bind the guarded campaign send. */
637
+ sendCampaign() {
638
+ return new SendCampaignOperation(this);
639
+ }
640
+ /** Resolve the current API key and its data center without exposing it in failures. */
641
+ async resolveConnection(call) {
642
+ let key;
643
+ try {
644
+ key = (await this.credentials.resolve(call, call.context.cancellationSignal)).apiKey.reveal();
645
+ } catch {
646
+ return void 0;
647
+ }
648
+ const match = /^([A-Za-z0-9]{8,128})-([a-z]{2,10}[0-9]{1,4})$/.exec(key);
649
+ if (!match || !isHeaderSafeCredential(key)) return void 0;
650
+ return { key, baseURL: this.apiBaseURL ?? `https://${match[2]}.api.mailchimp.com/3.0` };
651
+ }
652
+ /** Send one request and classify the outcome before an operation chooses its branch. */
653
+ async exchange(call, connection, operation, method, path, query, payload) {
654
+ const url = `${connection.baseURL}${path}${query && [...query.keys()].length ? `?${sortedQuery(query)}` : ""}`;
655
+ const headers = { Authorization: `Bearer ${connection.key}`, Accept: "application/json" };
656
+ if (payload !== void 0) headers["Content-Type"] = "application/json";
657
+ const request = {
658
+ url,
659
+ method,
660
+ headers,
661
+ maxResponseBytes: this.maxResponseBytes,
662
+ addressPolicy: this.apiBaseURL ? "privateNetworkHTTP" : "publicHTTPS",
663
+ timeoutMs: Math.min(25e3, call.context.deadline ? Math.max(1, call.context.deadline.getTime() - Date.now()) : 25e3),
664
+ signal: call.context.cancellationSignal,
665
+ ...payload !== void 0 ? { body: Buffer.from(JSON.stringify(payload), "utf8") } : {}
666
+ };
667
+ let response;
668
+ try {
669
+ response = await this.send(request);
670
+ } catch (error) {
671
+ if (error instanceof BodyTooLargeError && error.status !== void 0 && error.headers !== void 0) {
672
+ response = { status: error.status, headers: error.headers, body: new Uint8Array() };
673
+ if (response.status >= 200 && response.status < 300) return { outcome: "invalid", status: response.status, headers: response.headers, body: response.body, failure: mailchimpFailure(operation, "RESPONSE_TOO_LARGE", "Mailchimp response exceeds the configured maxResponseBytes limit"), retryAfterMs: 0 };
674
+ } else {
675
+ const isNotSent = error instanceof AddressRefusal || error instanceof ProviderTransportError && error.isProvablyNotSent;
676
+ return { outcome: isNotSent ? "notSent" : "unavailable", status: 0, headers: {}, body: new Uint8Array(), failure: mailchimpFailure(operation, "TRANSPORT", isNotSent ? "Mailchimp could not be reached; no request was sent" : "Mailchimp request failed before a response arrived"), retryAfterMs: 0 };
677
+ }
678
+ }
679
+ const status = response.status;
680
+ const retryAfterMs = parseRetryAfter(header(response.headers, "retry-after"), this.now());
681
+ if (status >= 200 && status < 300) {
682
+ if (Buffer.from(response.body).includes(Buffer.from(connection.key))) return { outcome: "invalid", status, headers: response.headers, body: new Uint8Array(), failure: mailchimpFailure(operation, "PROTOCOL", "Mailchimp response reflected the connection credential"), retryAfterMs: 0 };
683
+ return { outcome: "succeeded", status, headers: response.headers, body: response.body, retryAfterMs: 0 };
684
+ }
685
+ const hasProblem = hasProblemDocument(response.body);
686
+ let outcome;
687
+ let kind;
688
+ if (status === 429 || status === 403 && !hasProblem) {
689
+ outcome = "rateLimited";
690
+ kind = "RATE_LIMIT";
691
+ } else if (status === 408 || status >= 500) {
692
+ outcome = "unavailable";
693
+ kind = "AVAILABILITY";
694
+ } else if (status === 404) {
695
+ outcome = "notFound";
696
+ kind = "NOT_FOUND";
697
+ } else {
698
+ outcome = "rejected";
699
+ kind = status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : status === 409 ? "CONFLICT" : status === 400 ? "VALIDATION" : status >= 300 && status < 400 ? "PROTOCOL" : "PROVIDER_REJECTION";
700
+ }
701
+ return { outcome, status, headers: response.headers, body: new Uint8Array(), failure: mailchimpFailure(operation, kind, `Mailchimp request failed (HTTP ${status})`), retryAfterMs };
702
+ }
703
+ /** Create a secret-free provider receipt. */
704
+ receipt(call, exchange, objectID) {
705
+ const requestID = header(exchange.headers, "x-request-id");
706
+ return {
707
+ callId: call.id,
708
+ provider: "mailchimp",
709
+ observedAt: goDate(this.now()),
710
+ ...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {},
711
+ ...objectID ? { providerObjectId: objectID } : {},
712
+ .../^[A-Za-z0-9._:-]{1,128}$/.test(requestID) ? { providerRequestId: requestID } : {}
713
+ };
714
+ }
715
+ };
716
+ function header(headers, name) {
717
+ const value = headers[name.toLowerCase()];
718
+ return Array.isArray(value) ? value[0] ?? "" : value ?? "";
719
+ }
720
+ function hasProblemDocument(body) {
721
+ try {
722
+ const document = JSON.parse(Buffer.from(body).toString("utf8"));
723
+ return typeof document.title === "string";
724
+ } catch {
725
+ return false;
726
+ }
727
+ }
728
+ function sortedQuery(query) {
729
+ return [...query.entries()].sort(([left], [right]) => Buffer.compare(Buffer.from(left), Buffer.from(right))).map(([key, value]) => `${goQueryEscape(key)}=${goQueryEscape(value)}`).join("&");
730
+ }
731
+ function goQueryEscape(value) {
732
+ return [...Buffer.from(value, "utf8")].map((byte) => byte >= 65 && byte <= 90 || byte >= 97 && byte <= 122 || byte >= 48 && byte <= 57 || [45, 46, 95, 126].includes(byte) ? String.fromCharCode(byte) : byte === 32 ? "+" : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`).join("");
733
+ }
734
+ function goDate(date) {
735
+ return date.toISOString().replace(/\.000Z$/, "Z");
736
+ }
737
+
738
+ // src/project.ts
739
+ function newProjectConnection2(project, connectionName) {
740
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
741
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "mailchimp" && entry.connectionName === name);
742
+ if (!selected) throw new TypeError("Mailchimp project connection is not configured");
743
+ const config = z2.object({ maxResponseBytes: z2.number().int().optional() }).parse(selected.configuration);
744
+ const credentials = {
745
+ async resolve(call, signal) {
746
+ void call;
747
+ const fields = await loadedProject.resolveCredential("mailchimp", name, signal);
748
+ const decoded = z2.object({ api_key: z2.string().min(1) }).parse(fields);
749
+ return { apiKey: new SecretString(decoded.api_key) };
750
+ }
751
+ };
752
+ return new MailchimpClient(config, credentials);
753
+ });
754
+ }
755
+ export {
756
+ CampaignSchema,
757
+ ConfigSchema,
758
+ Connection,
759
+ ConnectorID,
760
+ GetMemberBranch,
761
+ GetMemberBranchDefect,
762
+ GetMemberBranchFound,
763
+ GetMemberBranchInvalidResponse,
764
+ GetMemberBranchNotFound,
765
+ GetMemberBranchProviderRejected,
766
+ GetMemberDefinition,
767
+ GetMemberInputSchema,
768
+ GetMemberMetadata,
769
+ GetMemberOperation,
770
+ ListMembersBranch,
771
+ ListMembersBranchDefect,
772
+ ListMembersBranchInvalidResponse,
773
+ ListMembersBranchListed,
774
+ ListMembersBranchNotFound,
775
+ ListMembersBranchProviderRejected,
776
+ ListMembersDefinition,
777
+ ListMembersInputSchema2 as ListMembersInputSchema,
778
+ ListMembersMetadata,
779
+ ListMembersOperation,
780
+ ListMembersOutputSchema,
781
+ MailchimpClient,
782
+ MarketingPermissionInputSchema,
783
+ MemberSchema,
784
+ ProviderID,
785
+ SendCampaignBranch,
786
+ SendCampaignBranchAlreadySent,
787
+ SendCampaignBranchDefect,
788
+ SendCampaignBranchInvalidResponse,
789
+ SendCampaignBranchNotFound,
790
+ SendCampaignBranchNotSendable,
791
+ SendCampaignBranchProviderRejected,
792
+ SendCampaignBranchSent,
793
+ SendCampaignBranchUncertain,
794
+ SendCampaignDefinition,
795
+ SendCampaignInputSchema,
796
+ SendCampaignMetadata,
797
+ SendCampaignOperation,
798
+ SendCampaignOutputSchema,
799
+ UpdateMemberTagsBranch,
800
+ UpdateMemberTagsBranchDefect,
801
+ UpdateMemberTagsBranchInvalidResponse,
802
+ UpdateMemberTagsBranchNotFound,
803
+ UpdateMemberTagsBranchProviderRejected,
804
+ UpdateMemberTagsBranchUpdated,
805
+ UpdateMemberTagsDefinition,
806
+ UpdateMemberTagsInputSchema,
807
+ UpdateMemberTagsMetadata,
808
+ UpdateMemberTagsOperation,
809
+ UpdateMemberTagsOutputSchema,
810
+ UpsertMemberBranch,
811
+ UpsertMemberBranchDefect,
812
+ UpsertMemberBranchInvalidResponse,
813
+ UpsertMemberBranchProviderRejected,
814
+ UpsertMemberBranchUpserted,
815
+ UpsertMemberDefinition,
816
+ UpsertMemberInputSchema,
817
+ UpsertMemberMetadata,
818
+ UpsertMemberOperation,
819
+ UpsertMemberOutputSchema,
820
+ decodeCredentials,
821
+ newConnection,
822
+ newConnectionWithOperations,
823
+ newGetMemberStep,
824
+ newListMembersStep,
825
+ newProjectConnection2 as newProjectConnection,
826
+ newSendCampaignStep,
827
+ newUpdateMemberTagsStep,
828
+ newUpsertMemberStep
829
+ };