@superdurable/connector-braze 0.0.0-stage → 0.2.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,873 @@
1
+ import {
2
+ CampaignIdentitySchema,
3
+ CampaignsListSchema,
4
+ CanvasIdentitySchema,
5
+ CanvasesListSchema,
6
+ ConfigSchema,
7
+ Connection,
8
+ ConnectorID,
9
+ CredentialMaterialError,
10
+ DeleteUserProfileBranch,
11
+ DeleteUserProfileBranchDefect,
12
+ DeleteUserProfileBranchDeleted,
13
+ DeleteUserProfileBranchInvalidResponse,
14
+ DeleteUserProfileBranchProviderRejected,
15
+ DeleteUserProfileDefinition,
16
+ DeleteUserProfileInputSchema,
17
+ DeleteUserProfileMetadata,
18
+ GetUserProfileBranch,
19
+ GetUserProfileBranchDefect,
20
+ GetUserProfileBranchFound,
21
+ GetUserProfileBranchInvalidResponse,
22
+ GetUserProfileBranchNotFound,
23
+ GetUserProfileBranchProviderRejected,
24
+ GetUserProfileDefinition,
25
+ GetUserProfileInputSchema,
26
+ GetUserProfileMetadata,
27
+ ListCampaignsBranch,
28
+ ListCampaignsBranchDefect,
29
+ ListCampaignsBranchInvalidResponse,
30
+ ListCampaignsBranchListed,
31
+ ListCampaignsBranchProviderRejected,
32
+ ListCampaignsDefinition,
33
+ ListCampaignsInputSchema,
34
+ ListCampaignsMetadata,
35
+ ListCanvasesBranch,
36
+ ListCanvasesBranchDefect,
37
+ ListCanvasesBranchInvalidResponse,
38
+ ListCanvasesBranchListed,
39
+ ListCanvasesBranchProviderRejected,
40
+ ListCanvasesDefinition,
41
+ ListCanvasesInputSchema,
42
+ ListCanvasesMetadata,
43
+ ListSegmentsBranch,
44
+ ListSegmentsBranchDefect,
45
+ ListSegmentsBranchInvalidResponse,
46
+ ListSegmentsBranchListed,
47
+ ListSegmentsBranchProviderRejected,
48
+ ListSegmentsDefinition,
49
+ ListSegmentsInputSchema,
50
+ ListSegmentsMetadata,
51
+ ProviderID,
52
+ SegmentIdentitySchema,
53
+ SegmentsListSchema,
54
+ TargetedSendResultSchema,
55
+ TriggerCampaignSendBranch,
56
+ TriggerCampaignSendBranchDefect,
57
+ TriggerCampaignSendBranchProviderRejected,
58
+ TriggerCampaignSendBranchSent,
59
+ TriggerCampaignSendBranchUncertain,
60
+ TriggerCampaignSendDefinition,
61
+ TriggerCampaignSendInputSchema,
62
+ TriggerCampaignSendMetadata,
63
+ TriggerCanvasSendBranch,
64
+ TriggerCanvasSendBranchDefect,
65
+ TriggerCanvasSendBranchProviderRejected,
66
+ TriggerCanvasSendBranchSent,
67
+ TriggerCanvasSendBranchUncertain,
68
+ TriggerCanvasSendDefinition,
69
+ TriggerCanvasSendInputSchema,
70
+ TriggerCanvasSendMetadata,
71
+ UpdateUserProfileBranch,
72
+ UpdateUserProfileBranchAccepted,
73
+ UpdateUserProfileBranchDefect,
74
+ UpdateUserProfileBranchInvalidResponse,
75
+ UpdateUserProfileBranchProviderRejected,
76
+ UpdateUserProfileDefinition,
77
+ UpdateUserProfileInputSchema,
78
+ UpdateUserProfileMetadata,
79
+ UserDeleteResultSchema,
80
+ UserProfileSchema,
81
+ UserWriteResultSchema,
82
+ decodeCredentials,
83
+ isCredentialMaterialError,
84
+ newConnection,
85
+ newConnectionWithOperations,
86
+ newProjectConnection
87
+ } from "./chunk-E4CIKIAP.js";
88
+
89
+ // src/generated/steps.ts
90
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
91
+ function newTriggerCampaignSendStep(configuration) {
92
+ const { connection, connectionName, sent, providerRejected, defect, uncertain, ...stepConfiguration } = configuration;
93
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
94
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.triggerCampaignSend(), connection: connection.reference, branches: [
95
+ goToBranch("sent", sent),
96
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
97
+ ...defect ? [goToBranch("defect", defect)] : [],
98
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : []
99
+ ] });
100
+ }
101
+ function newTriggerCanvasSendStep(configuration) {
102
+ const { connection, connectionName, sent, providerRejected, defect, uncertain, ...stepConfiguration } = configuration;
103
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
104
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.triggerCanvasSend(), connection: connection.reference, branches: [
105
+ goToBranch("sent", sent),
106
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
107
+ ...defect ? [goToBranch("defect", defect)] : [],
108
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : []
109
+ ] });
110
+ }
111
+ function newUpdateUserProfileStep(configuration) {
112
+ const { connection, connectionName, accepted, providerRejected, invalidResponse, defect, maxSends, ...stepConfiguration } = configuration;
113
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
114
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateUserProfile(), connection: connection.reference, branches: [
115
+ goToBranch("accepted", accepted),
116
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
117
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
118
+ ...defect ? [goToBranch("defect", defect)] : []
119
+ ] });
120
+ }
121
+ function newDeleteUserProfileStep(configuration) {
122
+ const { connection, connectionName, deleted, providerRejected, invalidResponse, defect, maxSends, ...stepConfiguration } = configuration;
123
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
124
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.deleteUserProfile(), connection: connection.reference, branches: [
125
+ goToBranch("deleted", deleted),
126
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
127
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
128
+ ...defect ? [goToBranch("defect", defect)] : []
129
+ ] });
130
+ }
131
+ function newListCampaignsStep(configuration) {
132
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
133
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
134
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listCampaigns(), connection: connection.reference, branches: [
135
+ goToBranch("listed", listed),
136
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
137
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
138
+ ...defect ? [goToBranch("defect", defect)] : []
139
+ ] });
140
+ }
141
+ function newListCanvasesStep(configuration) {
142
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
143
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
144
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listCanvases(), connection: connection.reference, branches: [
145
+ goToBranch("listed", listed),
146
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
147
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
148
+ ...defect ? [goToBranch("defect", defect)] : []
149
+ ] });
150
+ }
151
+ function newListSegmentsStep(configuration) {
152
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
153
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
154
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listSegments(), connection: connection.reference, branches: [
155
+ goToBranch("listed", listed),
156
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
157
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
158
+ ...defect ? [goToBranch("defect", defect)] : []
159
+ ] });
160
+ }
161
+ function newGetUserProfileStep(configuration) {
162
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
163
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
164
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getUserProfile(), connection: connection.reference, branches: [
165
+ goToBranch("found", found),
166
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
167
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
168
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
169
+ ...defect ? [goToBranch("defect", defect)] : []
170
+ ] });
171
+ }
172
+
173
+ // src/project.ts
174
+ import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
175
+ import { z } from "zod";
176
+
177
+ // src/client.ts
178
+ import { isIP } from "net";
179
+ import { SecretString, definitionMaxSends, newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
180
+ import { BodyTooLargeError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
181
+ import { CheckpointError, DispatchNotAllowedError, InsufficientTimeError, newFence } from "@superdurable/connectors-sdk/singledispatch";
182
+ var fieldsToExport = ["external_id", "braze_id", "first_name", "last_name", "email"];
183
+ var emptyProfile = () => ({ externalId: "" });
184
+ var providerRequest = /* @__PURE__ */ Symbol("Braze provider request");
185
+ var prepareTargetedSend = /* @__PURE__ */ Symbol("Braze targeted send");
186
+ var BrazeClient = class {
187
+ /** Validate account endpoint and request limits without contacting Braze. */
188
+ constructor(config, credentials, options = {}) {
189
+ this.credentials = credentials;
190
+ if (!config || !credentials) throw new TypeError("Braze configuration and credentials are required");
191
+ this.baseURL = validateBaseURL(config.baseUrl);
192
+ this.timeoutMs = config.timeoutMs || 15e3;
193
+ this.maxResponseBytes = config.maxResponseBytes || 1048576;
194
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0)
195
+ throw new TypeError("Braze request limits must be positive integers");
196
+ this.send = options.send ?? sendProviderRequest;
197
+ }
198
+ credentials;
199
+ baseURL;
200
+ timeoutMs;
201
+ maxResponseBytes;
202
+ send;
203
+ /** Bind the getUserProfile Query. */
204
+ getUserProfile() {
205
+ return new GetUserProfileOperation(this);
206
+ }
207
+ /** Submit absolute attributes for one Braze profile. */
208
+ updateUserProfile() {
209
+ return new UpdateUserProfileOperation(this);
210
+ }
211
+ /** Queue deletion of one Braze profile. */
212
+ deleteUserProfile() {
213
+ return new DeleteUserProfileOperation(this);
214
+ }
215
+ /** List one page of Braze campaign identities. */
216
+ listCampaigns() {
217
+ return new ListCampaignsOperation(this);
218
+ }
219
+ /** List one page of Braze Canvas identities. */
220
+ listCanvases() {
221
+ return new ListCanvasesOperation(this);
222
+ }
223
+ /** List one page of Braze segment identities. */
224
+ listSegments() {
225
+ return new ListSegmentsOperation(this);
226
+ }
227
+ /** Dispatch one Braze campaign to an existing user. */
228
+ triggerCampaignSend() {
229
+ return new TriggerCampaignSendOperation(this);
230
+ }
231
+ /** Dispatch one Braze Canvas to an existing user. */
232
+ triggerCanvasSend() {
233
+ return new TriggerCanvasSendOperation(this);
234
+ }
235
+ /** Resolve the key and send one bounded profile export request. */
236
+ async post(call, externalID) {
237
+ return this[providerRequest](call, "POST", "/users/export/ids", jsonBody({ external_ids: [externalID], fields_to_export: fieldsToExport }));
238
+ }
239
+ async resolveToken(call) {
240
+ try {
241
+ const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
242
+ const token = credentials.restApiKey instanceof SecretString ? credentials.restApiKey.reveal() : "";
243
+ return token && isHeaderSafeCredential(token) ? token : void 0;
244
+ } catch {
245
+ return void 0;
246
+ }
247
+ }
248
+ async [providerRequest](call, method, path, payload) {
249
+ const token = await this.resolveToken(call);
250
+ if (!token) return emptyExchange("credential");
251
+ return this.sendRequest(token, method, path, payload, call.context.cancellationSignal);
252
+ }
253
+ async [prepareTargetedSend](call, path, payload) {
254
+ const token = await this.resolveToken(call);
255
+ return token ? this.sendRequest.bind(this, token, "POST", path, payload) : void 0;
256
+ }
257
+ async sendRequest(token, method, path, payload, signal) {
258
+ const request = {
259
+ url: this.baseURL + path,
260
+ method,
261
+ headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: `Bearer ${token}` },
262
+ ...payload ? { body: payload } : {},
263
+ maxResponseBytes: this.maxResponseBytes,
264
+ timeoutMs: this.timeoutMs,
265
+ addressPolicy: this.baseURL.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP",
266
+ signal
267
+ };
268
+ let response;
269
+ let isTooLarge = false;
270
+ try {
271
+ response = await this.send(request);
272
+ } catch (error) {
273
+ if (error instanceof BodyTooLargeError && error.status !== void 0) {
274
+ response = { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() };
275
+ isTooLarge = true;
276
+ } else if (error instanceof ProviderTransportError && error.status !== void 0) {
277
+ return { status: error.status, body: new Uint8Array(), retryAfterMs: parseRetryAfter(header(error.headers ?? {}, "retry-after")), error: "interrupted" };
278
+ } else return emptyExchange("request");
279
+ }
280
+ const retryAfterMs = parseRetryAfter(header(response.headers, "retry-after"));
281
+ if (isTooLarge || response.body.length > this.maxResponseBytes)
282
+ return { status: response.status, body: new Uint8Array(), retryAfterMs, error: "tooLarge" };
283
+ return { status: response.status, body: response.body, retryAfterMs };
284
+ }
285
+ };
286
+ var GetUserProfileOperation = class {
287
+ /** Bind the provider client. */
288
+ constructor(client) {
289
+ this.client = client;
290
+ }
291
+ client;
292
+ /** Return the generated Query contract. */
293
+ definition() {
294
+ return GetUserProfileDefinition;
295
+ }
296
+ /** Classify provider outcomes consistently with the Go implementation. */
297
+ async invoke(call, input) {
298
+ if (!input || typeof input.externalId !== "string" || !input.externalId.trim() || /[\uD800-\uDFFF]/u.test(input.externalId) || Buffer.byteLength(input.externalId, "utf8") > 987)
299
+ return terminal("defect", "VALIDATION", "external ID must be a nonempty UTF-8 value of at most 987 bytes");
300
+ const exchange = await this.client.post(call, input.externalId);
301
+ if (exchange.error === "credential") return terminal("defect", "AUTHENTICATION", "Braze credentials are unavailable or invalid");
302
+ if (exchange.error === "request") return retry("TRANSPORT", "Braze profile request failed");
303
+ if (exchange.status === 429) return retry("RATE_LIMIT", "Braze rate limited the request", exchange.retryAfterMs);
304
+ if (exchange.status === 408 || exchange.status >= 500) return retry("AVAILABILITY", "Braze is temporarily unavailable", exchange.retryAfterMs);
305
+ if (exchange.status !== 200 && exchange.status !== 201) return terminal("providerRejected", "PROVIDER_REJECTION", `Braze rejected HTTP ${exchange.status}`);
306
+ if (exchange.error === "tooLarge") return terminal("invalidResponse", "RESPONSE_TOO_LARGE", "Braze response exceeded the configured limit");
307
+ if (exchange.error) return retry("TRANSPORT", "Braze response was interrupted");
308
+ const profile = decodeProfile(exchange.body, input.externalId);
309
+ if (profile === void 0) return terminal("invalidResponse", "PROTOCOL", "Braze returned an invalid profile response");
310
+ if (profile === null) return terminal("notFound", "NOT_FOUND", "Braze did not find the user");
311
+ return newQueryBranch("found", profile);
312
+ }
313
+ };
314
+ function emptyExchange(error) {
315
+ return { status: 0, body: new Uint8Array(), retryAfterMs: 0, error };
316
+ }
317
+ function failure(kind, message) {
318
+ return { provider: "braze", operation: "getUserProfile", kind, message };
319
+ }
320
+ function terminal(branch, kind, message) {
321
+ return newQueryBranch(branch, emptyProfile(), {}, failure(kind, message));
322
+ }
323
+ function retry(kind, message, delay = 0) {
324
+ return newQueryRetry(failure(kind, message), delay);
325
+ }
326
+ function header(headers, name) {
327
+ const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
328
+ return Array.isArray(entry) ? entry[0] ?? "" : entry ?? "";
329
+ }
330
+ function isObject(value) {
331
+ return typeof value === "object" && value !== null && !Array.isArray(value);
332
+ }
333
+ function decodeProfile(body, externalID) {
334
+ let raw;
335
+ try {
336
+ raw = JSON.parse(Buffer.from(body).toString("utf8"));
337
+ } catch {
338
+ return void 0;
339
+ }
340
+ if (!isObject(raw) || raw.message !== "success" || !Array.isArray(raw.users) || raw.users.length > 1) return void 0;
341
+ if (raw.users.length === 0) return null;
342
+ const user = raw.users[0];
343
+ if (!isObject(user) || user.external_id !== externalID) return void 0;
344
+ for (const field2 of ["braze_id", "first_name", "last_name", "email"])
345
+ if (user[field2] !== void 0 && user[field2] !== null && typeof user[field2] !== "string") return void 0;
346
+ const result = { externalId: externalID };
347
+ if (user.braze_id) result.brazeId = user.braze_id;
348
+ if (user.first_name) result.firstName = user.first_name;
349
+ if (user.last_name) result.lastName = user.last_name;
350
+ if (user.email) result.email = user.email;
351
+ return result;
352
+ }
353
+ var emptyUpdate = { externalId: "" };
354
+ var emptyDelete = { externalId: "", deleted: 0 };
355
+ var emptyCampaigns = { campaigns: [] };
356
+ var emptyCanvases = { canvases: [] };
357
+ var emptySegments = { segments: [] };
358
+ var emptySend = { dispatchId: "" };
359
+ var refusalStatuses = /* @__PURE__ */ new Set([400, 401, 403, 404, 411, 413, 414, 415, 422]);
360
+ var emailAtom = /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~\u0080-\u{10ffff}-]+$/u;
361
+ var UpdateUserProfileOperation = class {
362
+ /** Bind the provider client. */
363
+ constructor(client) {
364
+ this.client = client;
365
+ }
366
+ client;
367
+ /** Return the safe profile update contract. */
368
+ definition() {
369
+ return UpdateUserProfileDefinition;
370
+ }
371
+ /** Identify the logical update across attempts. */
372
+ idempotencyKey(callId) {
373
+ return callId;
374
+ }
375
+ /** Send only supplied attributes and require a successful acknowledgment. */
376
+ async invoke(call, input) {
377
+ const operation = "updateUserProfile";
378
+ if (!validExternalID(input.externalId) || input.firstName == null && input.lastName == null && input.email == null) {
379
+ return mutationBranch(operation, emptyUpdate, "defect", "VALIDATION", "external ID and at least one attribute are required");
380
+ }
381
+ if (input.email != null && !plainAddress(input.email)) {
382
+ return mutationBranch(operation, emptyUpdate, "defect", "VALIDATION", "email must be a plain address");
383
+ }
384
+ const payload = jsonBody({ attributes: [{
385
+ external_id: input.externalId,
386
+ ...input.firstName != null ? { first_name: input.firstName } : {},
387
+ ...input.lastName != null ? { last_name: input.lastName } : {},
388
+ ...input.email != null ? { email: input.email } : {}
389
+ }] });
390
+ if (payload.byteLength > 1 << 20) return mutationBranch(operation, emptyUpdate, "defect", "VALIDATION", "profile update is invalid or too large");
391
+ return safeWrite(this.client, call, operation, "/users/track", payload, "accepted", emptyUpdate, (document) => {
392
+ const errors = field(document, "errors");
393
+ if (errors != null && (!Array.isArray(errors) || errors.length !== 0)) throw new TypeError("Braze update has errors");
394
+ return { externalId: input.externalId };
395
+ });
396
+ }
397
+ };
398
+ var DeleteUserProfileOperation = class {
399
+ /** Bind the provider client. */
400
+ constructor(client) {
401
+ this.client = client;
402
+ }
403
+ client;
404
+ /** Return the safe profile deletion contract. */
405
+ definition() {
406
+ return DeleteUserProfileDefinition;
407
+ }
408
+ /** Identify the logical deletion across attempts. */
409
+ idempotencyKey(callId) {
410
+ return callId;
411
+ }
412
+ /** Request deletion and report whether Braze matched the profile. */
413
+ async invoke(call, input) {
414
+ const operation = "deleteUserProfile";
415
+ if (!validExternalID(input.externalId)) return mutationBranch(
416
+ operation,
417
+ emptyDelete,
418
+ "defect",
419
+ "VALIDATION",
420
+ "external ID must be a nonempty UTF-8 value of at most 987 bytes"
421
+ );
422
+ return safeWrite(
423
+ this.client,
424
+ call,
425
+ operation,
426
+ "/users/delete",
427
+ jsonBody({ external_ids: [input.externalId] }),
428
+ "deleted",
429
+ emptyDelete,
430
+ (document) => {
431
+ const deleted = field(document, "deleted");
432
+ if (deleted !== 0 && deleted !== 1) throw new TypeError("Braze deletion count is invalid");
433
+ return { externalId: input.externalId, deleted };
434
+ }
435
+ );
436
+ }
437
+ };
438
+ var ListCampaignsOperation = class {
439
+ /** Bind the provider client. */
440
+ constructor(client) {
441
+ this.client = client;
442
+ }
443
+ client;
444
+ /** Return the campaign list Query contract. */
445
+ definition() {
446
+ return ListCampaignsDefinition;
447
+ }
448
+ /** Fetch the specified zero-based page. */
449
+ async invoke(call, input) {
450
+ return listPage(
451
+ this.client,
452
+ call,
453
+ "listCampaigns",
454
+ "/campaigns/list",
455
+ input.page,
456
+ "campaigns",
457
+ emptyCampaigns,
458
+ (document) => ({ campaigns: identities(document, "campaigns").map(({ id, name }) => ({ id, name })) })
459
+ );
460
+ }
461
+ };
462
+ var ListCanvasesOperation = class {
463
+ /** Bind the provider client. */
464
+ constructor(client) {
465
+ this.client = client;
466
+ }
467
+ client;
468
+ /** Return the Canvas list Query contract. */
469
+ definition() {
470
+ return ListCanvasesDefinition;
471
+ }
472
+ /** Fetch the specified zero-based page. */
473
+ async invoke(call, input) {
474
+ return listPage(
475
+ this.client,
476
+ call,
477
+ "listCanvases",
478
+ "/canvas/list",
479
+ input.page,
480
+ "canvases",
481
+ emptyCanvases,
482
+ (document) => ({ canvases: identities(document, "canvases").map(({ id, name }) => ({ id, name })) })
483
+ );
484
+ }
485
+ };
486
+ var ListSegmentsOperation = class {
487
+ /** Bind the provider client. */
488
+ constructor(client) {
489
+ this.client = client;
490
+ }
491
+ client;
492
+ /** Return the segment list Query contract. */
493
+ definition() {
494
+ return ListSegmentsDefinition;
495
+ }
496
+ /** Fetch the specified zero-based page. */
497
+ async invoke(call, input) {
498
+ return listPage(this.client, call, "listSegments", "/segments/list", input.page, "segments", emptySegments, (document) => ({
499
+ segments: identities(document, "segments").map(({ id, name, entry }) => {
500
+ const enabled = field(entry, "analytics_tracking_enabled");
501
+ if (enabled != null && typeof enabled !== "boolean") throw new TypeError("Braze segment tracking flag is invalid");
502
+ return { id, name, analyticsTrackingEnabled: enabled ?? false };
503
+ })
504
+ }));
505
+ }
506
+ };
507
+ var TriggerCampaignSendOperation = class {
508
+ /** Bind the provider client. */
509
+ constructor(client) {
510
+ this.client = client;
511
+ }
512
+ client;
513
+ /** Return the limited-send campaign contract. */
514
+ definition() {
515
+ return TriggerCampaignSendDefinition;
516
+ }
517
+ /** Identify the logical dispatch across attempts. */
518
+ idempotencyKey(callId) {
519
+ return callId;
520
+ }
521
+ /** Dispatch the campaign to the specified existing external user. */
522
+ async invoke(call, input) {
523
+ const operation = "triggerCampaignSend";
524
+ if (!validMessageID(input.campaignId) || !validExternalID(input.externalId)) {
525
+ return mutationBranch(operation, emptySend, "defect", "VALIDATION", "campaign ID and existing external user ID are required");
526
+ }
527
+ const payload = jsonBody({
528
+ campaign_id: input.campaignId,
529
+ recipients: [{ external_user_id: input.externalId, send_to_existing_only: true }]
530
+ });
531
+ return targetedSend(this.client, call, operation, "/campaigns/trigger/send", payload, this.definition());
532
+ }
533
+ };
534
+ var TriggerCanvasSendOperation = class {
535
+ /** Bind the provider client. */
536
+ constructor(client) {
537
+ this.client = client;
538
+ }
539
+ client;
540
+ /** Return the limited-send Canvas contract. */
541
+ definition() {
542
+ return TriggerCanvasSendDefinition;
543
+ }
544
+ /** Identify the logical dispatch across attempts. */
545
+ idempotencyKey(callId) {
546
+ return callId;
547
+ }
548
+ /** Dispatch the Canvas to the specified external user. */
549
+ async invoke(call, input) {
550
+ const operation = "triggerCanvasSend";
551
+ if (!validMessageID(input.canvasId) || !validExternalID(input.externalId)) {
552
+ return mutationBranch(operation, emptySend, "defect", "VALIDATION", "Canvas ID and existing external user ID are required");
553
+ }
554
+ const payload = jsonBody({ canvas_id: input.canvasId, recipients: [{ external_user_id: input.externalId }] });
555
+ return targetedSend(this.client, call, operation, "/canvas/trigger/send", payload, this.definition());
556
+ }
557
+ };
558
+ async function listPage(client, call, operation, path, page, resource, empty, decode) {
559
+ if (!Number.isSafeInteger(page) || page < 0) return queryBranch(operation, empty, "defect", "VALIDATION", "page must be non-negative");
560
+ const response = await client[providerRequest](call, "GET", `${path}?page=${page}`);
561
+ if (response.error === "credential") return queryBranch(operation, empty, "defect", "AUTHENTICATION", "Braze credentials are unavailable or invalid");
562
+ if (response.error === "request") return newQueryRetry(operationFailure(operation, "TRANSPORT", `Braze ${resource} request failed`));
563
+ const transient = transientStatus(response.status);
564
+ if (transient) return newQueryRetry(operationFailure(operation, ...transient), response.retryAfterMs);
565
+ if (response.status !== 200) return queryBranch(operation, empty, "providerRejected", "PROVIDER_REJECTION", `Braze rejected HTTP ${response.status}`);
566
+ if (response.error === "tooLarge") return queryBranch(operation, empty, "invalidResponse", "RESPONSE_TOO_LARGE", "Braze response exceeded the configured limit");
567
+ if (response.error) return newQueryRetry(operationFailure(operation, "TRANSPORT", "Braze response was interrupted"));
568
+ try {
569
+ return newQueryBranch("listed", decode(successfulDocument(response.body)));
570
+ } catch {
571
+ return queryBranch(operation, empty, "invalidResponse", "PROTOCOL", `Braze returned invalid ${resource} JSON`);
572
+ }
573
+ }
574
+ async function safeWrite(client, call, operation, path, payload, success, empty, decode) {
575
+ const response = await client[providerRequest](call, "POST", path, payload);
576
+ const attempt = call.context.attempt ?? 1;
577
+ if (response.error === "credential") {
578
+ if (attempt > 1) return mutationRetry(operation, "TRANSPORT", "an earlier Braze write remains unconfirmed");
579
+ return mutationBranch(operation, empty, "defect", "AUTHENTICATION", "Braze credentials are unavailable or invalid");
580
+ }
581
+ if (response.error === "request") return mutationRetry(operation, "TRANSPORT", "Braze response is unavailable");
582
+ const transient = transientStatus(response.status);
583
+ if (transient) return mutationRetry(operation, ...transient, response.retryAfterMs);
584
+ if (response.status !== 201) {
585
+ if (attempt === 1 && definiteRefusal(response)) return mutationBranch(operation, empty, "providerRejected", "PROVIDER_REJECTION", `Braze rejected HTTP ${response.status}`);
586
+ return mutationRetry(operation, "TRANSPORT", "Braze write outcome is unknown");
587
+ }
588
+ if (response.error === "tooLarge") return mutationRetry(operation, "RESPONSE_TOO_LARGE", "Braze response exceeded the configured limit");
589
+ if (response.error) return mutationRetry(operation, "TRANSPORT", "Braze response was interrupted");
590
+ try {
591
+ return newMutationBranch(success, decode(successfulDocument(response.body)));
592
+ } catch {
593
+ return mutationRetry(operation, "PROTOCOL", "Braze returned an invalid write acknowledgment");
594
+ }
595
+ }
596
+ async function targetedSend(client, call, operation, path, payload, definition) {
597
+ const maxSends = call.maxSendsOverride ?? definitionMaxSends(definition);
598
+ let fence;
599
+ try {
600
+ fence = newFence(call, definition.stepDefaults.executeMethodTimeoutMs ?? 3e4, { maxSends });
601
+ } catch {
602
+ return mutationBranch(operation, emptySend, "defect", "LOCAL_DEFECT", "send fence could not be constructed");
603
+ }
604
+ const decision = fence.decide();
605
+ if (decision.kind === "failClosed") return mutationRetry(operation, "TRANSPORT", "dispatch checkpoint could not be trusted");
606
+ if (decision.kind === "readBackRequired") return sendUncertain(operation, "TRANSPORT", "an earlier message may have been dispatched");
607
+ const send = await client[prepareTargetedSend](call, path, payload);
608
+ if (!send) return mutationBranch(operation, emptySend, "defect", "AUTHENTICATION", "Braze credentials are unavailable or invalid");
609
+ const prior = decision.priorSendUpperBound ?? 0;
610
+ const isFinalSend = prior + 1 >= maxSends;
611
+ let response;
612
+ try {
613
+ response = await fence.dispatch(send);
614
+ } catch (error) {
615
+ if (error instanceof CheckpointError || error instanceof DispatchNotAllowedError || error instanceof InsufficientTimeError || error instanceof AggregateError && error.errors.some((cause) => cause instanceof InsufficientTimeError)) {
616
+ return mutationRetry(operation, "AVAILABILITY", "send dispatch was not recorded or sent");
617
+ }
618
+ return unknownSend(operation, isFinalSend);
619
+ }
620
+ if (response.status === 429 || response.status === 503) {
621
+ try {
622
+ await fence.recordCanResend();
623
+ } catch {
624
+ return mutationRetry(operation, "AVAILABILITY", "send retry checkpoint failed");
625
+ }
626
+ return mutationRetry(operation, "RATE_LIMIT", "Braze asked to retry the send", response.retryAfterMs);
627
+ }
628
+ if (response.error || response.status === 408 || response.status >= 500) return unknownSend(operation, isFinalSend);
629
+ if (response.status !== 201) {
630
+ if (prior || !definiteRefusal(response)) return mutationRetry("targeted_sends", "TRANSPORT", "provider write outcome is unknown");
631
+ try {
632
+ await fence.recordCanResend();
633
+ } catch {
634
+ return mutationRetry("targeted_sends", "TRANSPORT", "provider write outcome is unknown");
635
+ }
636
+ return mutationBranch(operation, emptySend, "providerRejected", "PROVIDER_REJECTION", `Braze rejected HTTP ${response.status}`);
637
+ }
638
+ try {
639
+ const dispatchId = field(successfulDocument(response.body), "dispatch_id");
640
+ if (typeof dispatchId !== "string" || !dispatchId) throw new TypeError("dispatch ID missing");
641
+ return newMutationBranch("sent", { dispatchId });
642
+ } catch {
643
+ const message = "Braze accepted a send but its dispatch ID could not be confirmed";
644
+ if (isFinalSend) return sendUncertain(operation, "PROTOCOL", message);
645
+ return mutationRetry(operation, "PROTOCOL", message);
646
+ }
647
+ }
648
+ function unknownSend(operation, isFinalSend) {
649
+ if (isFinalSend) return sendUncertain(operation, "TRANSPORT", "send outcome is unknown after bounded sends");
650
+ return mutationRetry(operation, "TRANSPORT", "send outcome is unknown");
651
+ }
652
+ function sendUncertain(operation, kind, message) {
653
+ return newMutationUncertain(emptySend, operationFailure(operation, kind, message));
654
+ }
655
+ function transientStatus(status) {
656
+ if (status === 429) return ["RATE_LIMIT", "Braze rate limited the request"];
657
+ if (status === 408 || status >= 500) return ["AVAILABILITY", "Braze is temporarily unavailable"];
658
+ return void 0;
659
+ }
660
+ function definiteRefusal(response) {
661
+ if (!refusalStatuses.has(response.status)) return false;
662
+ const document = parseDocument(response.body);
663
+ if (document.success === true || ["data", "result", "results"].some((key) => hasContent(document[key]))) return false;
664
+ return ["code", "message", "error", "errors", "errorInfo"].some((key) => document[key] !== "" && hasContent(document[key]));
665
+ }
666
+ function hasContent(value) {
667
+ if (value == null) return false;
668
+ if (typeof value === "object") return Object.keys(value).length > 0;
669
+ return true;
670
+ }
671
+ function jsonBody(document) {
672
+ const content = JSON.stringify(document).replace(/[&<>\u2028\u2029]/gu, (character) => "\\u" + character.charCodeAt(0).toString(16).padStart(4, "0"));
673
+ return new TextEncoder().encode(content);
674
+ }
675
+ function plainAddress(value) {
676
+ const separator = value.lastIndexOf("@");
677
+ if (separator < 0 || /[\uD800-\uDFFF]/u.test(value) || !isDotAtom(value.slice(0, separator))) return false;
678
+ const domain = value.slice(separator + 1);
679
+ if (domain.startsWith("[") && domain.endsWith("]")) {
680
+ const literal = domain.slice(1, -1);
681
+ return !literal.includes("%") && isIP(literal) !== 0;
682
+ }
683
+ return isDotAtom(domain);
684
+ }
685
+ function isDotAtom(value) {
686
+ return value.split(".").every((atom) => emailAtom.exec(atom)?.[0] === atom);
687
+ }
688
+ function validExternalID(value) {
689
+ return !!value.trim() && !/[\uD800-\uDFFF]/u.test(value) && Buffer.byteLength(value, "utf8") <= 987;
690
+ }
691
+ function validMessageID(value) {
692
+ return !!value && value === value.trim() && !/[\uD800-\uDFFF]/u.test(value) && Buffer.byteLength(value, "utf8") <= 128;
693
+ }
694
+ function parseDocument(bytes) {
695
+ try {
696
+ const document = JSON.parse(Buffer.from(bytes).toString("utf8"));
697
+ return isObject(document) ? document : {};
698
+ } catch {
699
+ return {};
700
+ }
701
+ }
702
+ function field(document, name) {
703
+ if (Object.hasOwn(document, name)) return document[name];
704
+ const key = Object.keys(document).find((key2) => key2.toLowerCase() === name.toLowerCase());
705
+ return key === void 0 ? void 0 : document[key];
706
+ }
707
+ function successfulDocument(body) {
708
+ const document = parseDocument(body);
709
+ if (field(document, "message") !== "success") throw new TypeError("Braze success message missing");
710
+ return document;
711
+ }
712
+ function identities(document, name) {
713
+ const entries = field(document, name);
714
+ if (!Array.isArray(entries)) throw new TypeError("Braze list missing");
715
+ return entries.map((entry) => {
716
+ if (!isObject(entry)) throw new TypeError("Braze list item invalid");
717
+ const id = field(entry, "id"), name2 = field(entry, "name");
718
+ if (typeof id !== "string" || !id || typeof name2 !== "string" || !name2) throw new TypeError("Braze identity missing");
719
+ return { id, name: name2, entry };
720
+ });
721
+ }
722
+ function operationFailure(operation, kind, message) {
723
+ return { provider: "braze", operation, kind, message };
724
+ }
725
+ function queryBranch(operation, value, branch, kind, message) {
726
+ return newQueryBranch(branch, value, {}, operationFailure(operation, kind, message));
727
+ }
728
+ function mutationBranch(operation, value, branch, kind, message) {
729
+ return newMutationBranch(branch, value, {}, operationFailure(operation, kind, message));
730
+ }
731
+ function mutationRetry(operation, kind, message, delay = 0) {
732
+ return newMutationRetry(operationFailure(operation, kind, message), delay);
733
+ }
734
+
735
+ // src/project.ts
736
+ function newProjectConnection2(project, connectionName) {
737
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
738
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "braze" && entry.connectionName === name);
739
+ if (!selected) throw new TypeError("Braze project connection is not configured");
740
+ const fields = z.strictObject({ baseUrl: z.string(), timeout: z.union([z.string(), z.number().int()]).optional(), maxResponseBytes: z.number().int().optional() }).parse(selected.configuration);
741
+ const timeoutMs = typeof fields.timeout === "number" ? Math.ceil(fields.timeout / 1e6) : fields.timeout ? parseDurationMilliseconds(fields.timeout) : void 0;
742
+ const config = {
743
+ baseUrl: fields.baseUrl,
744
+ ...timeoutMs !== void 0 ? { timeoutMs } : {},
745
+ ...fields.maxResponseBytes !== void 0 ? { maxResponseBytes: fields.maxResponseBytes } : {}
746
+ };
747
+ const credentials = {
748
+ async resolve(_call, signal) {
749
+ const privateFields = await loadedProject.resolveCredential("braze", name, signal);
750
+ if (typeof privateFields.rest_api_key !== "string") throw new TypeError("Braze credentials are unavailable");
751
+ return { restApiKey: new SecretString2(privateFields.rest_api_key) };
752
+ }
753
+ };
754
+ return new BrazeClient(config, credentials);
755
+ });
756
+ }
757
+ function parseDurationMilliseconds(value) {
758
+ let remaining = value;
759
+ let milliseconds = 0;
760
+ const units = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
761
+ while (remaining) {
762
+ const part = /^(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/.exec(remaining);
763
+ if (!part) throw new TypeError("Braze timeout must be a positive Go duration");
764
+ milliseconds += Number(part[1]) * (units[part[2] ?? ""] ?? NaN);
765
+ remaining = remaining.slice(part[0].length);
766
+ }
767
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) throw new TypeError("Braze timeout must resolve to positive whole milliseconds");
768
+ return milliseconds;
769
+ }
770
+ export {
771
+ BrazeClient,
772
+ CampaignIdentitySchema,
773
+ CampaignsListSchema,
774
+ CanvasIdentitySchema,
775
+ CanvasesListSchema,
776
+ ConfigSchema,
777
+ Connection,
778
+ ConnectorID,
779
+ CredentialMaterialError,
780
+ DeleteUserProfileBranch,
781
+ DeleteUserProfileBranchDefect,
782
+ DeleteUserProfileBranchDeleted,
783
+ DeleteUserProfileBranchInvalidResponse,
784
+ DeleteUserProfileBranchProviderRejected,
785
+ DeleteUserProfileDefinition,
786
+ DeleteUserProfileInputSchema,
787
+ DeleteUserProfileMetadata,
788
+ DeleteUserProfileOperation,
789
+ GetUserProfileBranch,
790
+ GetUserProfileBranchDefect,
791
+ GetUserProfileBranchFound,
792
+ GetUserProfileBranchInvalidResponse,
793
+ GetUserProfileBranchNotFound,
794
+ GetUserProfileBranchProviderRejected,
795
+ GetUserProfileDefinition,
796
+ GetUserProfileInputSchema,
797
+ GetUserProfileMetadata,
798
+ GetUserProfileOperation,
799
+ ListCampaignsBranch,
800
+ ListCampaignsBranchDefect,
801
+ ListCampaignsBranchInvalidResponse,
802
+ ListCampaignsBranchListed,
803
+ ListCampaignsBranchProviderRejected,
804
+ ListCampaignsDefinition,
805
+ ListCampaignsInputSchema,
806
+ ListCampaignsMetadata,
807
+ ListCampaignsOperation,
808
+ ListCanvasesBranch,
809
+ ListCanvasesBranchDefect,
810
+ ListCanvasesBranchInvalidResponse,
811
+ ListCanvasesBranchListed,
812
+ ListCanvasesBranchProviderRejected,
813
+ ListCanvasesDefinition,
814
+ ListCanvasesInputSchema,
815
+ ListCanvasesMetadata,
816
+ ListCanvasesOperation,
817
+ ListSegmentsBranch,
818
+ ListSegmentsBranchDefect,
819
+ ListSegmentsBranchInvalidResponse,
820
+ ListSegmentsBranchListed,
821
+ ListSegmentsBranchProviderRejected,
822
+ ListSegmentsDefinition,
823
+ ListSegmentsInputSchema,
824
+ ListSegmentsMetadata,
825
+ ListSegmentsOperation,
826
+ ProviderID,
827
+ SegmentIdentitySchema,
828
+ SegmentsListSchema,
829
+ TargetedSendResultSchema,
830
+ TriggerCampaignSendBranch,
831
+ TriggerCampaignSendBranchDefect,
832
+ TriggerCampaignSendBranchProviderRejected,
833
+ TriggerCampaignSendBranchSent,
834
+ TriggerCampaignSendBranchUncertain,
835
+ TriggerCampaignSendDefinition,
836
+ TriggerCampaignSendInputSchema,
837
+ TriggerCampaignSendMetadata,
838
+ TriggerCampaignSendOperation,
839
+ TriggerCanvasSendBranch,
840
+ TriggerCanvasSendBranchDefect,
841
+ TriggerCanvasSendBranchProviderRejected,
842
+ TriggerCanvasSendBranchSent,
843
+ TriggerCanvasSendBranchUncertain,
844
+ TriggerCanvasSendDefinition,
845
+ TriggerCanvasSendInputSchema,
846
+ TriggerCanvasSendMetadata,
847
+ TriggerCanvasSendOperation,
848
+ UpdateUserProfileBranch,
849
+ UpdateUserProfileBranchAccepted,
850
+ UpdateUserProfileBranchDefect,
851
+ UpdateUserProfileBranchInvalidResponse,
852
+ UpdateUserProfileBranchProviderRejected,
853
+ UpdateUserProfileDefinition,
854
+ UpdateUserProfileInputSchema,
855
+ UpdateUserProfileMetadata,
856
+ UpdateUserProfileOperation,
857
+ UserDeleteResultSchema,
858
+ UserProfileSchema,
859
+ UserWriteResultSchema,
860
+ decodeCredentials,
861
+ isCredentialMaterialError,
862
+ newConnection,
863
+ newConnectionWithOperations,
864
+ newDeleteUserProfileStep,
865
+ newGetUserProfileStep,
866
+ newListCampaignsStep,
867
+ newListCanvasesStep,
868
+ newListSegmentsStep,
869
+ newProjectConnection2 as newProjectConnection,
870
+ newTriggerCampaignSendStep,
871
+ newTriggerCanvasSendStep,
872
+ newUpdateUserProfileStep
873
+ };