@superdurable/connector-front 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,975 @@
1
+ import {
2
+ CommentSchema,
3
+ ConfigSchema,
4
+ Connection,
5
+ ConnectorID,
6
+ ContactHandleSchema,
7
+ ContactSchema,
8
+ ConversationDetailsSchema,
9
+ ConversationReplySchema,
10
+ ConversationSchema,
11
+ FindContactByEmailBranch,
12
+ FindContactByEmailBranchDefect,
13
+ FindContactByEmailBranchFound,
14
+ FindContactByEmailBranchInvalidResponse,
15
+ FindContactByEmailBranchNotFound,
16
+ FindContactByEmailBranchProviderRejected,
17
+ FindContactByEmailDefinition,
18
+ FindContactByEmailInputSchema,
19
+ FindContactByEmailMetadata,
20
+ FindContactByEmailOutputSchema,
21
+ GetConversationBranch,
22
+ GetConversationBranchDefect,
23
+ GetConversationBranchFound,
24
+ GetConversationBranchInvalidResponse,
25
+ GetConversationBranchMerged,
26
+ GetConversationBranchNotFound,
27
+ GetConversationBranchProviderRejected,
28
+ GetConversationDefinition,
29
+ GetConversationInputSchema,
30
+ GetConversationMetadata,
31
+ MessageSchema,
32
+ ProviderID,
33
+ RecipientSchema,
34
+ ReplyToConversationBranch,
35
+ ReplyToConversationBranchDefect,
36
+ ReplyToConversationBranchNotFound,
37
+ ReplyToConversationBranchProviderRejected,
38
+ ReplyToConversationBranchReplied,
39
+ ReplyToConversationBranchUncertain,
40
+ ReplyToConversationDefinition,
41
+ ReplyToConversationInputSchema,
42
+ ReplyToConversationMetadata,
43
+ SearchConversationsBranch,
44
+ SearchConversationsBranchDefect,
45
+ SearchConversationsBranchInvalidResponse,
46
+ SearchConversationsBranchProviderRejected,
47
+ SearchConversationsBranchSearched,
48
+ SearchConversationsDefinition,
49
+ SearchConversationsInputSchema,
50
+ SearchConversationsMetadata,
51
+ SearchConversationsOutputSchema,
52
+ TagSchema,
53
+ TeammateSchema,
54
+ UpdateConversationBranch,
55
+ UpdateConversationBranchDefect,
56
+ UpdateConversationBranchInvalidResponse,
57
+ UpdateConversationBranchNotFound,
58
+ UpdateConversationBranchProviderRejected,
59
+ UpdateConversationBranchUpdated,
60
+ UpdateConversationDefinition,
61
+ UpdateConversationInputSchema,
62
+ UpdateConversationMetadata,
63
+ UpdateConversationOutputSchema,
64
+ newConnection,
65
+ newConnectionWithOperations,
66
+ newProjectConnection
67
+ } from "./chunk-7HCGNRLW.js";
68
+
69
+ // src/generated/steps.ts
70
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
71
+ function newSearchConversationsStep(configuration) {
72
+ const { connection, connectionName, searched, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
73
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
74
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.searchConversations(), connection: connection.reference, branches: [
75
+ goToBranch("searched", searched),
76
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
77
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
78
+ ...defect ? [goToBranch("defect", defect)] : []
79
+ ] });
80
+ }
81
+ function newGetConversationStep(configuration) {
82
+ const { connection, connectionName, found, merged, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
83
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
84
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getConversation(), connection: connection.reference, branches: [
85
+ goToBranch("found", found),
86
+ ...merged ? [goToBranch("merged", merged)] : [],
87
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
88
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
89
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
90
+ ...defect ? [goToBranch("defect", defect)] : []
91
+ ] });
92
+ }
93
+ function newReplyToConversationStep(configuration) {
94
+ const { connection, connectionName, replied, notFound, providerRejected, uncertain, defect, ...stepConfiguration } = configuration;
95
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
96
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.replyToConversation(), connection: connection.reference, branches: [
97
+ goToBranch("replied", replied),
98
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
99
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
100
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : [],
101
+ ...defect ? [goToBranch("defect", defect)] : []
102
+ ] });
103
+ }
104
+ function newUpdateConversationStep(configuration) {
105
+ const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
106
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
107
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateConversation(), connection: connection.reference, branches: [
108
+ goToBranch("updated", updated),
109
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
110
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
111
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
112
+ ...defect ? [goToBranch("defect", defect)] : []
113
+ ] });
114
+ }
115
+ function newFindContactByEmailStep(configuration) {
116
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
117
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
118
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.findContactByEmail(), connection: connection.reference, branches: [
119
+ goToBranch("found", found),
120
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
121
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
122
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
123
+ ...defect ? [goToBranch("defect", defect)] : []
124
+ ] });
125
+ }
126
+
127
+ // src/project.ts
128
+ import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
129
+ import { z } from "zod";
130
+
131
+ // src/client.ts
132
+ import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, ProviderTransportError, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
133
+ import { ReauthorizationRequiredError, SecretString, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
134
+
135
+ // src/operations.ts
136
+ import { newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
137
+ import { newFence } from "@superdurable/connectors-sdk/singledispatch";
138
+
139
+ // src/wire.ts
140
+ var identifiers = {
141
+ conversation: /^cnv_[A-Za-z0-9]{1,40}$/,
142
+ teammate: /^tea_[A-Za-z0-9]{1,40}$/,
143
+ tag: /^tag_[A-Za-z0-9]{1,40}$/,
144
+ inbox: /^inb_[A-Za-z0-9]{1,40}$/,
145
+ status: /^sts_[A-Za-z0-9]{1,40}$/,
146
+ contact: /^crd_[A-Za-z0-9]{1,40}$/,
147
+ message: /^msg_[A-Za-z0-9]{1,40}$/,
148
+ comment: /^com_[A-Za-z0-9]{1,40}$/,
149
+ pageToken: /^[A-Za-z0-9._~-]{1,1000}$/
150
+ };
151
+ function object(value) {
152
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("expected an object");
153
+ return value;
154
+ }
155
+ function string(value) {
156
+ if (value == null) return "";
157
+ if (typeof value !== "string") throw new Error("expected a string");
158
+ return value;
159
+ }
160
+ function array(value) {
161
+ if (value == null) return [];
162
+ if (!Array.isArray(value)) throw new Error("expected a list");
163
+ return value;
164
+ }
165
+ function decode(body) {
166
+ return object(JSON.parse(Buffer.from(body).toString("utf8")));
167
+ }
168
+ function requireID(label, value, pattern) {
169
+ if (!pattern.test(value)) throw new Error(`${label} must be a Front ID`);
170
+ }
171
+ function timestamp(value) {
172
+ if (value == null) return "0001-01-01T00:00:00Z";
173
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1e11) throw new Error("a Front timestamp is not Unix seconds");
174
+ if (value === 0) return "0001-01-01T00:00:00Z";
175
+ return new Date(Math.round(value * 1e3)).toISOString().replace(/\.000Z$/, "Z");
176
+ }
177
+ function optionalTimestamp(value) {
178
+ const time = timestamp(value);
179
+ return time.startsWith("0001-") ? void 0 : time;
180
+ }
181
+ function optional(key, value) {
182
+ return value === void 0 || value === null || value === "" ? {} : { [key]: value };
183
+ }
184
+ function list(key, values) {
185
+ return values.length ? { [key]: values } : {};
186
+ }
187
+ function teammate(value) {
188
+ if (value == null) return void 0;
189
+ const wire = object(value);
190
+ if (!wire.id && !wire.email) return void 0;
191
+ requireID("teammate", string(wire.id), identifiers.teammate);
192
+ return { id: string(wire.id), ...optional("email", string(wire.email)), ...optional("firstName", string(wire.first_name)), ...optional("lastName", string(wire.last_name)) };
193
+ }
194
+ function recipient(value) {
195
+ const wire = object(value);
196
+ const related = object(object(wire._links ?? {}).related ?? {});
197
+ let contactId = "";
198
+ try {
199
+ const last = new URL(string(related.contact), "https://api2.frontapp.com").pathname.split("/").at(-1) ?? "";
200
+ if (identifiers.contact.test(last)) contactId = last;
201
+ } catch {
202
+ }
203
+ return { handle: string(wire.handle), ...optional("role", string(wire.role)), ...optional("name", string(wire.name)), ...optional("contactId", contactId) };
204
+ }
205
+ function conversation(wire) {
206
+ requireID("conversation", string(wire.id), identifiers.conversation);
207
+ if (!wire.status) throw new Error("a conversation lacks a status");
208
+ const statusId = string(wire.status_id);
209
+ if (statusId) requireID("status", statusId, identifiers.status);
210
+ const tags = array(wire.tags).map((value) => {
211
+ const tag = object(value);
212
+ requireID("tag", string(tag.id), identifiers.tag);
213
+ return { id: string(tag.id), ...optional("name", string(tag.name)) };
214
+ });
215
+ const assignee = teammate(wire.assignee);
216
+ const mainRecipient = wire.recipient == null || !string(object(wire.recipient).handle) ? void 0 : recipient(wire.recipient);
217
+ return {
218
+ id: string(wire.id),
219
+ status: string(wire.status),
220
+ createdAt: timestamp(wire.created_at),
221
+ ...optional("type", string(wire.type)),
222
+ ...optional("subject", string(wire.subject)),
223
+ ...optional("statusId", statusId),
224
+ ...optional("statusCategory", string(wire.status_category)),
225
+ ...list("ticketIds", array(wire.ticket_ids).map(string)),
226
+ ...assignee ? { assignee } : {},
227
+ ...mainRecipient ? { recipient: mainRecipient } : {},
228
+ ...list("tags", tags),
229
+ ...wire.is_private ? { isPrivate: true } : {},
230
+ ...string(wire.status) === "archived" && array(wire.scheduled_reminders).length ? { isSnoozed: true } : {},
231
+ ...optional("updatedAt", optionalTimestamp(wire.updated_at)),
232
+ ...optional("waitingSince", optionalTimestamp(wire.waiting_since)),
233
+ ...optional("dueAt", optionalTimestamp(wire.due_at))
234
+ };
235
+ }
236
+ function page(body) {
237
+ const wire = decode(body);
238
+ if (!Array.isArray(wire._results)) throw new Error("the page has no list");
239
+ return { results: wire._results.map(object), next: object(wire._pagination ?? {}).next, total: wire._total };
240
+ }
241
+ function truncate(value) {
242
+ const bytes = Buffer.from(value);
243
+ if (bytes.length <= 16384) return { body: value };
244
+ let cut = 16384;
245
+ while (cut > 0 && (bytes[cut] & 192) === 128) cut--;
246
+ return { body: bytes.subarray(0, cut).toString("utf8"), isBodyTruncated: true };
247
+ }
248
+ function message(wire) {
249
+ requireID("message", string(wire.id), identifiers.message);
250
+ const author = teammate(wire.author);
251
+ const recipients = array(wire.recipients).map(recipient);
252
+ return {
253
+ id: string(wire.id),
254
+ isInbound: Boolean(wire.is_inbound),
255
+ createdAt: timestamp(wire.created_at),
256
+ ...optional("type", string(wire.type)),
257
+ ...wire.draft_mode ? { isDraft: true } : {},
258
+ ...optional("subject", string(wire.subject)),
259
+ ...optional("blurb", string(wire.blurb)),
260
+ ...string(wire.body) ? truncate(string(wire.body)) : {},
261
+ ...author ? { author } : {},
262
+ ...list("recipients", recipients)
263
+ };
264
+ }
265
+ function comment(wire) {
266
+ requireID("comment", string(wire.id), identifiers.comment);
267
+ const author = teammate(wire.author);
268
+ return {
269
+ id: string(wire.id),
270
+ postedAt: timestamp(wire.posted_at),
271
+ ...string(wire.body) ? truncate(string(wire.body)) : {},
272
+ ...author ? { author } : {},
273
+ ...wire.is_pinned ? { isPinned: true } : {}
274
+ };
275
+ }
276
+ function contact(wire, email) {
277
+ requireID("contact", string(wire.id), identifiers.contact);
278
+ const handles = array(wire.handles).map((value) => ({ handle: string(object(value).handle), source: string(object(value).source) }));
279
+ if (!handles.some((handle) => handle.source === "email" && handle.handle.toLowerCase() === email.toLowerCase())) throw new Error("the contact does not hold the requested email handle");
280
+ const listNames = array(wire.lists).map((value) => string(object(value).name)).filter(Boolean);
281
+ return {
282
+ id: string(wire.id),
283
+ ...optional("name", string(wire.name)),
284
+ ...optional("description", string(wire.description)),
285
+ ...list("handles", handles),
286
+ ...list("listNames", listNames),
287
+ ...wire.is_private ? { isPrivate: true } : {},
288
+ ...optional("updatedAt", optionalTimestamp(wire.updated_at))
289
+ };
290
+ }
291
+
292
+ // src/operations.ts
293
+ var zeroConversation = { id: "", status: "", createdAt: "0001-01-01T00:00:00Z" };
294
+ var zeroDetails = () => ({ conversation: zeroConversation, messages: [], comments: [] });
295
+ var zeroUpdate = () => ({ conversation: zeroConversation });
296
+ var isRetry = (exchange) => ["notSent", "rateLimited", "unconfirmed"].includes(exchange.outcome);
297
+ function fail(client, operation, kind, message2) {
298
+ return client.failure(kind, operation, message2);
299
+ }
300
+ function queryFailure(client, operation, branch, output, receipt, kind, message2) {
301
+ return newQueryBranch(branch, output, receipt, fail(client, operation, kind, message2));
302
+ }
303
+ function mutationFailure(client, operation, branch, output, receipt, kind, message2) {
304
+ return newMutationBranch(branch, output, receipt, fail(client, operation, kind, message2));
305
+ }
306
+ function header(exchange, name) {
307
+ const value = exchange.response?.headers[name.toLowerCase()];
308
+ return Array.isArray(value) ? value[0] ?? "" : value ?? "";
309
+ }
310
+ function mergedID(exchange) {
311
+ try {
312
+ const last = new URL(header(exchange, "location"), "https://api2.frontapp.com").pathname.split("/").at(-1) ?? "";
313
+ return identifiers.conversation.test(last) ? last : "";
314
+ } catch {
315
+ return "";
316
+ }
317
+ }
318
+ async function tokenOrBranch(client, call, operation, output) {
319
+ const value = await client.resolveToken(call);
320
+ return "token" in value ? value : { attempt: queryFailure(client, operation, "defect", output, {}, "AUTHENTICATION", value.failure.message) };
321
+ }
322
+ var SearchConversationsOperation = class {
323
+ /** Bind one client. */
324
+ constructor(client) {
325
+ this.client = client;
326
+ }
327
+ client;
328
+ /** Return the manifest definition. */
329
+ definition() {
330
+ return SearchConversationsDefinition;
331
+ }
332
+ /** Validate filters, search, and classify one page. */
333
+ async invoke(call, input) {
334
+ let query = "";
335
+ const output = { conversations: [], totalCount: 0, query };
336
+ try {
337
+ query = buildConversationSearchQuery(input);
338
+ validatePage(input);
339
+ output.query = query;
340
+ } catch (error) {
341
+ return queryFailure(this.client, "searchConversations", "defect", output, {}, "VALIDATION", errorMessage(error));
342
+ }
343
+ const selected = await tokenOrBranch(this.client, call, "searchConversations", output);
344
+ if ("attempt" in selected) return selected.attempt;
345
+ const parameters = new URLSearchParams({ limit: String(input.pageSize || 25) });
346
+ if (input.pageToken) parameters.set("page_token", input.pageToken);
347
+ const result = await this.client.exchange(call, selected.token, "searchConversations", { method: "GET", path: `/conversations/search/${goQueryEscape(query)}`, query: parameters });
348
+ const receipt = this.client.receipt(call);
349
+ if (isRetry(result)) return newQueryRetry(result.failure, result.retryAfterMs);
350
+ if (result.outcome !== "succeeded") return newQueryBranch(result.outcome === "invalid" ? "invalidResponse" : result.outcome === "defect" ? "defect" : "providerRejected", output, result.outcome === "defect" ? {} : receipt, result.failure);
351
+ try {
352
+ const answer = page(result.response.body);
353
+ output.conversations = answer.results.map(conversation);
354
+ output.totalCount = typeof answer.total === "number" && answer.total >= 0 ? answer.total : 0;
355
+ const next = this.client.nextPageToken(answer.next, "/conversations/search/");
356
+ if (next) output.nextPageToken = next;
357
+ return newQueryBranch("searched", output, receipt);
358
+ } catch (error) {
359
+ return queryFailure(this.client, "searchConversations", "invalidResponse", { conversations: [], totalCount: 0, query }, receipt, "PROTOCOL", `Front returned an invalid search page: ${errorMessage(error)}`);
360
+ }
361
+ }
362
+ };
363
+ var GetConversationOperation = class {
364
+ /** Bind one client. */
365
+ constructor(client) {
366
+ this.client = client;
367
+ }
368
+ client;
369
+ /** Return the manifest definition. */
370
+ definition() {
371
+ return GetConversationDefinition;
372
+ }
373
+ /** Read and classify the three provider resources. */
374
+ async invoke(call, input) {
375
+ const output = zeroDetails();
376
+ try {
377
+ requireID("conversationId", input.conversationId, identifiers.conversation);
378
+ if ((input.messageLimit ?? 0) < 0 || (input.messageLimit ?? 0) > 25 || (input.commentLimit ?? 0) < 0 || (input.commentLimit ?? 0) > 25) throw new Error("messageLimit and commentLimit must be 1 to 25, or zero for 10");
379
+ } catch (error) {
380
+ return queryFailure(this.client, "getConversation", "defect", output, {}, "VALIDATION", errorMessage(error));
381
+ }
382
+ const selected = await tokenOrBranch(this.client, call, "getConversation", output);
383
+ if ("attempt" in selected) return selected.attempt;
384
+ const base = `/conversations/${input.conversationId}`;
385
+ const requests = [{ method: "GET", path: base }, { method: "GET", path: `${base}/messages`, query: new URLSearchParams({ limit: String(input.messageLimit || 10) }) }, { method: "GET", path: `${base}/comments` }];
386
+ const receipt = this.client.receipt(call, input.conversationId);
387
+ for (let index = 0; index < requests.length; index++) {
388
+ const result = await this.client.exchange(call, selected.token, "getConversation", requests[index]);
389
+ if (isRetry(result)) return newQueryRetry(result.failure, result.retryAfterMs);
390
+ if (result.outcome !== "succeeded") {
391
+ if (result.outcome === "merged") {
392
+ const merged = mergedID(result);
393
+ if (merged) output.mergedIntoConversationId = merged;
394
+ }
395
+ const branch = result.outcome === "merged" ? "merged" : result.outcome === "notFound" ? "notFound" : result.outcome === "invalid" ? "invalidResponse" : result.outcome === "defect" ? "defect" : "providerRejected";
396
+ return newQueryBranch(branch, output, branch === "defect" ? {} : receipt, result.failure);
397
+ }
398
+ try {
399
+ if (index === 0) {
400
+ output.conversation = conversation(decode(result.response.body));
401
+ if (output.conversation.id !== input.conversationId) throw new Error("Front returned another conversation");
402
+ } else if (index === 1) {
403
+ const answer = page(result.response.body);
404
+ output.messages = answer.results.map(message);
405
+ if (this.client.nextPageToken(answer.next, `${base}/messages`)) output.hasOlderMessages = true;
406
+ } else {
407
+ const answer = page(result.response.body);
408
+ output.comments = answer.results.slice(0, input.commentLimit || 10).map(comment);
409
+ if (answer.results.length > (input.commentLimit || 10)) output.hasOlderComments = true;
410
+ }
411
+ } catch (error) {
412
+ return queryFailure(this.client, "getConversation", "invalidResponse", zeroDetails(), receipt, "PROTOCOL", `Front returned an invalid conversation: ${errorMessage(error)}`);
413
+ }
414
+ }
415
+ return newQueryBranch("found", output, receipt);
416
+ }
417
+ };
418
+ var FindContactByEmailOperation = class {
419
+ /** Bind one client. */
420
+ constructor(client) {
421
+ this.client = client;
422
+ }
423
+ client;
424
+ /** Return the manifest definition. */
425
+ definition() {
426
+ return FindContactByEmailDefinition;
427
+ }
428
+ /** Read the contact alias and verify its email handle. */
429
+ async invoke(call, input) {
430
+ const output = { contacts: [] };
431
+ try {
432
+ validateBareEmail(input.email);
433
+ } catch (error) {
434
+ return queryFailure(this.client, "findContactByEmail", "defect", output, {}, "VALIDATION", errorMessage(error));
435
+ }
436
+ const selected = await tokenOrBranch(this.client, call, "findContactByEmail", output);
437
+ if ("attempt" in selected) return selected.attempt;
438
+ const result = await this.client.exchange(call, selected.token, "findContactByEmail", { method: "GET", path: `/contacts/alt:email:${goPathEscape(input.email)}` });
439
+ const receipt = this.client.receipt(call);
440
+ if (isRetry(result)) return newQueryRetry(result.failure, result.retryAfterMs);
441
+ if (result.outcome !== "succeeded") return newQueryBranch(result.outcome === "notFound" ? "notFound" : result.outcome === "invalid" ? "invalidResponse" : result.outcome === "defect" ? "defect" : "providerRejected", output, result.outcome === "defect" ? {} : receipt, result.failure);
442
+ try {
443
+ const found = contact(decode(result.response.body), input.email);
444
+ output.contacts = [found];
445
+ return newQueryBranch("found", output, this.client.receipt(call, found.id));
446
+ } catch (error) {
447
+ return queryFailure(this.client, "findContactByEmail", "invalidResponse", output, receipt, "PROTOCOL", `Front returned an invalid contact: ${errorMessage(error)}`);
448
+ }
449
+ }
450
+ };
451
+ var UpdateConversationOperation = class {
452
+ /** Bind one client. */
453
+ constructor(client) {
454
+ this.client = client;
455
+ }
456
+ client;
457
+ /** Return the manifest definition. */
458
+ definition() {
459
+ return UpdateConversationDefinition;
460
+ }
461
+ /** Stable call identity; writes set absolute values. */
462
+ idempotencyKey(callId) {
463
+ return callId;
464
+ }
465
+ /** Read, plan writes, and confirm the result. */
466
+ async invoke(call, input) {
467
+ const zero = zeroUpdate();
468
+ try {
469
+ validateUpdate(input);
470
+ } catch (error) {
471
+ return mutationFailure(this.client, "updateConversation", "defect", zero, {}, "VALIDATION", errorMessage(error));
472
+ }
473
+ const selected = await this.client.resolveToken(call);
474
+ if (!("token" in selected)) return newMutationBranch("defect", zero, {}, selected.failure);
475
+ const path = `/conversations/${input.conversationId}`;
476
+ const receipt = this.client.receipt(call, input.conversationId);
477
+ const read = async () => {
478
+ const result = await this.client.exchange(call, selected.token, "updateConversation", { method: "GET", path });
479
+ if (result.outcome !== "succeeded") return { attempt: classifyUpdate(result, zero, receipt) };
480
+ try {
481
+ const value = conversation(decode(result.response.body));
482
+ if (value.id !== input.conversationId) throw new Error("Front returned another conversation");
483
+ return { conversation: value };
484
+ } catch (error) {
485
+ return { attempt: mutationFailure(this.client, "updateConversation", "invalidResponse", zero, receipt, "PROTOCOL", `Front returned an invalid conversation: ${errorMessage(error)}`) };
486
+ }
487
+ };
488
+ const initial = await read();
489
+ if ("attempt" in initial) return initial.attempt;
490
+ const writes = planWrites(input, initial.conversation, path);
491
+ for (let index = 0; index < writes.length; index++) {
492
+ const result = await this.client.exchange(call, selected.token, "updateConversation", writes[index]);
493
+ if (result.outcome !== "succeeded") {
494
+ if (result.outcome === "notFound") result.outcome = "rejected";
495
+ return classifyUpdate(result, zero, receipt, index > 0 ? "; writes sent before it stay applied" : "");
496
+ }
497
+ }
498
+ if (!writes.length) return newMutationBranch("updated", { conversation: initial.conversation, wasAlreadyApplied: true }, receipt);
499
+ const final = await read();
500
+ if ("attempt" in final) return final.attempt;
501
+ if (planWrites(input, final.conversation, path).length) return newMutationRetry(fail(this.client, "updateConversation", "AVAILABILITY", "Front accepted the change but does not show it on the conversation yet"));
502
+ return newMutationBranch("updated", { conversation: final.conversation }, receipt);
503
+ }
504
+ };
505
+ var ReplyToConversationOperation = class {
506
+ /** Bind one client. */
507
+ constructor(client) {
508
+ this.client = client;
509
+ }
510
+ client;
511
+ /** Return the manifest definition. */
512
+ definition() {
513
+ return ReplyToConversationDefinition;
514
+ }
515
+ /** Stable call identity, recorded in the receipt. */
516
+ idempotencyKey(callId) {
517
+ return callId;
518
+ }
519
+ /** Send once with a durable claim, or read back an accepted provider ID. */
520
+ async invoke(call, input) {
521
+ const output = { conversationId: input.conversationId, ...input.isInternalNote ? { isInternalNote: true } : {}, ...input.authorId ? { authorId: input.authorId } : {} };
522
+ try {
523
+ validateReply(input);
524
+ } catch (error) {
525
+ return mutationFailure(this.client, "replyToConversation", "defect", output, {}, "VALIDATION", errorMessage(error));
526
+ }
527
+ let fence;
528
+ try {
529
+ fence = newFence(call, 3e4);
530
+ } catch (error) {
531
+ return mutationFailure(this.client, "replyToConversation", "defect", output, {}, "LOCAL_DEFECT", errorMessage(error));
532
+ }
533
+ const decision = fence.decide();
534
+ if (decision.kind === "failClosed") return this.uncertain(call, output, "AVAILABILITY", "the dispatch checkpoint could not be trusted; the reply or comment is not sent again");
535
+ if (decision.kind === "readBackRequired") return this.readBack(call, input, output, decision.marker);
536
+ const selected = await this.client.resolveToken(call);
537
+ if (!("token" in selected)) {
538
+ try {
539
+ await fence.recordNotSent();
540
+ } catch {
541
+ return newMutationRetry(fail(this.client, "replyToConversation", "AVAILABILITY", "Front credentials were temporarily unavailable and the not-sent checkpoint failed"));
542
+ }
543
+ if (selected.terminal) return mutationFailure(this.client, "replyToConversation", "defect", output, {}, "AUTHENTICATION", "Reconnect the Front connection before sending the reply or comment");
544
+ return newMutationRetry(fail(this.client, "replyToConversation", "AVAILABILITY", "Front credentials were temporarily unavailable"));
545
+ }
546
+ const path = `/conversations/${input.conversationId}/${input.isInternalNote ? "comments" : "messages"}`;
547
+ const payload = input.isInternalNote ? { body: input.text, ...input.authorId ? { author_id: input.authorId } : {} } : { body: buildReplyHTML(input.text), text: input.text, ...input.authorId ? { author_id: input.authorId } : {}, options: { archive: Boolean(input.shouldArchive) } };
548
+ let result;
549
+ try {
550
+ result = await fence.dispatch((signal) => this.client.exchange(call, selected.token, "replyToConversation", { method: "POST", path, payload, signal }));
551
+ } catch {
552
+ return newMutationRetry(fail(this.client, "replyToConversation", "AVAILABILITY", "the reply was not dispatched; retry after the checkpoint or attempt budget recovers"));
553
+ }
554
+ return this.classifySend(call, output, result, fence, selected.token);
555
+ }
556
+ async readBack(call, input, output, marker) {
557
+ if (!marker || marker.callId !== call.id || !marker.providerId) return this.uncertain(call, output, marker?.state === "claimed" ? "TRANSPORT" : "AVAILABILITY", "an earlier attempt may have sent the reply or comment without a provider ID");
558
+ if (!(input.isInternalNote ? identifiers.comment : /^[A-Za-z0-9]{1,64}$/).test(marker.providerId)) return this.uncertain(call, output, "PROTOCOL", "an earlier attempt stored an invalid provider ID");
559
+ const selected = await this.client.resolveToken(call);
560
+ if (!("token" in selected)) return selected.terminal ? newMutationUncertain(output, fail(this.client, "replyToConversation", "AUTHENTICATION", "Front accepted an earlier reply or comment, but its connection needs reconnection before read-back; verify the saved provider ID before retrying manually"), this.client.receipt(call, marker.providerId)) : newMutationRetry(fail(this.client, "replyToConversation", "AVAILABILITY", "Front credentials were temporarily unavailable during read-back"));
561
+ const path = input.isInternalNote ? `/comments/${marker.providerId}` : `/messages/alt:uid:${marker.providerId}`;
562
+ const result = await this.client.exchange(call, selected.token, "replyToConversation", { method: "GET", path });
563
+ if (result.outcome === "succeeded") return newMutationBranch("replied", { ...output, ...input.isInternalNote ? { commentId: marker.providerId } : { messageUid: marker.providerId } }, this.client.receipt(call, marker.providerId));
564
+ if (isRetry(result) || result.outcome === "notFound" && !input.isInternalNote) return newMutationRetry(result.failure, result.retryAfterMs);
565
+ return newMutationUncertain(output, fail(this.client, "replyToConversation", result.failure.kind, "Front could not confirm an earlier accepted reply or comment"), this.client.receipt(call, marker.providerId));
566
+ }
567
+ async classifySend(call, output, result, fence, rejectedToken) {
568
+ const receipt = this.client.receipt(call, output.conversationId);
569
+ if (result.response && result.response.status >= 200 && result.response.status < 300) {
570
+ let identity = "";
571
+ try {
572
+ const answer = decode(result.response.body);
573
+ identity = string(output.isInternalNote ? answer.id : answer.message_uid);
574
+ } catch {
575
+ }
576
+ if (!(output.isInternalNote ? identifiers.comment : /^[A-Za-z0-9]{1,64}$/).test(identity)) return this.uncertain(call, output, result.failure?.kind ?? "PROTOCOL", "Front accepted the reply or comment, but its answer has no usable provider ID; do not resend");
577
+ try {
578
+ await fence.recordProviderId(identity);
579
+ } catch {
580
+ }
581
+ return newMutationBranch("replied", { ...output, ...output.isInternalNote ? { commentId: identity } : { messageUid: identity } }, this.client.receipt(call, identity));
582
+ }
583
+ if (result.outcome === "notSent" || result.outcome === "rateLimited" || result.outcome === "unconfirmed" && result.response?.status === 503) {
584
+ try {
585
+ await fence.recordCanResend();
586
+ } catch {
587
+ return newMutationRetry(fail(this.client, "replyToConversation", "AVAILABILITY", "the resend checkpoint failed"));
588
+ }
589
+ return newMutationRetry(result.failure, result.retryAfterMs);
590
+ }
591
+ if (result.outcome === "unconfirmed") return newMutationUncertain(output, { ...result.failure, message: `${result.failure.message}; the reply or comment may exist` }, receipt);
592
+ if (result.outcome === "notFound" || result.outcome === "merged") return newMutationBranch("notFound", output, receipt, result.failure);
593
+ if (result.outcome === "rejected") {
594
+ if (result.response?.status === 409) return this.uncertain(call, output, "CONFLICT", "Front returned a conflict without a key or unique value for read-back");
595
+ if (result.response?.status === 401) {
596
+ const replacement = await this.client.replacementAfterRejection(call, rejectedToken);
597
+ if (replacement === "replacement") {
598
+ try {
599
+ await fence.recordCanResend();
600
+ } catch {
601
+ return newMutationRetry(fail(this.client, "replyToConversation", "AVAILABILITY", "the credential resend checkpoint failed"));
602
+ }
603
+ return newMutationRetry(fail(this.client, "replyToConversation", "AUTHENTICATION", "Front rejected the prior API token; retry with its replacement"));
604
+ }
605
+ return mutationFailure(this.client, "replyToConversation", "providerRejected", output, receipt, "AUTHENTICATION", replacement === "reconnect" ? "Front rejected the API token (HTTP 401); reconnect the Front connection" : "Front rejected the API token (HTTP 401); credential refresh is temporarily unavailable");
606
+ }
607
+ return newMutationBranch("providerRejected", output, receipt, result.failure);
608
+ }
609
+ return this.uncertain(call, output, result.failure?.kind ?? "PROTOCOL", "the reply or comment may exist");
610
+ }
611
+ uncertain(call, output, kind, message2) {
612
+ return newMutationUncertain(output, fail(this.client, "replyToConversation", kind, message2), this.client.receipt(call, output.conversationId));
613
+ }
614
+ };
615
+ function errorMessage(error) {
616
+ return error instanceof Error ? error.message : "invalid value";
617
+ }
618
+ function goQueryEscape(value) {
619
+ return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
620
+ }
621
+ function goPathEscape(value) {
622
+ return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(24|26|2B|3D|3A|40)/g, (code) => String.fromCharCode(parseInt(code.slice(1), 16)));
623
+ }
624
+ function validateBareEmail(value) {
625
+ const match = /^([A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64})@([A-Za-z0-9.-]{1,253})$/.exec(value);
626
+ if (!match || match[1]?.startsWith(".") || match[1]?.endsWith(".") || match[1]?.includes("..") || match[2]?.startsWith(".") || match[2]?.endsWith(".") || match[2]?.includes("..") || !match[2]?.split(".").every((label) => /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(label))) throw new Error("email must be one bare email address such as jane@acme.example.com");
627
+ }
628
+ function validatePage(input) {
629
+ if ((input.pageSize ?? 0) < 0 || (input.pageSize ?? 0) > 100 || input.pageToken && !identifiers.pageToken.test(input.pageToken)) throw new Error("pageSize or pageToken is invalid");
630
+ }
631
+ function buildConversationSearchQuery(input) {
632
+ const terms = [];
633
+ const text = input.text?.trim() ?? "";
634
+ if (text) {
635
+ if (Buffer.byteLength(text) > 512 || /\p{Cc}/u.test(text)) throw new Error("text is too long or contains a control character");
636
+ terms.push(text);
637
+ }
638
+ if (input.inboxId) {
639
+ requireID("inboxId", input.inboxId, identifiers.inbox);
640
+ terms.push(`inbox:${input.inboxId}`);
641
+ }
642
+ if (input.tagId) {
643
+ requireID("tagId", input.tagId, identifiers.tag);
644
+ terms.push(`tag:${input.tagId}`);
645
+ }
646
+ const seen = /* @__PURE__ */ new Set();
647
+ for (const status of input.statuses ?? []) {
648
+ if (!["open", "archived", "snoozed", "trashed", "assigned", "unassigned", "unreplied", "waiting", "resolved"].includes(status)) throw new Error("statuses must be Front is: values");
649
+ if (!seen.has(status)) terms.push(`is:${status}`);
650
+ seen.add(status);
651
+ }
652
+ if (input.recipientEmail) {
653
+ validateBareEmail(input.recipientEmail);
654
+ terms.push(`recipient:${input.recipientEmail}`);
655
+ }
656
+ if (input.assigneeId) {
657
+ requireID("assigneeId", input.assigneeId, identifiers.teammate);
658
+ terms.push(`assignee:${input.assigneeId}`);
659
+ }
660
+ if (input.activityAfter) {
661
+ const seconds = Math.floor(Date.parse(input.activityAfter) / 1e3);
662
+ if (!Number.isFinite(seconds) || seconds < 1) throw new Error("activityAfter must be after 1970");
663
+ terms.push(`after:${seconds}`);
664
+ }
665
+ if (!terms.length) throw new Error("set text or at least one filter; Front has no empty search");
666
+ return terms.join(" ");
667
+ }
668
+ function classifyUpdate(result, output, receipt, note = "") {
669
+ if (isRetry(result)) return newMutationRetry(result.failure, result.retryAfterMs);
670
+ const branch = result.outcome === "merged" || result.outcome === "notFound" ? "notFound" : result.outcome === "invalid" ? "invalidResponse" : result.outcome === "defect" ? "defect" : "providerRejected";
671
+ return newMutationBranch(branch, output, branch === "defect" ? {} : receipt, result.failure ? { ...result.failure, message: result.failure.message + note } : void 0);
672
+ }
673
+ function validateUpdate(input) {
674
+ requireID("conversationId", input.conversationId, identifiers.conversation);
675
+ if (input.status && !["open", "archived", "deleted"].includes(input.status)) throw new Error("status must be open, archived, or deleted");
676
+ if (input.status && input.statusId) throw new Error("set status or statusId, not both");
677
+ if (input.assigneeId && input.isUnassigned) throw new Error("set assigneeId or isUnassigned, not both");
678
+ if ((input.addTagIds?.length ?? 0) > 25 || (input.removeTagIds?.length ?? 0) > 25) throw new Error("tag changes exceed 25");
679
+ if (!input.status && !input.statusId && !input.assigneeId && !input.isUnassigned && !input.addTagIds?.length && !input.removeTagIds?.length) throw new Error("set at least one change");
680
+ if (input.statusId) requireID("statusId", input.statusId, identifiers.status);
681
+ if (input.assigneeId) requireID("assigneeId", input.assigneeId, identifiers.teammate);
682
+ for (const id of [...input.addTagIds ?? [], ...input.removeTagIds ?? []]) requireID("tagId", id, identifiers.tag);
683
+ if (input.addTagIds?.some((id) => input.removeTagIds?.includes(id))) throw new Error("tag is both added and removed");
684
+ }
685
+ function planWrites(input, current, path) {
686
+ const patch = {};
687
+ if (input.status && !(input.status === "open" ? ["assigned", "unassigned"].includes(current.status) : current.status === input.status)) patch.status = input.status;
688
+ if (input.statusId && current.statusId !== input.statusId) patch.status_id = input.statusId;
689
+ if (input.assigneeId && current.assignee?.id !== input.assigneeId) patch.assignee_id = input.assigneeId;
690
+ if (input.isUnassigned && current.assignee?.id) patch.assignee_id = null;
691
+ const existing = new Set(current.tags?.map((tag) => tag.id) ?? []);
692
+ const add = [...new Set(input.addTagIds ?? [])].filter((id) => !existing.has(id));
693
+ const remove = [...new Set(input.removeTagIds ?? [])].filter((id) => existing.has(id));
694
+ return [...Object.keys(patch).length ? [{ method: "PATCH", path, payload: patch }] : [], ...add.length ? [{ method: "POST", path: `${path}/tags`, payload: { tag_ids: add } }] : [], ...remove.length ? [{ method: "DELETE", path: `${path}/tags`, payload: { tag_ids: remove } }] : []];
695
+ }
696
+ function validateReply(input) {
697
+ requireID("conversationId", input.conversationId, identifiers.conversation);
698
+ if (!input.text.trim() || Buffer.byteLength(input.text) > 65536) throw new Error("text is required and must fit 65536 bytes");
699
+ if (input.isInternalNote && input.shouldArchive) throw new Error("shouldArchive applies only to a reply");
700
+ if (input.authorId) requireID("authorId", input.authorId, identifiers.teammate);
701
+ }
702
+ function buildReplyHTML(value) {
703
+ return value.replace(/\r\n?/g, "\n").split("\n\n").map((block) => block.replace(/^\n+|\n+$/g, "")).filter((block) => block.trim()).map((block) => `<p>${block.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/\n/g, "<br>")}</p>`).join("");
704
+ }
705
+
706
+ // src/client.ts
707
+ var defaultEndpoint = "https://api2.frontapp.com";
708
+ var InvalidFrontTokenError = class extends Error {
709
+ };
710
+ var FrontClient = class {
711
+ /** Validated Front API base URL. */
712
+ endpoint;
713
+ maxResponseBytes;
714
+ credentials;
715
+ send;
716
+ now;
717
+ /** Construct a bounded client without contacting Front. */
718
+ constructor(config, credentials, options = {}) {
719
+ if (!credentials) throw new TypeError("Front credential provider is required");
720
+ this.endpoint = validateBaseURL(options.apiBaseURL ?? defaultEndpoint);
721
+ this.maxResponseBytes = config.maxResponseBytes ?? 4194304;
722
+ if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes < 1) throw new TypeError("Front maxResponseBytes must be positive");
723
+ this.credentials = credentials;
724
+ this.send = options.send ?? sendProviderRequest;
725
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
726
+ }
727
+ /** Bind the search query. */
728
+ searchConversations() {
729
+ return new SearchConversationsOperation(this);
730
+ }
731
+ /** Bind the conversation query. */
732
+ getConversation() {
733
+ return new GetConversationOperation(this);
734
+ }
735
+ /** Bind the fenced reply mutation. */
736
+ replyToConversation() {
737
+ return new ReplyToConversationOperation(this);
738
+ }
739
+ /** Bind the repeat-safe update mutation. */
740
+ updateConversation() {
741
+ return new UpdateConversationOperation(this);
742
+ }
743
+ /** Bind the contact query. */
744
+ findContactByEmail() {
745
+ return new FindContactByEmailOperation(this);
746
+ }
747
+ /** Resolve the current token before each logical operation. */
748
+ async resolveToken(call) {
749
+ try {
750
+ const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
751
+ if (!(credentials.apiToken instanceof SecretString)) throw new InvalidFrontTokenError();
752
+ const token = credentials.apiToken.reveal();
753
+ if (!isHeaderSafeCredential(token)) throw new InvalidFrontTokenError();
754
+ return { token };
755
+ } catch (error) {
756
+ return { failure: this.failure("AUTHENTICATION", call.operation.operationId, "the Front API token is unavailable, blank, or contains characters a header cannot carry"), terminal: error instanceof ReauthorizationRequiredError || error instanceof InvalidFrontTokenError };
757
+ }
758
+ }
759
+ /** Ask a refresh-capable credential source for a replacement after HTTP 401. */
760
+ async replacementAfterRejection(call, rejectedToken) {
761
+ if (!("resolveAfterRejection" in this.credentials) || typeof this.credentials.resolveAfterRejection !== "function") return "reconnect";
762
+ try {
763
+ const replacement = await resolveCredentialAfterRejection(this.credentials, call, {
764
+ refreshRequired: () => false,
765
+ refresh: async () => {
766
+ throw new ReauthorizationRequiredError();
767
+ }
768
+ }, call.context.cancellationSignal);
769
+ if (replacement.apiToken instanceof SecretString) {
770
+ const token = replacement.apiToken.reveal();
771
+ if (isHeaderSafeCredential(token) && token !== rejectedToken) return "replacement";
772
+ }
773
+ return "reconnect";
774
+ } catch (error) {
775
+ return error instanceof ReauthorizationRequiredError ? "reconnect" : "temporarilyUnavailable";
776
+ }
777
+ }
778
+ /** Send and classify one provider request. */
779
+ async exchange(call, token, operation, request) {
780
+ let body;
781
+ try {
782
+ if (request.payload !== void 0) body = Buffer.from(JSON.stringify(request.payload));
783
+ } catch {
784
+ return { outcome: "defect", failure: this.failure("LOCAL_DEFECT", operation, "Front request could not be built"), retryAfterMs: 0 };
785
+ }
786
+ const query = request.query?.toString();
787
+ const url = this.endpoint + request.path + (query ? `?${query}` : "");
788
+ let response;
789
+ try {
790
+ response = await this.send({
791
+ url,
792
+ method: request.method,
793
+ headers: { Authorization: `Bearer ${token}`, Accept: "application/json", ...body ? { "Content-Type": "application/json" } : {} },
794
+ ...body ? { body } : {},
795
+ maxResponseBytes: Math.max(this.maxResponseBytes, 65536),
796
+ addressPolicy: this.endpoint === defaultEndpoint ? "publicHTTPS" : "privateNetworkHTTP",
797
+ timeoutMs: 25e3,
798
+ signal: request.signal ?? call.context.cancellationSignal
799
+ });
800
+ } catch (error) {
801
+ if (error instanceof BodyTooLargeError) {
802
+ if (error.status && (error.status < 200 || error.status >= 300)) return this.classifyFailureStatus(error.status, error.headers ?? {}, operation);
803
+ return { outcome: "invalid", ...error.status ? { response: { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() } } : {}, failure: this.failure("RESPONSE_TOO_LARGE", operation, "the Front response exceeds the configured maxResponseBytes"), retryAfterMs: 0 };
804
+ }
805
+ return { outcome: error instanceof ProviderTransportError && error.isProvablyNotSent ? "notSent" : "unconfirmed", failure: this.failure("TRANSPORT", operation, error instanceof ProviderTransportError && error.isProvablyNotSent ? "Front could not be reached; no request was sent" : "the Front request may have been sent, but no answer arrived"), retryAfterMs: 0 };
806
+ }
807
+ const status = response.status;
808
+ if (status >= 200 && status < 300) {
809
+ if (response.body.length > this.maxResponseBytes) return { outcome: "invalid", response, failure: this.failure("RESPONSE_TOO_LARGE", operation, "the Front response exceeds the configured maxResponseBytes"), retryAfterMs: 0 };
810
+ if (Buffer.from(response.body).includes(Buffer.from(token))) return { outcome: "invalid", response, failure: this.failure("PROTOCOL", operation, "the Front response reflected the API token"), retryAfterMs: 0 };
811
+ return { outcome: "succeeded", response, retryAfterMs: 0 };
812
+ }
813
+ return this.classifyFailureStatus(status, response.headers, operation, response);
814
+ }
815
+ classifyFailureStatus(status, headers, operation, response) {
816
+ let outcome = "rejected";
817
+ let kind = "PROVIDER_REJECTION";
818
+ let message2 = `Front rejected the request (HTTP ${status})`;
819
+ let retryAfterMs = 0;
820
+ if (status === 429) {
821
+ outcome = "rateLimited";
822
+ kind = "RATE_LIMIT";
823
+ message2 = "Front rate limited the request (HTTP 429)";
824
+ retryAfterMs = this.rateLimitDelay(headers);
825
+ } else if (status === 408 || status >= 500) {
826
+ outcome = "unconfirmed";
827
+ kind = "AVAILABILITY";
828
+ message2 = `Front could not complete the request (HTTP ${status})`;
829
+ } else if (status === 301) {
830
+ outcome = "merged";
831
+ kind = "NOT_FOUND";
832
+ message2 = "Front reports that the conversation was merged into another (HTTP 301)";
833
+ } else if (status === 404 || status === 410) {
834
+ outcome = "notFound";
835
+ kind = "NOT_FOUND";
836
+ message2 = `Front found no such resource (HTTP ${status})`;
837
+ } else if (status >= 300 && status < 400) {
838
+ kind = "PROTOCOL";
839
+ message2 = `Front redirected the request (HTTP ${status}), which the connector never follows`;
840
+ } else if (status === 401) {
841
+ kind = "AUTHENTICATION";
842
+ message2 = "Front rejected the API token (HTTP 401); check that the token still exists";
843
+ } else if (status === 403) {
844
+ kind = "AUTHORIZATION";
845
+ message2 = "Front denied access (HTTP 403); check the token's namespaces and its read, write, or send permission for this resource";
846
+ } else if ([400, 413, 422].includes(status)) kind = "VALIDATION";
847
+ else if (status === 409) kind = "CONFLICT";
848
+ return { outcome, ...response ? { response } : {}, failure: this.failure(kind, operation, message2), retryAfterMs };
849
+ }
850
+ /** Return only public correlation fields. */
851
+ receipt(call, providerObjectId = "") {
852
+ return { callId: call.id, provider: "front", observedAt: this.now().toISOString(), ...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {}, ...providerObjectId ? { providerObjectId } : {} };
853
+ }
854
+ /** Construct a secret-safe failure. */
855
+ failure(kind, operation, message2) {
856
+ return { kind, provider: "front", operation, message: message2 };
857
+ }
858
+ /** Return the page token from a validated next link. */
859
+ nextPageToken(next, pathPrefix) {
860
+ if (next == null || next === "") return "";
861
+ if (typeof next !== "string") throw new Error("the next-page link is not a plain URL");
862
+ const parsed = new URL(next);
863
+ const base = new URL(this.endpoint);
864
+ if (parsed.username || parsed.password || parsed.hash || !(parsed.protocol === "https:" && (parsed.host === "api2.frontapp.com" || /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.api\.frontapp\.com$/.test(parsed.host)) || parsed.protocol === base.protocol && parsed.host === base.host)) throw new Error("the next-page link points outside Front's API hosts");
865
+ if (!parsed.pathname.startsWith(pathPrefix)) throw new Error("the next-page link names another resource");
866
+ const token = parsed.searchParams.get("page_token") ?? "";
867
+ if (!/^[A-Za-z0-9._~-]{1,1000}$/.test(token)) throw new Error("the next-page link has no valid page_token");
868
+ return token;
869
+ }
870
+ rateLimitDelay(headers) {
871
+ const value = headers["retry-after"];
872
+ const delay = parseRetryAfter(Array.isArray(value) ? value[0] ?? "" : value ?? "", this.now());
873
+ if (delay > 0) return delay;
874
+ const reset = Number(headers["x-ratelimit-reset"]);
875
+ return Number.isSafeInteger(reset) && reset > 0 ? Math.min(Math.max(reset * 1e3 - this.now().getTime(), 1e3), 6e4) : 0;
876
+ }
877
+ };
878
+
879
+ // src/project.ts
880
+ function newProjectConnection2(project, connectionName) {
881
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
882
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "front" && entry.connectionName === name);
883
+ if (!selected) throw new TypeError("Front project connection is not configured");
884
+ const config = z.object({ maxResponseBytes: z.number().int().optional() }).parse(selected.configuration);
885
+ const credentials = {
886
+ async resolve(call, signal) {
887
+ void call;
888
+ const fields = await loadedProject.resolveCredential("front", name, signal);
889
+ const decoded = z.object({ api_token: z.string().min(1) }).parse(fields);
890
+ return { apiToken: new SecretString2(decoded.api_token) };
891
+ }
892
+ };
893
+ return new FrontClient(config, credentials);
894
+ });
895
+ }
896
+ export {
897
+ CommentSchema,
898
+ ConfigSchema,
899
+ Connection,
900
+ ConnectorID,
901
+ ContactHandleSchema,
902
+ ContactSchema,
903
+ ConversationDetailsSchema,
904
+ ConversationReplySchema,
905
+ ConversationSchema,
906
+ FindContactByEmailBranch,
907
+ FindContactByEmailBranchDefect,
908
+ FindContactByEmailBranchFound,
909
+ FindContactByEmailBranchInvalidResponse,
910
+ FindContactByEmailBranchNotFound,
911
+ FindContactByEmailBranchProviderRejected,
912
+ FindContactByEmailDefinition,
913
+ FindContactByEmailInputSchema,
914
+ FindContactByEmailMetadata,
915
+ FindContactByEmailOperation,
916
+ FindContactByEmailOutputSchema,
917
+ FrontClient,
918
+ GetConversationBranch,
919
+ GetConversationBranchDefect,
920
+ GetConversationBranchFound,
921
+ GetConversationBranchInvalidResponse,
922
+ GetConversationBranchMerged,
923
+ GetConversationBranchNotFound,
924
+ GetConversationBranchProviderRejected,
925
+ GetConversationDefinition,
926
+ GetConversationInputSchema,
927
+ GetConversationMetadata,
928
+ GetConversationOperation,
929
+ MessageSchema,
930
+ ProviderID,
931
+ RecipientSchema,
932
+ ReplyToConversationBranch,
933
+ ReplyToConversationBranchDefect,
934
+ ReplyToConversationBranchNotFound,
935
+ ReplyToConversationBranchProviderRejected,
936
+ ReplyToConversationBranchReplied,
937
+ ReplyToConversationBranchUncertain,
938
+ ReplyToConversationDefinition,
939
+ ReplyToConversationInputSchema,
940
+ ReplyToConversationMetadata,
941
+ ReplyToConversationOperation,
942
+ SearchConversationsBranch,
943
+ SearchConversationsBranchDefect,
944
+ SearchConversationsBranchInvalidResponse,
945
+ SearchConversationsBranchProviderRejected,
946
+ SearchConversationsBranchSearched,
947
+ SearchConversationsDefinition,
948
+ SearchConversationsInputSchema,
949
+ SearchConversationsMetadata,
950
+ SearchConversationsOperation,
951
+ SearchConversationsOutputSchema,
952
+ TagSchema,
953
+ TeammateSchema,
954
+ UpdateConversationBranch,
955
+ UpdateConversationBranchDefect,
956
+ UpdateConversationBranchInvalidResponse,
957
+ UpdateConversationBranchNotFound,
958
+ UpdateConversationBranchProviderRejected,
959
+ UpdateConversationBranchUpdated,
960
+ UpdateConversationDefinition,
961
+ UpdateConversationInputSchema,
962
+ UpdateConversationMetadata,
963
+ UpdateConversationOperation,
964
+ UpdateConversationOutputSchema,
965
+ buildConversationSearchQuery,
966
+ buildReplyHTML,
967
+ newConnection,
968
+ newConnectionWithOperations,
969
+ newFindContactByEmailStep,
970
+ newGetConversationStep,
971
+ newProjectConnection2 as newProjectConnection,
972
+ newReplyToConversationStep,
973
+ newSearchConversationsStep,
974
+ newUpdateConversationStep
975
+ };