@superdurable/connector-braze 0.1.0 → 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 CHANGED
@@ -1,7 +1,20 @@
1
1
  import {
2
+ CampaignIdentitySchema,
3
+ CampaignsListSchema,
4
+ CanvasIdentitySchema,
5
+ CanvasesListSchema,
2
6
  ConfigSchema,
3
7
  Connection,
4
8
  ConnectorID,
9
+ CredentialMaterialError,
10
+ DeleteUserProfileBranch,
11
+ DeleteUserProfileBranchDefect,
12
+ DeleteUserProfileBranchDeleted,
13
+ DeleteUserProfileBranchInvalidResponse,
14
+ DeleteUserProfileBranchProviderRejected,
15
+ DeleteUserProfileDefinition,
16
+ DeleteUserProfileInputSchema,
17
+ DeleteUserProfileMetadata,
5
18
  GetUserProfileBranch,
6
19
  GetUserProfileBranchDefect,
7
20
  GetUserProfileBranchFound,
@@ -11,16 +24,140 @@ import {
11
24
  GetUserProfileDefinition,
12
25
  GetUserProfileInputSchema,
13
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,
14
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,
15
80
  UserProfileSchema,
81
+ UserWriteResultSchema,
16
82
  decodeCredentials,
83
+ isCredentialMaterialError,
17
84
  newConnection,
18
85
  newConnectionWithOperations,
19
86
  newProjectConnection
20
- } from "./chunk-VGRZKZ7B.js";
87
+ } from "./chunk-E4CIKIAP.js";
21
88
 
22
89
  // src/generated/steps.ts
23
- import { goToBranch, newQueryStep } from "@superdurable/connectors-sdk";
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
+ }
24
161
  function newGetUserProfileStep(configuration) {
25
162
  const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
26
163
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
@@ -38,10 +175,14 @@ import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
38
175
  import { z } from "zod";
39
176
 
40
177
  // src/client.ts
41
- import { SecretString, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
42
- import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
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";
43
182
  var fieldsToExport = ["external_id", "braze_id", "first_name", "last_name", "email"];
44
183
  var emptyProfile = () => ({ externalId: "" });
184
+ var providerRequest = /* @__PURE__ */ Symbol("Braze provider request");
185
+ var prepareTargetedSend = /* @__PURE__ */ Symbol("Braze targeted send");
45
186
  var BrazeClient = class {
46
187
  /** Validate account endpoint and request limits without contacting Braze. */
47
188
  constructor(config, credentials, options = {}) {
@@ -63,25 +204,66 @@ var BrazeClient = class {
63
204
  getUserProfile() {
64
205
  return new GetUserProfileOperation(this);
65
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
+ }
66
235
  /** Resolve the key and send one bounded profile export request. */
67
236
  async post(call, externalID) {
68
- let token;
237
+ return this[providerRequest](call, "POST", "/users/export/ids", jsonBody({ external_ids: [externalID], fields_to_export: fieldsToExport }));
238
+ }
239
+ async resolveToken(call) {
69
240
  try {
70
241
  const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
71
- token = credentials.restApiKey instanceof SecretString ? credentials.restApiKey.reveal() : "";
242
+ const token = credentials.restApiKey instanceof SecretString ? credentials.restApiKey.reveal() : "";
243
+ return token && isHeaderSafeCredential(token) ? token : void 0;
72
244
  } catch {
73
- return emptyExchange("credential");
245
+ return void 0;
74
246
  }
75
- if (!token || !isHeaderSafeCredential(token)) return emptyExchange("credential");
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) {
76
258
  const request = {
77
- url: `${this.baseURL}/users/export/ids`,
78
- method: "POST",
259
+ url: this.baseURL + path,
260
+ method,
79
261
  headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: `Bearer ${token}` },
80
- body: new TextEncoder().encode(JSON.stringify({ external_ids: [externalID], fields_to_export: fieldsToExport })),
262
+ ...payload ? { body: payload } : {},
81
263
  maxResponseBytes: this.maxResponseBytes,
82
264
  timeoutMs: this.timeoutMs,
83
265
  addressPolicy: this.baseURL.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP",
84
- signal: call.context.cancellationSignal
266
+ signal
85
267
  };
86
268
  let response;
87
269
  let isTooLarge = false;
@@ -91,6 +273,8 @@ var BrazeClient = class {
91
273
  if (error instanceof BodyTooLargeError && error.status !== void 0) {
92
274
  response = { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() };
93
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" };
94
278
  } else return emptyExchange("request");
95
279
  }
96
280
  const retryAfterMs = parseRetryAfter(header(response.headers, "retry-after"));
@@ -120,6 +304,7 @@ var GetUserProfileOperation = class {
120
304
  if (exchange.status === 408 || exchange.status >= 500) return retry("AVAILABILITY", "Braze is temporarily unavailable", exchange.retryAfterMs);
121
305
  if (exchange.status !== 200 && exchange.status !== 201) return terminal("providerRejected", "PROVIDER_REJECTION", `Braze rejected HTTP ${exchange.status}`);
122
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");
123
308
  const profile = decodeProfile(exchange.body, input.externalId);
124
309
  if (profile === void 0) return terminal("invalidResponse", "PROTOCOL", "Braze returned an invalid profile response");
125
310
  if (profile === null) return terminal("notFound", "NOT_FOUND", "Braze did not find the user");
@@ -156,8 +341,8 @@ function decodeProfile(body, externalID) {
156
341
  if (raw.users.length === 0) return null;
157
342
  const user = raw.users[0];
158
343
  if (!isObject(user) || user.external_id !== externalID) return void 0;
159
- for (const field of ["braze_id", "first_name", "last_name", "email"])
160
- if (user[field] !== void 0 && user[field] !== null && typeof user[field] !== "string") 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;
161
346
  const result = { externalId: externalID };
162
347
  if (user.braze_id) result.brazeId = user.braze_id;
163
348
  if (user.first_name) result.firstName = user.first_name;
@@ -165,6 +350,387 @@ function decodeProfile(body, externalID) {
165
350
  if (user.email) result.email = user.email;
166
351
  return result;
167
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
+ }
168
734
 
169
735
  // src/project.ts
170
736
  function newProjectConnection2(project, connectionName) {
@@ -203,9 +769,23 @@ function parseDurationMilliseconds(value) {
203
769
  }
204
770
  export {
205
771
  BrazeClient,
772
+ CampaignIdentitySchema,
773
+ CampaignsListSchema,
774
+ CanvasIdentitySchema,
775
+ CanvasesListSchema,
206
776
  ConfigSchema,
207
777
  Connection,
208
778
  ConnectorID,
779
+ CredentialMaterialError,
780
+ DeleteUserProfileBranch,
781
+ DeleteUserProfileBranchDefect,
782
+ DeleteUserProfileBranchDeleted,
783
+ DeleteUserProfileBranchInvalidResponse,
784
+ DeleteUserProfileBranchProviderRejected,
785
+ DeleteUserProfileDefinition,
786
+ DeleteUserProfileInputSchema,
787
+ DeleteUserProfileMetadata,
788
+ DeleteUserProfileOperation,
209
789
  GetUserProfileBranch,
210
790
  GetUserProfileBranchDefect,
211
791
  GetUserProfileBranchFound,
@@ -216,11 +796,78 @@ export {
216
796
  GetUserProfileInputSchema,
217
797
  GetUserProfileMetadata,
218
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,
219
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,
220
858
  UserProfileSchema,
859
+ UserWriteResultSchema,
221
860
  decodeCredentials,
861
+ isCredentialMaterialError,
222
862
  newConnection,
223
863
  newConnectionWithOperations,
864
+ newDeleteUserProfileStep,
224
865
  newGetUserProfileStep,
225
- newProjectConnection2 as newProjectConnection
866
+ newListCampaignsStep,
867
+ newListCanvasesStep,
868
+ newListSegmentsStep,
869
+ newProjectConnection2 as newProjectConnection,
870
+ newTriggerCampaignSendStep,
871
+ newTriggerCanvasSendStep,
872
+ newUpdateUserProfileStep
226
873
  };