@superdurable/connector-freshdesk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1279 @@
1
+ import {
2
+ AddNoteBranch,
3
+ AddNoteBranchAdded,
4
+ AddNoteBranchDefect,
5
+ AddNoteBranchNotFound,
6
+ AddNoteBranchProviderRejected,
7
+ AddNoteBranchUncertain,
8
+ AddNoteDefinition,
9
+ AddNoteInputSchema,
10
+ AddNoteMetadata,
11
+ AddNoteOutputSchema,
12
+ ConfigSchema,
13
+ Connection,
14
+ ConnectorID,
15
+ CreateTicketBranch,
16
+ CreateTicketBranchCreated,
17
+ CreateTicketBranchDefect,
18
+ CreateTicketBranchProviderRejected,
19
+ CreateTicketBranchUncertain,
20
+ CreateTicketDefinition,
21
+ CreateTicketInputSchema,
22
+ CreateTicketMetadata,
23
+ CreateTicketOutputSchema,
24
+ GetTicketBranch,
25
+ GetTicketBranchDefect,
26
+ GetTicketBranchFound,
27
+ GetTicketBranchInvalidResponse,
28
+ GetTicketBranchNotFound,
29
+ GetTicketBranchProviderRejected,
30
+ GetTicketDefinition,
31
+ GetTicketInputSchema,
32
+ GetTicketMetadata,
33
+ ProviderID,
34
+ SearchTicketsBranch,
35
+ SearchTicketsBranchDefect,
36
+ SearchTicketsBranchInvalidResponse,
37
+ SearchTicketsBranchProviderRejected,
38
+ SearchTicketsBranchSearched,
39
+ SearchTicketsDefinition,
40
+ SearchTicketsInputSchema,
41
+ SearchTicketsMetadata,
42
+ SearchTicketsOutputSchema,
43
+ TicketConversationSchema,
44
+ TicketDetailsSchema,
45
+ TicketRequesterInputSchema,
46
+ TicketRequesterSchema,
47
+ TicketSchema,
48
+ UpdateTicketBranch,
49
+ UpdateTicketBranchDefect,
50
+ UpdateTicketBranchInvalidResponse,
51
+ UpdateTicketBranchNotFound,
52
+ UpdateTicketBranchProviderRejected,
53
+ UpdateTicketBranchUpdated,
54
+ UpdateTicketDefinition,
55
+ UpdateTicketInputSchema,
56
+ UpdateTicketMetadata,
57
+ UpdateTicketOutputSchema,
58
+ decodeCredentials,
59
+ newConnection,
60
+ newConnectionWithOperations,
61
+ newProjectConnection
62
+ } from "./chunk-SSAMOXWJ.js";
63
+
64
+ // src/generated/steps.ts
65
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
66
+ function newSearchTicketsStep(configuration) {
67
+ const { connection, connectionName, searched, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
68
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
69
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.searchTickets(), connection: connection.reference, branches: [
70
+ goToBranch("searched", searched),
71
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
72
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
73
+ ...defect ? [goToBranch("defect", defect)] : []
74
+ ] });
75
+ }
76
+ function newGetTicketStep(configuration) {
77
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
78
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
79
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getTicket(), connection: connection.reference, branches: [
80
+ goToBranch("found", found),
81
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
82
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
83
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
84
+ ...defect ? [goToBranch("defect", defect)] : []
85
+ ] });
86
+ }
87
+ function newCreateTicketStep(configuration) {
88
+ const { connection, connectionName, created, providerRejected, uncertain, defect, ...stepConfiguration } = configuration;
89
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
90
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.createTicket(), connection: connection.reference, branches: [
91
+ goToBranch("created", created),
92
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
93
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : [],
94
+ ...defect ? [goToBranch("defect", defect)] : []
95
+ ] });
96
+ }
97
+ function newUpdateTicketStep(configuration) {
98
+ const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
99
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
100
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateTicket(), connection: connection.reference, branches: [
101
+ goToBranch("updated", updated),
102
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
103
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
104
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
105
+ ...defect ? [goToBranch("defect", defect)] : []
106
+ ] });
107
+ }
108
+ function newAddNoteStep(configuration) {
109
+ const { connection, connectionName, added, notFound, providerRejected, uncertain, defect, ...stepConfiguration } = configuration;
110
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
111
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.addNote(), connection: connection.reference, branches: [
112
+ goToBranch("added", added),
113
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
114
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
115
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : [],
116
+ ...defect ? [goToBranch("defect", defect)] : []
117
+ ] });
118
+ }
119
+
120
+ // src/project.ts
121
+ import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
122
+
123
+ // src/client.ts
124
+ import { SecretString, ReauthorizationRequiredError, defaultTriggerLogger } from "@superdurable/connectors-sdk";
125
+ import { AddressRefusal, BodyTooLargeError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, readErrorTokens, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
126
+ import { ConnectionNotSelectedError, CredentialBrokerRejectedError, ObjectNotFoundError } from "@superdurable/connectors-sdk/projectconfig";
127
+
128
+ // src/operations.ts
129
+ import { newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
130
+ var zeroTicket = { id: 0, status: 0, priority: 0, createdAt: "0001-01-01T00:00:00Z", updatedAt: "0001-01-01T00:00:00Z" };
131
+ var zeroDetails = { ticket: zeroTicket, conversations: [] };
132
+ var zeroConversation = { id: 0, source: 0, isPrivate: false, body: "", createdAt: "0001-01-01T00:00:00Z" };
133
+ var tagPattern = /^[A-Za-z0-9](?:[A-Za-z0-9 _./+-]{0,62}[A-Za-z0-9_./+-])?$/;
134
+ var positive = (value) => Number.isSafeInteger(value) && value > 0;
135
+ var nonnegative = (value) => Number.isSafeInteger(value) && value >= 0;
136
+ function validateTags(tags) {
137
+ const seen = /* @__PURE__ */ new Set();
138
+ for (const tag of tags) {
139
+ if (!tagPattern.test(tag) || Buffer.byteLength(tag) > 64 || seen.has(tag.toLowerCase())) throw new TypeError("Freshdesk tag is invalid or duplicated");
140
+ seen.add(tag.toLowerCase());
141
+ }
142
+ }
143
+ function validateStatus(value) {
144
+ if (!Number.isSafeInteger(value) || value < 2) throw new TypeError("Freshdesk status is invalid");
145
+ }
146
+ function validatePriority(value) {
147
+ if (!Number.isSafeInteger(value) || value < 1 || value > 4) throw new TypeError("Freshdesk priority is invalid");
148
+ }
149
+ function validateText(value) {
150
+ if (!value?.trim()) throw new TypeError("Freshdesk text is required");
151
+ }
152
+ function validateEmail(value) {
153
+ if (!/^[A-Za-z0-9.!#$%&*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/.test(value) || value.includes("..") || value.startsWith(".") || value.slice(0, value.indexOf("@")).endsWith(".") || /["'()<>,;\s]/.test(value)) throw new TypeError("Freshdesk requester email is invalid");
154
+ }
155
+ function encodeHTML(text2) {
156
+ return text2.replaceAll("\r\n", "\n").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&#34;").replaceAll("'", "&#39;").replaceAll("\n", "<br>");
157
+ }
158
+ function object(value) {
159
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Freshdesk response is not an object");
160
+ return value;
161
+ }
162
+ function parse(body) {
163
+ return JSON.parse(Buffer.from(body).toString("utf8"));
164
+ }
165
+ function number(value) {
166
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TypeError("Freshdesk numeric field is invalid");
167
+ return value;
168
+ }
169
+ function text(value) {
170
+ if (typeof value !== "string") throw new TypeError("Freshdesk text field is invalid");
171
+ return value;
172
+ }
173
+ function wireNumber(value) {
174
+ return value == null ? 0 : number(value);
175
+ }
176
+ function wireText(value) {
177
+ return value == null ? "" : text(value);
178
+ }
179
+ function wireBoolean(value) {
180
+ if (value == null) return false;
181
+ if (typeof value !== "boolean") throw new TypeError("Freshdesk boolean field is invalid");
182
+ return value;
183
+ }
184
+ function optionalField(value, name) {
185
+ return value ? { [name]: value } : {};
186
+ }
187
+ function timestamp(value) {
188
+ const raw = text(value);
189
+ const date = new Date(raw);
190
+ if (!Number.isFinite(date.getTime()) || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(raw)) throw new TypeError("Freshdesk timestamp is invalid");
191
+ return date.toISOString().replace(".000Z", "Z");
192
+ }
193
+ function truncated(value) {
194
+ const bytes = Buffer.from(value);
195
+ if (bytes.length <= 16384) return { text: value, isTruncated: false };
196
+ let end = 16384;
197
+ while (end > 0 && (bytes[end] & 192) === 128) end--;
198
+ return { text: bytes.subarray(0, end).toString("utf8"), isTruncated: true };
199
+ }
200
+ function decodeTicketWire(value, expectedID = 0) {
201
+ return ticket(value, expectedID);
202
+ }
203
+ function ticket(value, expectedID = 0) {
204
+ const wire = object(value);
205
+ const id = number(wire.id);
206
+ const status = number(wire.status);
207
+ if (!positive(id) || status < 1 || expectedID && id !== expectedID) throw new TypeError("Freshdesk ticket ID or status is invalid");
208
+ const description = truncated(wireText(wire.description_text));
209
+ const tags = wire.tags === void 0 || wire.tags === null ? void 0 : wire.tags;
210
+ if (tags !== void 0 && (!Array.isArray(tags) || tags.some((item) => typeof item !== "string"))) throw new TypeError("Freshdesk ticket tags are invalid");
211
+ const result = {
212
+ id,
213
+ status,
214
+ priority: wireNumber(wire.priority),
215
+ createdAt: timestamp(wire.created_at),
216
+ updatedAt: timestamp(wire.updated_at),
217
+ ...optionalField(wireText(wire.subject), "subject"),
218
+ ...optionalField(description.text, "description"),
219
+ ...description.isTruncated ? { isDescriptionTruncated: true } : {},
220
+ ...optionalField(wireNumber(wire.source), "source"),
221
+ ...optionalField(wireText(wire.type), "type"),
222
+ ...optionalField(wireNumber(wire.requester_id), "requesterId"),
223
+ ...optionalField(wireNumber(wire.responder_id), "responderId"),
224
+ ...optionalField(wireNumber(wire.group_id), "groupId"),
225
+ ...optionalField(wireNumber(wire.company_id), "companyId"),
226
+ ...optionalField(wireNumber(wire.product_id), "productId"),
227
+ ...tags?.length ? { tags } : {},
228
+ ...wireBoolean(wire.is_escalated) ? { isEscalated: true } : {},
229
+ ...wireBoolean(wire.spam) ? { isSpam: true } : {}
230
+ };
231
+ if (wire.due_by) result.dueBy = timestamp(wire.due_by);
232
+ if (wire.fr_due_by) result.firstResponseDueBy = timestamp(wire.fr_due_by);
233
+ return result;
234
+ }
235
+ function conversation(value) {
236
+ const wire = object(value);
237
+ const id = number(wire.id);
238
+ if (!positive(id)) throw new TypeError("Freshdesk conversation ID is invalid");
239
+ const body = truncated(wireText(wire.body_text));
240
+ return {
241
+ id,
242
+ source: wireNumber(wire.source),
243
+ isPrivate: wireBoolean(wire.private),
244
+ body: body.text,
245
+ createdAt: timestamp(wire.created_at),
246
+ ...optionalField(wireNumber(wire.ticket_id), "ticketId"),
247
+ ...optionalField(wireNumber(wire.user_id), "userId"),
248
+ ...wireBoolean(wire.incoming) ? { isIncoming: true } : {},
249
+ ...body.isTruncated ? { isBodyTruncated: true } : {}
250
+ };
251
+ }
252
+ function queryFailure(client, call, operation, branch, value, kind, message, response, objectID = 0) {
253
+ return newQueryBranch(branch, value, client.receipt(call, response, objectID), client.failure(operation, kind, message));
254
+ }
255
+ function mutationFailure(client, call, operation, branch, value, kind, message, response, objectID = 0) {
256
+ return newMutationBranch(branch, value, client.receipt(call, response, objectID), client.failure(operation, kind, message));
257
+ }
258
+ function queryExchange(client, call, exchange, zero, notFoundBranch, objectID = 0) {
259
+ if (exchange.outcome === "succeeded") return void 0;
260
+ if (["rateLimited", "notSent", "serviceUnavailable", "unavailable"].includes(exchange.outcome)) return newQueryRetry(exchange.failure, exchange.retryAfterMs);
261
+ const branch = exchange.outcome === "notFound" ? notFoundBranch : exchange.outcome === "invalid" ? "invalidResponse" : exchange.outcome === "defect" ? "defect" : "providerRejected";
262
+ return newQueryBranch(branch, zero, client.receipt(call, exchange.response, objectID), exchange.failure);
263
+ }
264
+ function updateExchange(client, call, exchange, value, objectID) {
265
+ if (exchange.outcome === "succeeded") return void 0;
266
+ if (["rateLimited", "notSent", "serviceUnavailable", "unavailable"].includes(exchange.outcome)) return newMutationRetry(exchange.failure, exchange.retryAfterMs);
267
+ const branch = exchange.outcome === "notFound" ? "notFound" : exchange.outcome === "invalid" ? "invalidResponse" : exchange.outcome === "defect" ? "defect" : "providerRejected";
268
+ return newMutationBranch(branch, value, client.receipt(call, exchange.response, objectID), exchange.failure);
269
+ }
270
+ async function credential(client, call, operation) {
271
+ return client.resolveCredential(call, operation);
272
+ }
273
+ var SearchTicketsOperation = class {
274
+ /** Bind the API client. */
275
+ constructor(client) {
276
+ this.client = client;
277
+ }
278
+ client;
279
+ /** Return stable manifest metadata. */
280
+ definition() {
281
+ return SearchTicketsDefinition;
282
+ }
283
+ /** Validate filters, then perform at most two reads. */
284
+ async invoke(call, input) {
285
+ const operation = "searchTickets";
286
+ const zero = { tickets: [], totalMatched: 0 };
287
+ let filter;
288
+ try {
289
+ filter = buildFilter(input);
290
+ if (!nonnegative(input.page ?? 0) || (input.page ?? 0) > 10) throw new TypeError("page is invalid");
291
+ if (input.requesterEmail) validateEmail(input.requesterEmail);
292
+ } catch (error) {
293
+ return queryFailure(this.client, call, operation, "defect", zero, "VALIDATION", String(error));
294
+ }
295
+ const resolved = await credential(this.client, call, operation);
296
+ if ("failure" in resolved) return resolved.transient ? newQueryRetry(resolved.failure) : newQueryBranch("defect", zero, {}, resolved.failure);
297
+ let requesterIDs;
298
+ if (input.requesterEmail) {
299
+ const contact = await this.client.exchange(call, operation, resolved.key, "GET", "/contacts", new URLSearchParams({ email: input.requesterEmail }));
300
+ const terminal2 = queryExchange(this.client, call, contact, zero, "providerRejected");
301
+ if (terminal2) return terminal2;
302
+ try {
303
+ const rows = parse(contact.response.body);
304
+ if (!Array.isArray(rows)) throw new TypeError("contact list is not an array");
305
+ requesterIDs = /* @__PURE__ */ new Set();
306
+ for (const row of rows) {
307
+ const record = object(row);
308
+ const id = number(record.id);
309
+ if (!positive(id)) throw new TypeError("contact has no ID");
310
+ if (wireText(record.email).toLowerCase() === input.requesterEmail.toLowerCase()) requesterIDs.add(id);
311
+ }
312
+ } catch {
313
+ return queryFailure(this.client, call, operation, "invalidResponse", zero, "PROTOCOL", "Freshdesk returned an invalid contact list", contact.response);
314
+ }
315
+ if (requesterIDs.size === 0) return newQueryBranch("searched", { tickets: [], totalMatched: 0 }, this.client.receipt(call, contact.response));
316
+ }
317
+ const page = input.page || 1;
318
+ const response = await this.client.exchange(call, operation, resolved.key, "GET", "/search/tickets", new URLSearchParams({ query: `"${filter}"`, page: String(page) }));
319
+ const terminal = queryExchange(this.client, call, response, zero, "providerRejected");
320
+ if (terminal) return terminal;
321
+ try {
322
+ const wire = object(parse(response.response.body));
323
+ const total = number(wire.total);
324
+ if (total < 0 || !Array.isArray(wire.results) || wire.results.length > 30) throw new TypeError("invalid search page");
325
+ const tickets = wire.results.map((item) => ticket(item)).filter((item) => !requesterIDs || requesterIDs.has(item.requesterId ?? 0)).map((item) => {
326
+ delete item.description;
327
+ delete item.isDescriptionTruncated;
328
+ return item;
329
+ });
330
+ return newQueryBranch("searched", { tickets, totalMatched: total, ...page < 10 && page * 30 < total ? { nextPage: page + 1 } : {} }, this.client.receipt(call, response.response));
331
+ } catch {
332
+ return queryFailure(this.client, call, operation, "invalidResponse", zero, "PROTOCOL", "Freshdesk returned an invalid search page", response.response);
333
+ }
334
+ }
335
+ };
336
+ var GetTicketOperation = class {
337
+ /** Bind the API client. */
338
+ constructor(client) {
339
+ this.client = client;
340
+ }
341
+ client;
342
+ /** Return stable manifest metadata. */
343
+ definition() {
344
+ return GetTicketDefinition;
345
+ }
346
+ /** Perform the ticket and conversation reads. */
347
+ async invoke(call, input) {
348
+ const operation = "getTicket";
349
+ const zero = zeroDetails;
350
+ if (!positive(input.ticketId) || !nonnegative(input.conversationLimit ?? 0) || (input.conversationLimit ?? 0) > 20) return queryFailure(this.client, call, operation, "defect", zero, "VALIDATION", "ticketId or conversationLimit is invalid");
351
+ const resolved = await credential(this.client, call, operation);
352
+ if ("failure" in resolved) return resolved.transient ? newQueryRetry(resolved.failure) : newQueryBranch("defect", zero, {}, resolved.failure);
353
+ const path = `/tickets/${input.ticketId}`;
354
+ const first = await this.client.exchange(call, operation, resolved.key, "GET", path, new URLSearchParams({ include: "requester" }));
355
+ const terminal = queryExchange(this.client, call, first, zero, "notFound", input.ticketId);
356
+ if (terminal) return terminal;
357
+ let details;
358
+ try {
359
+ const wire = object(parse(first.response.body));
360
+ details = { ticket: ticket(wire, input.ticketId), conversations: [] };
361
+ if (wire.requester) {
362
+ const requester = object(wire.requester);
363
+ const id = number(requester.id);
364
+ if (positive(id)) {
365
+ if (id !== details.ticket.requesterId) throw new TypeError("requester mismatch");
366
+ details.requester = { id, ...optionalField(wireText(requester.name), "name"), ...optionalField(wireText(requester.email), "email") };
367
+ }
368
+ }
369
+ } catch {
370
+ return queryFailure(this.client, call, operation, "invalidResponse", zero, "PROTOCOL", "Freshdesk returned an invalid ticket", first.response, input.ticketId);
371
+ }
372
+ const limit = input.conversationLimit || 10;
373
+ const second = await this.client.exchange(call, operation, resolved.key, "GET", `${path}/conversations`, new URLSearchParams({ per_page: String(limit), page: "1" }));
374
+ const secondTerminal = queryExchange(this.client, call, second, zero, "notFound", input.ticketId);
375
+ if (secondTerminal) return secondTerminal;
376
+ try {
377
+ const rows = parse(second.response.body);
378
+ if (!Array.isArray(rows) || rows.length > limit) throw new TypeError("invalid conversation page");
379
+ details.conversations = rows.map((item) => conversation(item)).sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id - right.id);
380
+ if (String(second.response.headers.link ?? "").includes('rel="next"')) details.hasMoreConversations = true;
381
+ return newQueryBranch("found", details, this.client.receipt(call, second.response, input.ticketId));
382
+ } catch {
383
+ return queryFailure(this.client, call, operation, "invalidResponse", zero, "PROTOCOL", "Freshdesk returned an invalid conversation page", second.response, input.ticketId);
384
+ }
385
+ }
386
+ };
387
+ function buildFilter(input) {
388
+ const clauses = [];
389
+ const any = (values) => {
390
+ if (values.length) clauses.push(values.length === 1 ? values[0] : `(${values.join(" OR ")})`);
391
+ };
392
+ const statuses = input.statuses ?? [];
393
+ statuses.forEach(validateStatus);
394
+ if (new Set(statuses).size !== statuses.length) throw new TypeError("duplicate statuses");
395
+ any(statuses.map((value) => `status:${value}`));
396
+ const priorities = input.priorities ?? [];
397
+ priorities.forEach(validatePriority);
398
+ if (new Set(priorities).size !== priorities.length) throw new TypeError("duplicate priorities");
399
+ any(priorities.map((value) => `priority:${value}`));
400
+ validateTags(input.tags ?? []);
401
+ any((input.tags ?? []).map((value) => `tag:'${value}'`));
402
+ if (input.updatedSinceDate) {
403
+ const date = /* @__PURE__ */ new Date(`${input.updatedSinceDate}T00:00:00Z`);
404
+ if (!/^\d{4}-\d\d-\d\d$/.test(input.updatedSinceDate) || !Number.isFinite(date.getTime()) || date.toISOString().slice(0, 10) !== input.updatedSinceDate) throw new TypeError("updatedSinceDate is invalid");
405
+ clauses.push(`updated_at:>'${input.updatedSinceDate}'`);
406
+ }
407
+ if (!clauses.length) throw new TypeError("at least one Freshdesk filter is required");
408
+ const query = clauses.join(" AND ");
409
+ if (Buffer.byteLength(query) + 2 > 512) throw new TypeError("Freshdesk filter is too long");
410
+ return query;
411
+ }
412
+ async function inspectDispatch(call) {
413
+ try {
414
+ if (!call.context.hasLastHeartbeatValue()) return call.context.attempt === 1 ? "allowed" : "uncertain";
415
+ const marker = call.context.getLastHeartbeatValue();
416
+ return marker?.freshdeskDispatchedCallId === call.id && marker.freshdeskRetryAttempt === call.context.attempt ? "allowed" : "uncertain";
417
+ } catch {
418
+ return "uncertain";
419
+ }
420
+ }
421
+ async function recordDispatch(call) {
422
+ try {
423
+ await call.context.recordHeartbeat({ freshdeskDispatchedCallId: call.id, freshdeskDispatchedAttempt: call.context.attempt });
424
+ return true;
425
+ } catch {
426
+ await permitRetry(call);
427
+ return false;
428
+ }
429
+ }
430
+ async function permitRetry(call) {
431
+ try {
432
+ await call.context.recordHeartbeat({ freshdeskDispatchedCallId: call.id, freshdeskRetryAttempt: call.context.attempt + 1 });
433
+ } catch {
434
+ }
435
+ }
436
+ async function singleDispatchExchange(client, call, exchange, zero, notFoundBranch = "providerRejected") {
437
+ if (exchange.outcome === "succeeded") return void 0;
438
+ if (["rateLimited", "notSent", "serviceUnavailable"].includes(exchange.outcome)) {
439
+ await permitRetry(call);
440
+ return newMutationRetry(exchange.failure, exchange.retryAfterMs);
441
+ }
442
+ if (exchange.outcome === "unavailable" || exchange.outcome === "invalid") return newMutationUncertain(zero, exchange.failure, client.receipt(call, exchange.response));
443
+ const branch = exchange.outcome === "notFound" ? notFoundBranch : exchange.outcome === "defect" ? "defect" : "providerRejected";
444
+ return newMutationBranch(branch, zero, client.receipt(call, exchange.response), exchange.failure);
445
+ }
446
+ async function beforeSingleDispatch(client, call, operation, zero) {
447
+ if (await inspectDispatch(call) === "uncertain") return newMutationUncertain(zero, client.failure(operation, "TRANSPORT", "an earlier attempt of this Step may have sent the request, so it is not sent again"), client.receipt(call));
448
+ return void 0;
449
+ }
450
+ var CreateTicketOperation = class {
451
+ /** Bind the API client. */
452
+ constructor(client) {
453
+ this.client = client;
454
+ }
455
+ client;
456
+ /** Return stable manifest metadata. */
457
+ definition() {
458
+ return CreateTicketDefinition;
459
+ }
460
+ /** Correlate the mutation by Call ID; Freshdesk does not receive this key. */
461
+ idempotencyKey(callID) {
462
+ return callID;
463
+ }
464
+ /** Validate, checkpoint, and send at most once per safe attempt. */
465
+ async invoke(call, input) {
466
+ const operation = "createTicket";
467
+ const zero = { ticket: zeroTicket };
468
+ try {
469
+ validateText(input.subject);
470
+ validateText(input.description);
471
+ validateEmail(input.requester.email);
472
+ if (input.requester.name && input.requester.name !== input.requester.name.trim()) throw new TypeError("requester name has surrounding spaces");
473
+ if (input.status) validateStatus(input.status);
474
+ if (input.priority) validatePriority(input.priority);
475
+ if (input.type && (input.type !== input.type.trim() || Buffer.byteLength(input.type) > 255)) throw new TypeError("ticket type is invalid");
476
+ validateTags(input.tags ?? []);
477
+ if (!nonnegative(input.groupId ?? 0) || !nonnegative(input.responderId ?? 0)) throw new TypeError("assignment ID is invalid");
478
+ } catch {
479
+ return mutationFailure(this.client, call, operation, "defect", zero, "VALIDATION", "Freshdesk create input is invalid");
480
+ }
481
+ const prior = await beforeSingleDispatch(this.client, call, operation, zero);
482
+ if (prior) return prior;
483
+ const resolved = await credential(this.client, call, operation);
484
+ if ("failure" in resolved) {
485
+ if (resolved.transient || call.context.attempt > 1) {
486
+ await permitRetry(call);
487
+ return newMutationRetry(resolved.failure);
488
+ }
489
+ return newMutationBranch("defect", zero, {}, resolved.failure);
490
+ }
491
+ if (!await recordDispatch(call)) return newMutationRetry(this.client.failure(operation, "AVAILABILITY", "Dex did not record the dispatch checkpoint; nothing was sent"));
492
+ const request = {
493
+ subject: input.subject,
494
+ description: encodeHTML(input.description),
495
+ email: input.requester.email,
496
+ ...input.requester.name ? { name: input.requester.name } : {},
497
+ ...input.status ? { status: input.status } : {},
498
+ ...input.priority ? { priority: input.priority } : {},
499
+ ...input.type ? { type: input.type } : {},
500
+ ...input.tags?.length ? { tags: input.tags } : {},
501
+ ...input.groupId ? { group_id: input.groupId } : {},
502
+ ...input.responderId ? { responder_id: input.responderId } : {}
503
+ };
504
+ const exchange = await this.client.exchange(call, operation, resolved.key, "POST", "/tickets", void 0, request);
505
+ const terminal = await singleDispatchExchange(this.client, call, exchange, zero);
506
+ if (terminal) return terminal;
507
+ try {
508
+ const created = ticket(parse(exchange.response.body));
509
+ return newMutationBranch("created", { ticket: created }, this.client.receipt(call, exchange.response, created.id));
510
+ } catch {
511
+ return newMutationUncertain(zero, this.client.failure(operation, "PROTOCOL", "Freshdesk accepted the ticket but returned an invalid ticket"), this.client.receipt(call, exchange.response));
512
+ }
513
+ }
514
+ };
515
+ var UpdateTicketOperation = class {
516
+ /** Bind the API client. */
517
+ constructor(client) {
518
+ this.client = client;
519
+ }
520
+ client;
521
+ /** Return stable manifest metadata. */
522
+ definition() {
523
+ return UpdateTicketDefinition;
524
+ }
525
+ /** Correlate the absolute replacement by Call ID. */
526
+ idempotencyKey(callID) {
527
+ return callID;
528
+ }
529
+ /** Read, diff, and write only when a field differs. */
530
+ async invoke(call, input) {
531
+ const operation = "updateTicket";
532
+ const zero = { ticket: zeroTicket };
533
+ try {
534
+ if (!positive(input.ticketId)) throw new TypeError("ticket ID is invalid");
535
+ if (input.status) validateStatus(input.status);
536
+ if (input.priority) validatePriority(input.priority);
537
+ if (!nonnegative(input.groupId ?? 0) || !nonnegative(input.responderId ?? 0)) throw new TypeError("assignment ID is invalid");
538
+ validateTags(input.addTags ?? []);
539
+ validateTags(input.removeTags ?? []);
540
+ if ((input.addTags ?? []).some((tag) => (input.removeTags ?? []).some((other) => other.toLowerCase() === tag.toLowerCase()))) throw new TypeError("tag appears in both changes");
541
+ if (!input.status && !input.priority && !input.groupId && !input.responderId && !input.addTags?.length && !input.removeTags?.length) throw new TypeError("no ticket change");
542
+ } catch {
543
+ return mutationFailure(this.client, call, operation, "defect", zero, "VALIDATION", "Freshdesk update input is invalid");
544
+ }
545
+ const resolved = await credential(this.client, call, operation);
546
+ if ("failure" in resolved) return resolved.transient ? newMutationRetry(resolved.failure) : newMutationBranch("defect", zero, {}, resolved.failure);
547
+ const path = `/tickets/${input.ticketId}`;
548
+ const read = await this.client.exchange(call, operation, resolved.key, "GET", path);
549
+ const readTerminal = updateExchange(this.client, call, read, zero, input.ticketId);
550
+ if (readTerminal) return readTerminal;
551
+ let current;
552
+ try {
553
+ current = ticket(parse(read.response.body), input.ticketId);
554
+ } catch {
555
+ return mutationFailure(this.client, call, operation, "invalidResponse", zero, "PROTOCOL", "Freshdesk returned an invalid ticket", read.response, input.ticketId);
556
+ }
557
+ const change = {};
558
+ if (input.status && input.status !== current.status) change.status = input.status;
559
+ if (input.priority && input.priority !== current.priority) change.priority = input.priority;
560
+ if (input.groupId && input.groupId !== current.groupId) change.group_id = input.groupId;
561
+ if (input.responderId && input.responderId !== current.responderId) change.responder_id = input.responderId;
562
+ const tags = (current.tags ?? []).filter((tag) => !(input.removeTags ?? []).some((other) => other.toLowerCase() === tag.toLowerCase()));
563
+ for (const tag of input.addTags ?? []) if (!tags.some((existing) => existing.toLowerCase() === tag.toLowerCase())) tags.push(tag);
564
+ if (JSON.stringify(tags) !== JSON.stringify(current.tags ?? [])) change.tags = tags;
565
+ if (!Object.keys(change).length) return newMutationBranch("updated", { ticket: current, wasAlreadyApplied: true }, this.client.receipt(call, read.response, input.ticketId));
566
+ const write = await this.client.exchange(call, operation, resolved.key, "PUT", path, void 0, change);
567
+ const writeTerminal = updateExchange(this.client, call, write, { ticket: current }, input.ticketId);
568
+ if (writeTerminal) return writeTerminal;
569
+ try {
570
+ return newMutationBranch("updated", { ticket: ticket(parse(write.response.body), input.ticketId) }, this.client.receipt(call, write.response, input.ticketId));
571
+ } catch {
572
+ return mutationFailure(this.client, call, operation, "invalidResponse", { ticket: current }, "PROTOCOL", "Freshdesk returned an invalid updated ticket", write.response, input.ticketId);
573
+ }
574
+ }
575
+ };
576
+ var AddNoteOperation = class {
577
+ /** Bind the API client. */
578
+ constructor(client) {
579
+ this.client = client;
580
+ }
581
+ client;
582
+ /** Return stable manifest metadata. */
583
+ definition() {
584
+ return AddNoteDefinition;
585
+ }
586
+ /** Correlate the mutation by Call ID; Freshdesk does not receive this key. */
587
+ idempotencyKey(callID) {
588
+ return callID;
589
+ }
590
+ /** Validate, checkpoint, and send one note or reply. */
591
+ async invoke(call, input) {
592
+ const operation = "addNote";
593
+ const zero = { conversation: zeroConversation };
594
+ if (!positive(input.ticketId) || !input.body?.trim()) return mutationFailure(this.client, call, operation, "defect", zero, "VALIDATION", "Freshdesk note input is invalid");
595
+ const prior = await beforeSingleDispatch(this.client, call, operation, zero);
596
+ if (prior) return prior;
597
+ const resolved = await credential(this.client, call, operation);
598
+ if ("failure" in resolved) {
599
+ if (resolved.transient || call.context.attempt > 1) {
600
+ await permitRetry(call);
601
+ return newMutationRetry(resolved.failure);
602
+ }
603
+ return newMutationBranch("defect", zero, {}, resolved.failure);
604
+ }
605
+ if (!await recordDispatch(call)) return newMutationRetry(this.client.failure(operation, "AVAILABILITY", "Dex did not record the dispatch checkpoint; nothing was sent"));
606
+ const path = `/tickets/${input.ticketId}/${input.isPublicReply ? "reply" : "notes"}`;
607
+ const payload = input.isPublicReply ? { body: encodeHTML(input.body) } : { body: encodeHTML(input.body), private: true };
608
+ const exchange = await this.client.exchange(call, operation, resolved.key, "POST", path, void 0, payload);
609
+ const terminal = await singleDispatchExchange(this.client, call, exchange, zero, "notFound");
610
+ if (terminal) return terminal;
611
+ try {
612
+ const wire = object(parse(exchange.response.body));
613
+ const added = conversation(wire);
614
+ if (added.ticketId && added.ticketId !== input.ticketId) throw new TypeError("conversation belongs to another ticket");
615
+ added.ticketId = input.ticketId;
616
+ added.source = input.isPublicReply ? 0 : 2;
617
+ added.isPrivate = input.isPublicReply ? false : wire.private !== false;
618
+ return newMutationBranch("added", { conversation: added }, this.client.receipt(call, exchange.response, added.id));
619
+ } catch {
620
+ return newMutationUncertain(zero, this.client.failure(operation, "PROTOCOL", "Freshdesk accepted the note but returned an invalid conversation"), this.client.receipt(call, exchange.response));
621
+ }
622
+ }
623
+ };
624
+
625
+ // src/client.ts
626
+ var domainPattern = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
627
+ var requestIDPattern = /^[A-Za-z0-9._:-]{1,128}$/;
628
+ var errorFieldPattern = /^[a-z][a-z0-9_]{0,63}$/;
629
+ var minimumPollIntervalMs = 1e4;
630
+ var FreshdeskClient = class {
631
+ /** Bind immutable configuration and a live credential source. */
632
+ constructor(config, credentials, options = {}) {
633
+ this.credentials = credentials;
634
+ if (!domainPattern.test(config.domain)) throw new TypeError("Freshdesk domain is invalid");
635
+ if (!credentials) throw new TypeError("Freshdesk credential provider is required");
636
+ this.maxResponseBytes = config.maxResponseBytes ?? 4194304;
637
+ if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes < 1) throw new TypeError("Freshdesk response limit must be positive");
638
+ this.pollIntervalMs = config.pollIntervalMs ?? 6e4;
639
+ if (!Number.isSafeInteger(this.pollIntervalMs) || this.pollIntervalMs < minimumPollIntervalMs) throw new TypeError("Freshdesk pollInterval must be at least 10s");
640
+ this.triggerLogger = options.logger ?? defaultTriggerLogger;
641
+ this.apiBaseURL = validateBaseURL(options.apiBaseURL ?? `https://${config.domain}.freshdesk.com/api/v2`);
642
+ this.send = options.send ?? sendProviderRequest;
643
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
644
+ }
645
+ credentials;
646
+ apiBaseURL;
647
+ maxResponseBytes;
648
+ send;
649
+ now;
650
+ /** Delay between ticketChanged polls in milliseconds, at least 10 seconds; one minute by default. */
651
+ pollIntervalMs;
652
+ /** Receives the ticketChanged runner's and durable inboxes' records. */
653
+ triggerLogger;
654
+ /** Bind the search query. */
655
+ searchTickets() {
656
+ return new SearchTicketsOperation(this);
657
+ }
658
+ /** Bind the ticket read query. */
659
+ getTicket() {
660
+ return new GetTicketOperation(this);
661
+ }
662
+ /** Bind the ticket creation mutation. */
663
+ createTicket() {
664
+ return new CreateTicketOperation(this);
665
+ }
666
+ /** Bind the ticket update mutation. */
667
+ updateTicket() {
668
+ return new UpdateTicketOperation(this);
669
+ }
670
+ /** Bind the note mutation. */
671
+ addNote() {
672
+ return new AddNoteOperation(this);
673
+ }
674
+ /** Return the current time of the injected clock. */
675
+ currentTime() {
676
+ return this.now();
677
+ }
678
+ /** Resolve the current API key, classifying terminal credential states. */
679
+ async resolveCredential(call, operation) {
680
+ let credential2;
681
+ try {
682
+ credential2 = await this.credentials.resolve(call, call.context.cancellationSignal);
683
+ } catch (error) {
684
+ const terminal = error instanceof ObjectNotFoundError || error instanceof ReauthorizationRequiredError || error instanceof ConnectionNotSelectedError || error instanceof CredentialBrokerRejectedError;
685
+ return { failure: this.failure(operation, terminal ? "AUTHENTICATION" : "AVAILABILITY", terminal ? "connection credentials are unavailable" : "connection credentials could not be read; no request was sent"), transient: !terminal };
686
+ }
687
+ if (!(credential2.apiKey instanceof SecretString) || !isHeaderSafeCredential(credential2.apiKey.reveal()) || credential2.apiKey.reveal().includes(":")) {
688
+ return { failure: this.failure(operation, "AUTHENTICATION", "connection credentials are unavailable"), transient: false };
689
+ }
690
+ return { key: credential2.apiKey.reveal() };
691
+ }
692
+ /** Send one bounded request and classify its observable outcome. */
693
+ async exchange(call, operation, key, method, path, query, payload, signal) {
694
+ const url = `${this.apiBaseURL}${path}${query ? `?${query.toString()}` : ""}`;
695
+ const headers = { Accept: "application/json", Authorization: `Basic ${Buffer.from(`${key}:X`).toString("base64")}` };
696
+ let body;
697
+ if (payload !== void 0) {
698
+ try {
699
+ body = Buffer.from(JSON.stringify(payload));
700
+ headers["Content-Type"] = "application/json";
701
+ } catch {
702
+ return { outcome: "defect", failure: this.failure(operation, "LOCAL_DEFECT", "Freshdesk request could not be built"), retryAfterMs: 0 };
703
+ }
704
+ }
705
+ try {
706
+ const response = await this.send({ url, method, headers, ...body ? { body } : {}, maxResponseBytes: this.maxResponseBytes, addressPolicy: this.apiBaseURL.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP", timeoutMs: 12e3, signal: signal ?? call.context.cancellationSignal });
707
+ if (response.status >= 200 && response.status < 300) {
708
+ if (Buffer.from(response.body).includes(Buffer.from(key))) return { outcome: "invalid", response, failure: this.failure(operation, "PROTOCOL", "Freshdesk response reflected the connection credential"), retryAfterMs: 0 };
709
+ return { outcome: "succeeded", response };
710
+ }
711
+ return this.classifyStatus(operation, key, response);
712
+ } catch (error) {
713
+ if (error instanceof BodyTooLargeError) {
714
+ if (error.status !== void 0 && (error.status < 200 || error.status >= 300)) {
715
+ return this.classifyStatus(operation, key, { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() });
716
+ }
717
+ return { outcome: "invalid", failure: this.failure(operation, "RESPONSE_TOO_LARGE", "Freshdesk response exceeds the configured maxResponseBytes limit"), retryAfterMs: 0 };
718
+ }
719
+ if (error instanceof AddressRefusal) return { outcome: "notSent", failure: this.failure(operation, "TRANSPORT", "Freshdesk could not be reached; no request was sent"), retryAfterMs: 0 };
720
+ if (error instanceof ProviderTransportError && error.isProvablyNotSent) return { outcome: "notSent", failure: this.failure(operation, "TRANSPORT", "Freshdesk could not be reached; no request was sent"), retryAfterMs: 0 };
721
+ return { outcome: "unavailable", failure: this.failure(operation, "TRANSPORT", "Freshdesk request failed before a response arrived"), retryAfterMs: 0 };
722
+ }
723
+ }
724
+ classifyStatus(operation, key, response) {
725
+ const status = response.status;
726
+ const retryAfterMs = parseRetryAfter(String(response.headers["retry-after"] ?? ""), this.now());
727
+ let outcome;
728
+ let kind;
729
+ let message;
730
+ if (status === 429) {
731
+ outcome = "rateLimited";
732
+ kind = "RATE_LIMIT";
733
+ message = "Freshdesk rate limited the request (HTTP 429)";
734
+ } else if (status === 503) {
735
+ outcome = "serviceUnavailable";
736
+ kind = "AVAILABILITY";
737
+ message = "Freshdesk is unavailable (HTTP 503)";
738
+ } else if (status === 408 || status >= 500) {
739
+ outcome = "unavailable";
740
+ kind = "AVAILABILITY";
741
+ message = `Freshdesk could not complete the request (HTTP ${status})`;
742
+ } else if (status === 404) {
743
+ outcome = "notFound";
744
+ kind = "NOT_FOUND";
745
+ message = "Freshdesk found no such resource (HTTP 404)";
746
+ } else if (status >= 300 && status < 400) {
747
+ outcome = "rejected";
748
+ kind = "PROTOCOL";
749
+ message = `Freshdesk redirected the request (HTTP ${status}); check that the domain is the freshdesk.com helpdesk domain`;
750
+ } else {
751
+ outcome = "rejected";
752
+ kind = status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : status === 409 ? "CONFLICT" : status === 400 ? "VALIDATION" : "PROVIDER_REJECTION";
753
+ message = `Freshdesk rejected the request (HTTP ${status})`;
754
+ }
755
+ if (status < 300 || status >= 400) message += safeErrorSummary(response.body, key);
756
+ return { outcome, response, failure: this.failure(operation, kind, message), retryAfterMs };
757
+ }
758
+ /** Build secret-free failure metadata. */
759
+ failure(operation, kind, message) {
760
+ return { kind, provider: "freshdesk", operation, message };
761
+ }
762
+ /** Build a stable receipt after provider observation. */
763
+ receipt(call, response, objectID = 0) {
764
+ const requestID = response?.headers["x-request-id"];
765
+ const safeID = typeof requestID === "string" && requestIDPattern.test(requestID) ? requestID : "";
766
+ return { callId: call.id, provider: "freshdesk", observedAt: this.now().toISOString(), ...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {}, ...safeID ? { providerRequestId: safeID } : {}, ...objectID > 0 ? { providerObjectId: String(objectID) } : {} };
767
+ }
768
+ };
769
+ function safeErrorSummary(body, secret) {
770
+ const code = readErrorTokens(body, ["/code"])[0];
771
+ let document;
772
+ try {
773
+ document = JSON.parse(Buffer.from(body).toString("utf8"));
774
+ } catch {
775
+ document = null;
776
+ }
777
+ const errors = document && typeof document === "object" && "errors" in document && Array.isArray(document.errors) ? document.errors : [];
778
+ const fields = [];
779
+ errors.forEach((_, index) => {
780
+ const field = readErrorTokens(body, [`/errors/${index}/field`])[0];
781
+ const fieldCode = readErrorTokens(body, [`/errors/${index}/code`])[0];
782
+ if (field && errorFieldPattern.test(field) && !field.includes(secret)) fields.push(field + (fieldCode && !fieldCode.includes(secret) ? `=${fieldCode}` : ""));
783
+ });
784
+ const details = [...code && !code.includes(secret) ? [code] : [], ...fields.length ? [`errors: ${fields.sort().slice(0, 5).join(", ")}`] : []];
785
+ return details.length ? ` [${details.join("; ")}]` : "";
786
+ }
787
+
788
+ // src/project.ts
789
+ function newProjectConnection2(project, connectionName, options = {}) {
790
+ return newProjectConnection(project, connectionName, (loaded, name) => {
791
+ const selected = loaded.configuration.connections.find((entry) => entry.connectorId === "freshdesk" && entry.connectionName === name);
792
+ if (!selected) throw new TypeError("Freshdesk project connection is not configured");
793
+ const raw = selected.configuration;
794
+ const pollIntervalMs = raw.pollInterval === void 0 || raw.pollInterval === null ? void 0 : durationMilliseconds(raw.pollInterval);
795
+ const parsed = ConfigSchema.parse({ ...raw, ...pollIntervalMs !== void 0 ? { pollIntervalMs } : {} });
796
+ const config = {
797
+ domain: parsed.domain,
798
+ ...parsed.maxResponseBytes !== void 0 ? { maxResponseBytes: parsed.maxResponseBytes } : {},
799
+ ...parsed.pollIntervalMs !== void 0 ? { pollIntervalMs: parsed.pollIntervalMs } : {}
800
+ };
801
+ const credentials = {
802
+ async resolve(call, signal) {
803
+ void call;
804
+ const fields = await loaded.resolveCredential("freshdesk", name, signal);
805
+ const apiKey = fields.api_key;
806
+ if (typeof apiKey !== "string" || !apiKey) throw new TypeError("Freshdesk API key is unavailable");
807
+ return { apiKey: new SecretString2(apiKey) };
808
+ }
809
+ };
810
+ return new FreshdeskClient(config, credentials, options);
811
+ });
812
+ }
813
+ function durationMilliseconds(value) {
814
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TypeError("Freshdesk configuration pollInterval has an invalid type");
815
+ return value === 0 ? void 0 : Math.ceil(value / 1e6);
816
+ }
817
+
818
+ // src/trigger_definition.ts
819
+ import { mustTriggerBindingDefinition } from "@superdurable/connectors-sdk";
820
+ import { z } from "zod";
821
+ var TicketChangeCreated = "created";
822
+ var TicketChangeUpdated = "updated";
823
+ var TicketChangedTriggerConfigurationSchema = z.strictObject({
824
+ /**
825
+ * Limits deliveries to these kinds, such as ["created"]. Empty or omitted delivers both. Skipped changes still
826
+ * move the cursor, so adding a kind later never delivers changes the binding already passed.
827
+ */
828
+ changeKinds: z.array(z.string()).nullable().optional()
829
+ }).superRefine((configuration, context) => {
830
+ const seen = /* @__PURE__ */ new Set();
831
+ for (const kind of configuration.changeKinds ?? []) {
832
+ if (kind !== TicketChangeCreated && kind !== TicketChangeUpdated) context.addIssue({ code: "custom", message: `ticketChanged changeKinds entry ${JSON.stringify(kind)} must be created or updated` });
833
+ else if (seen.has(kind)) context.addIssue({ code: "custom", message: `ticketChanged changeKinds lists ${JSON.stringify(kind)} twice` });
834
+ seen.add(kind);
835
+ }
836
+ });
837
+ var TicketChangedEventSchema = z.object({
838
+ /** created or updated; see TicketChangeKind. */
839
+ changeKind: z.enum([TicketChangeCreated, TicketChangeUpdated]),
840
+ /** The ticket as the list returned it, without its description; read it with getTicket for its text. */
841
+ ticket: TicketSchema
842
+ });
843
+ var TicketChangedTriggerDefinition = {
844
+ trigger: { connectorId: ConnectorID, triggerName: "ticketChanged" },
845
+ description: "Receive each Freshdesk ticket created or updated after the binding first started, read by polling the ticket list in updated_at order; the first run records a baseline and delivers no existing tickets."
846
+ };
847
+ function defineTicketChangedTriggerBinding(config) {
848
+ return mustTriggerBindingDefinition({ definition: TicketChangedTriggerDefinition, ...config });
849
+ }
850
+
851
+ // src/ticket_change_fetcher.ts
852
+ import { markCursorInvalid, markRateLimited, newTriggerCredentialCall, waitForPollRequest } from "@superdurable/connectors-sdk/pollingtrigger";
853
+ var TicketChangePageSize = 100;
854
+ var MaxTicketListPage = 300;
855
+ var TicketChangeOverlapMs = 6e4;
856
+ var maximumDeliveredTicketKeys = 1500;
857
+ var maximumSeedPages = 15;
858
+ var maximumClockSkewMs = 2e3;
859
+ var requestTimeoutMs = 12e3;
860
+ var zeroTime = Number.NEGATIVE_INFINITY;
861
+ var ticketListTimePattern = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/;
862
+ var goIntegerPattern = /^[+-]?\d+$/;
863
+ var operationName = "ticketChanged";
864
+ var TicketChangeCursorInvalidError = class extends Error {
865
+ /** Describe the rejected token without echoing it. */
866
+ constructor() {
867
+ super("Freshdesk ticketChanged cursor is not decodable");
868
+ this.name = "TicketChangeCursorInvalidError";
869
+ }
870
+ };
871
+ var unixSeconds = (milliseconds) => Math.floor(milliseconds / 1e3);
872
+ var truncateToSecond = (milliseconds) => unixSeconds(milliseconds) * 1e3;
873
+ var formatTicketListTime = (milliseconds) => `${new Date(truncateToSecond(milliseconds)).toISOString().slice(0, 19)}Z`;
874
+ function parseTicketListTime(text2) {
875
+ if (typeof text2 !== "string" || !ticketListTimePattern.test(text2)) throw new TicketChangeCursorInvalidError();
876
+ const parsed = Date.parse(text2);
877
+ if (!Number.isFinite(parsed) || formatTicketListTime(parsed) !== text2) throw new TicketChangeCursorInvalidError();
878
+ return parsed;
879
+ }
880
+ function deliveredTicketKey(ticket2) {
881
+ return `${ticket2.id}@${unixSeconds(Date.parse(ticket2.updatedAt))}`;
882
+ }
883
+ function ticketChangeEventId(ticket2) {
884
+ return `freshdesk-ticket-${ticket2.id}-${unixSeconds(Date.parse(ticket2.updatedAt))}`;
885
+ }
886
+ function deliversTicketChangeKind(configuration, kind) {
887
+ const kinds = configuration.changeKinds ?? [];
888
+ return kinds.length === 0 || kinds.includes(kind);
889
+ }
890
+ function steadyTicketWindowStart(highWaterMs, floorMs) {
891
+ const windowStart = highWaterMs - TicketChangeOverlapMs;
892
+ return floorMs > windowStart ? floorMs : windowStart;
893
+ }
894
+ function formatTicketCursorFloor(floorMs, highWaterMs) {
895
+ return floorMs > highWaterMs - TicketChangeOverlapMs ? formatTicketListTime(floorMs) : "";
896
+ }
897
+ function pruneDeliveredTicketKeys(keys, windowStartMs) {
898
+ const windowSecond = BigInt(unixSeconds(windowStartMs));
899
+ const kept = [];
900
+ const seen = /* @__PURE__ */ new Set();
901
+ for (const key of keys) {
902
+ const separator = key.indexOf("@");
903
+ if (separator < 0 || seen.has(key)) continue;
904
+ const text2 = key.slice(separator + 1);
905
+ if (!goIntegerPattern.test(text2)) continue;
906
+ const updatedAt = BigInt(text2);
907
+ if (updatedAt < -(1n << 63n) || updatedAt >= 1n << 63n || updatedAt < windowSecond) continue;
908
+ seen.add(key);
909
+ kept.push({ key, updatedAt });
910
+ }
911
+ kept.sort((left, right) => left.updatedAt < right.updatedAt ? -1 : left.updatedAt > right.updatedAt ? 1 : 0);
912
+ let floorMs = zeroTime;
913
+ let retained = kept;
914
+ const dropped = kept.length - maximumDeliveredTicketKeys;
915
+ if (dropped > 0) {
916
+ let floorSecond = kept[dropped].updatedAt;
917
+ if (kept[dropped - 1].updatedAt === floorSecond) floorSecond += 1n;
918
+ floorMs = Number(floorSecond) * 1e3;
919
+ retained = kept.slice(dropped).filter((entry) => entry.updatedAt >= floorSecond);
920
+ }
921
+ return { pruned: retained.map((entry) => entry.key), floorMs };
922
+ }
923
+ function encodeGoJSONString(text2) {
924
+ return JSON.stringify(text2.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD")).replace(/[<>&\u2028\u2029]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
925
+ }
926
+ function encodeTicketChangeCursor(position) {
927
+ const members = [`"updatedSince":${encodeGoJSONString(position.updatedSince)}`];
928
+ if (position.windowStart) members.push(`"windowStart":${encodeGoJSONString(position.windowStart)}`);
929
+ if (position.page) members.push(`"page":${position.page}`);
930
+ if (position.floor) members.push(`"floor":${encodeGoJSONString(position.floor)}`);
931
+ if (position.delivered.length) members.push(`"delivered":[${position.delivered.map(encodeGoJSONString).join(",")}]`);
932
+ return { token: `{${members.join(",")}}` };
933
+ }
934
+ function decodeCursorPosition(token) {
935
+ let document;
936
+ try {
937
+ document = JSON.parse(token);
938
+ } catch {
939
+ throw new TicketChangeCursorInvalidError();
940
+ }
941
+ const position = { updatedSince: "", windowStart: "", page: 0, floor: "", delivered: [] };
942
+ if (document === null) return position;
943
+ if (typeof document !== "object" || Array.isArray(document)) throw new TicketChangeCursorInvalidError();
944
+ for (const [name, value] of Object.entries(document)) {
945
+ if (value === null) continue;
946
+ const folded = name.toLowerCase();
947
+ if (folded === "updatedsince" || folded === "windowstart" || folded === "floor") {
948
+ if (typeof value !== "string") throw new TicketChangeCursorInvalidError();
949
+ if (folded === "updatedsince") position.updatedSince = value;
950
+ else if (folded === "windowstart") position.windowStart = value;
951
+ else position.floor = value;
952
+ } else if (folded === "page") {
953
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new TicketChangeCursorInvalidError();
954
+ position.page = value;
955
+ } else if (folded === "delivered") {
956
+ if (!Array.isArray(value) || value.some((item) => item !== null && typeof item !== "string")) throw new TicketChangeCursorInvalidError();
957
+ position.delivered = value.map((item) => typeof item === "string" ? item : "");
958
+ }
959
+ }
960
+ return position;
961
+ }
962
+ function decodeTicketChangeCursor(cursor) {
963
+ const position = decodeCursorPosition(cursor.token);
964
+ const sinceMs = parseTicketListTime(position.updatedSince);
965
+ const floorMs = position.floor ? parseTicketListTime(position.floor) : zeroTime;
966
+ const steady = steadyTicketWindowStart(sinceMs, floorMs);
967
+ if (position.page === 0 && position.windowStart === "") return { position, sinceMs, floorMs, windowStartMs: steady, pageNumber: 1 };
968
+ const backlogStartMs = parseTicketListTime(position.windowStart);
969
+ if (backlogStartMs > sinceMs || position.page === 1 || position.page < 0 || position.page > MaxTicketListPage) throw new TicketChangeCursorInvalidError();
970
+ if (position.page === 0) return { position, sinceMs, floorMs, windowStartMs: Math.max(floorMs, backlogStartMs), pageNumber: 1 };
971
+ return { position, sinceMs, floorMs, windowStartMs: backlogStartMs, pageNumber: position.page };
972
+ }
973
+ function headerValues(headers, name) {
974
+ const value = headers[name];
975
+ return value === void 0 ? [] : Array.isArray(value) ? value : [value];
976
+ }
977
+ function parseHTTPDate(value) {
978
+ if (!value) return void 0;
979
+ const parsed = Date.parse(value);
980
+ return Number.isFinite(parsed) ? truncateToSecond(parsed) : void 0;
981
+ }
982
+ function decodeTicketList(body) {
983
+ let rows;
984
+ try {
985
+ rows = JSON.parse(Buffer.from(body).toString("utf8"));
986
+ } catch {
987
+ throw new TypeError("the response is not a ticket array");
988
+ }
989
+ if (rows === null) return [];
990
+ if (!Array.isArray(rows)) throw new TypeError("the response is not a ticket array");
991
+ if (rows.length > TicketChangePageSize) throw new TypeError(`the page has ${rows.length} tickets, more than ${TicketChangePageSize}`);
992
+ return rows.map((row) => decodeTicketWire(row));
993
+ }
994
+ var TicketChangeFetcher = class {
995
+ /** Bind the fetcher to one connection's client and one binding's validated configuration. */
996
+ constructor(client, connection, configuration) {
997
+ this.client = client;
998
+ this.connection = connection;
999
+ this.configuration = configuration;
1000
+ if (!client || !connection || !configuration) throw new TypeError("Freshdesk ticketChanged client, connection, and configuration are required");
1001
+ }
1002
+ client;
1003
+ connection;
1004
+ configuration;
1005
+ /**
1006
+ * Record the baseline without reporting existing tickets: the high-water mark is Freshdesk's current time
1007
+ * from the response Date header, or the local clock without one, and tickets changed within the overlap
1008
+ * before it are remembered as delivered.
1009
+ */
1010
+ async seedCursor(context) {
1011
+ const baselineMs = truncateToSecond(this.client.currentTime().getTime());
1012
+ let seeded = await this.listSeedWindow(context, baselineMs);
1013
+ if (seeded.serverTimeMs !== void 0 && Math.abs(seeded.serverTimeMs - baselineMs) > maximumClockSkewMs) seeded = await this.listSeedWindow(context, seeded.serverTimeMs);
1014
+ return encodeTicketChangeCursor(seeded.position);
1015
+ }
1016
+ async listSeedWindow(context, baselineMs) {
1017
+ const delivered = [];
1018
+ let serverTimeMs;
1019
+ let sinceMs = baselineMs;
1020
+ for (let pageNumber = 1; pageNumber <= maximumSeedPages; pageNumber++) {
1021
+ const listed = await this.listTicketPage(context, baselineMs - TicketChangeOverlapMs, pageNumber);
1022
+ if (pageNumber === 1) serverTimeMs = listed.serverTimeMs;
1023
+ for (const ticket2 of listed.tickets) {
1024
+ delivered.push(deliveredTicketKey(ticket2));
1025
+ sinceMs = Math.max(sinceMs, Date.parse(ticket2.updatedAt));
1026
+ }
1027
+ if (!listed.hasNextPage) break;
1028
+ }
1029
+ const { pruned, floorMs } = pruneDeliveredTicketKeys(delivered, sinceMs - TicketChangeOverlapMs);
1030
+ return { position: { updatedSince: formatTicketListTime(sinceMs), windowStart: "", page: 0, floor: formatTicketCursorFloor(floorMs, sinceMs), delivered: pruned }, serverTimeMs };
1031
+ }
1032
+ /**
1033
+ * Read one page of tickets updated since the cursor's window start, oldest first. An undecodable cursor and a
1034
+ * Freshdesk 400 for the cursor's query reject with markCursorInvalid, so the kit records a new baseline; a
1035
+ * 429 rejects with markRateLimited and Retry-After.
1036
+ */
1037
+ async fetchChanges(context, cursor) {
1038
+ let decoded;
1039
+ try {
1040
+ decoded = decodeTicketChangeCursor(cursor);
1041
+ } catch (error) {
1042
+ throw markCursorInvalid(error);
1043
+ }
1044
+ const listed = await this.listTicketPage(context, decoded.windowStartMs, decoded.pageNumber);
1045
+ const delivered = new Set(decoded.position.delivered);
1046
+ const deliveredTicketIDs = new Set(decoded.position.delivered.map((key) => key.split("@", 1)[0]));
1047
+ const createdFloorMs = Math.min(decoded.sinceMs - TicketChangeOverlapMs, decoded.windowStartMs);
1048
+ const next = { updatedSince: "", windowStart: "", page: 0, floor: "", delivered: [...decoded.position.delivered] };
1049
+ let highWaterMs = decoded.sinceMs;
1050
+ const changes = [];
1051
+ for (const ticket2 of listed.tickets) {
1052
+ const key = deliveredTicketKey(ticket2);
1053
+ const updatedAtMs = Date.parse(ticket2.updatedAt);
1054
+ if (delivered.has(key) || updatedAtMs < decoded.windowStartMs) continue;
1055
+ const kind = Date.parse(ticket2.createdAt) >= createdFloorMs && !deliveredTicketIDs.has(String(ticket2.id)) ? "created" : "updated";
1056
+ delivered.add(key);
1057
+ next.delivered.push(key);
1058
+ highWaterMs = Math.max(highWaterMs, updatedAtMs);
1059
+ if (deliversTicketChangeKind(this.configuration, kind)) changes.push({ id: ticketChangeEventId(ticket2), occurredAt: new Date(updatedAtMs), payload: { changeKind: kind, ticket: ticket2 } });
1060
+ }
1061
+ next.updatedSince = formatTicketListTime(highWaterMs);
1062
+ let floorMs = decoded.floorMs;
1063
+ let nextWindowStartMs = steadyTicketWindowStart(highWaterMs, floorMs);
1064
+ let hasMorePages = false;
1065
+ const lastTicket = listed.tickets.at(-1);
1066
+ if (decoded.pageNumber >= MaxTicketListPage && listed.tickets.length === TicketChangePageSize) {
1067
+ hasMorePages = true;
1068
+ floorMs = decoded.windowStartMs + 1e3;
1069
+ nextWindowStartMs = steadyTicketWindowStart(highWaterMs, floorMs);
1070
+ } else if (!listed.hasNextPage || !lastTicket) {
1071
+ } else if (Date.parse(lastTicket.updatedAt) > decoded.windowStartMs) {
1072
+ hasMorePages = true;
1073
+ nextWindowStartMs = Date.parse(lastTicket.updatedAt);
1074
+ next.windowStart = formatTicketListTime(nextWindowStartMs);
1075
+ } else {
1076
+ hasMorePages = true;
1077
+ nextWindowStartMs = decoded.windowStartMs;
1078
+ next.windowStart = formatTicketListTime(decoded.windowStartMs);
1079
+ next.page = decoded.pageNumber + 1;
1080
+ }
1081
+ if (!hasMorePages && listed.serverTimeMs !== void 0) {
1082
+ floorMs = Math.max(floorMs, listed.serverTimeMs - TicketChangeOverlapMs - requestTimeoutMs);
1083
+ nextWindowStartMs = steadyTicketWindowStart(highWaterMs, floorMs);
1084
+ }
1085
+ const { pruned, floorMs: overflowFloorMs } = pruneDeliveredTicketKeys(next.delivered, Math.min(steadyTicketWindowStart(highWaterMs, floorMs), nextWindowStartMs));
1086
+ next.delivered = pruned;
1087
+ floorMs = Math.max(floorMs, overflowFloorMs);
1088
+ next.floor = formatTicketCursorFloor(floorMs, highWaterMs);
1089
+ return { changes, next: encodeTicketChangeCursor(next), hasMorePages };
1090
+ }
1091
+ async listTicketPage(context, windowStartMs, pageNumber) {
1092
+ await waitForPollRequest(context);
1093
+ const call = newTriggerCredentialCall(this.connection, TicketChangedTriggerDefinition.trigger, context.signal);
1094
+ const credential2 = await this.client.resolveCredential(call, operationName);
1095
+ if (!("key" in credential2)) throw new Error("Freshdesk ticketChanged credentials are unavailable");
1096
+ const query = new URLSearchParams([
1097
+ ["order_by", "updated_at"],
1098
+ ["order_type", "asc"],
1099
+ ["page", String(pageNumber)],
1100
+ ["per_page", String(TicketChangePageSize)],
1101
+ ["updated_since", formatTicketListTime(windowStartMs)]
1102
+ ]);
1103
+ const result = await this.client.exchange(call, operationName, credential2.key, "GET", "/tickets", query, void 0, context.signal);
1104
+ if (result.outcome !== "succeeded") {
1105
+ const failure = new Error(`Freshdesk ticket list request: ${result.failure.message}`);
1106
+ if (result.outcome === "rateLimited") throw markRateLimited(failure, result.retryAfterMs);
1107
+ if (result.outcome === "rejected" && result.response?.status === 400) throw markCursorInvalid(failure);
1108
+ throw failure;
1109
+ }
1110
+ let tickets;
1111
+ try {
1112
+ tickets = decodeTicketList(result.response.body);
1113
+ } catch (error) {
1114
+ throw new Error(`Freshdesk ticket list page is invalid: ${error instanceof Error ? error.message : String(error)}`);
1115
+ }
1116
+ const headers = result.response.headers;
1117
+ return { tickets, hasNextPage: headerValues(headers, "link").some((link) => link.includes('rel="next"')), serverTimeMs: parseHTTPDate(headerValues(headers, "date")[0]) };
1118
+ }
1119
+ };
1120
+
1121
+ // src/trigger.ts
1122
+ import { newTrigger } from "@superdurable/connectors-sdk";
1123
+ import { newBindingPoller, newBindingTriggerSource, newMemoryCursorStore, newRunner } from "@superdurable/connectors-sdk/pollingtrigger";
1124
+ import { ObjectNotFoundError as ObjectNotFoundError2, decodeTriggerConfiguration, newDurableTriggerTarget } from "@superdurable/connectors-sdk/projectconfig";
1125
+ var triggerName = TicketChangedTriggerDefinition.trigger.triggerName;
1126
+ function freshdeskClientOf(connection) {
1127
+ if (!connection) throw new TypeError("Freshdesk ticketChanged connection is required");
1128
+ if (!(connection.operations instanceof FreshdeskClient)) throw new TypeError("Freshdesk ticketChanged Triggers require a FreshdeskClient connection, not a mock");
1129
+ return connection.operations;
1130
+ }
1131
+ var pollSchedule = (client) => ({ intervalMs: client.pollIntervalMs });
1132
+ function newTicketTriggerRunner(config) {
1133
+ const client = freshdeskClientOf(config.connection);
1134
+ if (!config.ticketChangedRoutes?.length) throw new TypeError("Freshdesk ticketChanged routes are required");
1135
+ const reference = config.connection.reference;
1136
+ const pollers = config.ticketChangedRoutes.map((route) => {
1137
+ if (!route?.bindingName?.trim() || !route.target) throw new TypeError("Freshdesk ticketChanged binding name and target are required");
1138
+ const configuration = parseTicketChangedTriggerConfiguration(route.configuration ?? {});
1139
+ return newBindingPoller({
1140
+ definition: TicketChangedTriggerDefinition,
1141
+ binding: { connection: reference, trigger: TicketChangedTriggerDefinition.trigger, name: route.bindingName },
1142
+ cursor: route.cursor ?? newMemoryCursorStore(),
1143
+ fetcher: new TicketChangeFetcher(client, reference, configuration),
1144
+ target: route.target
1145
+ });
1146
+ });
1147
+ return newRunner({ connection: reference, schedule: pollSchedule(client), pollers, logger: client.triggerLogger });
1148
+ }
1149
+ function parseTicketChangedTriggerConfiguration(configuration) {
1150
+ const parsed = TicketChangedTriggerConfigurationSchema.safeParse(configuration);
1151
+ if (!parsed.success) throw new TypeError(`freshdesk ticketChanged configuration: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`);
1152
+ return parsed.data;
1153
+ }
1154
+ function decodeTicketChangedEventPayload(payloadJSON) {
1155
+ return TicketChangedEventSchema.parse(JSON.parse(payloadJSON));
1156
+ }
1157
+ function newProjectTicketTriggerRunner(project, connection, config) {
1158
+ if (!project) throw new TypeError("Freshdesk ticketChanged Triggers require a loaded project");
1159
+ const client = freshdeskClientOf(connection);
1160
+ const ticketChangedRoutes = (config.ticketChangedRoutes ?? []).map((route) => {
1161
+ if (!route?.target) throw new TypeError("Freshdesk ticketChanged binding target is required");
1162
+ const key = { connectorId: ConnectorID, connectionName: connection.reference.name, triggerName, bindingName: route.bindingName };
1163
+ let configuration;
1164
+ try {
1165
+ configuration = decodeTriggerConfiguration(project.configuration, key, TicketChangedTriggerConfigurationSchema);
1166
+ } catch (error) {
1167
+ if (!(error instanceof ObjectNotFoundError2)) throw new TypeError(`freshdesk ticketChanged binding ${JSON.stringify(route.bindingName)} configuration is invalid`, { cause: error });
1168
+ configuration = {};
1169
+ }
1170
+ const target = newDurableTriggerTarget(project.triggerInbox(key), key, route.target, { logger: client.triggerLogger, decodePayload: decodeTicketChangedEventPayload });
1171
+ return { bindingName: route.bindingName, configuration, target, cursor: project.pollCursorStore(key) };
1172
+ });
1173
+ return newTicketTriggerRunner({ connection, ticketChangedRoutes });
1174
+ }
1175
+ function newTicketChangedTrigger(config) {
1176
+ const client = freshdeskClientOf(config.connection);
1177
+ const reference = config.connection.reference;
1178
+ if (config.connectionName !== reference.name) throw new TypeError(`freshdesk connector trigger connectionName ${JSON.stringify(config.connectionName)} must equal its connection's name ${JSON.stringify(reference.name)}`);
1179
+ const configuration = parseTicketChangedTriggerConfiguration(config.configuration ?? {});
1180
+ const binding = { connection: reference, trigger: TicketChangedTriggerDefinition.trigger, name: config.bindingName };
1181
+ const source = newBindingTriggerSource({
1182
+ definition: TicketChangedTriggerDefinition,
1183
+ binding,
1184
+ cursor: newMemoryCursorStore(),
1185
+ fetcher: new TicketChangeFetcher(client, reference, configuration)
1186
+ }, pollSchedule(client), client.triggerLogger);
1187
+ return newTrigger({ definition: TicketChangedTriggerDefinition, binding, source, target: config.target, logger: client.triggerLogger });
1188
+ }
1189
+ export {
1190
+ AddNoteBranch,
1191
+ AddNoteBranchAdded,
1192
+ AddNoteBranchDefect,
1193
+ AddNoteBranchNotFound,
1194
+ AddNoteBranchProviderRejected,
1195
+ AddNoteBranchUncertain,
1196
+ AddNoteDefinition,
1197
+ AddNoteInputSchema,
1198
+ AddNoteMetadata,
1199
+ AddNoteOperation,
1200
+ AddNoteOutputSchema,
1201
+ ConfigSchema,
1202
+ Connection,
1203
+ ConnectorID,
1204
+ CreateTicketBranch,
1205
+ CreateTicketBranchCreated,
1206
+ CreateTicketBranchDefect,
1207
+ CreateTicketBranchProviderRejected,
1208
+ CreateTicketBranchUncertain,
1209
+ CreateTicketDefinition,
1210
+ CreateTicketInputSchema,
1211
+ CreateTicketMetadata,
1212
+ CreateTicketOperation,
1213
+ CreateTicketOutputSchema,
1214
+ FreshdeskClient,
1215
+ GetTicketBranch,
1216
+ GetTicketBranchDefect,
1217
+ GetTicketBranchFound,
1218
+ GetTicketBranchInvalidResponse,
1219
+ GetTicketBranchNotFound,
1220
+ GetTicketBranchProviderRejected,
1221
+ GetTicketDefinition,
1222
+ GetTicketInputSchema,
1223
+ GetTicketMetadata,
1224
+ GetTicketOperation,
1225
+ MaxTicketListPage,
1226
+ ProviderID,
1227
+ SearchTicketsBranch,
1228
+ SearchTicketsBranchDefect,
1229
+ SearchTicketsBranchInvalidResponse,
1230
+ SearchTicketsBranchProviderRejected,
1231
+ SearchTicketsBranchSearched,
1232
+ SearchTicketsDefinition,
1233
+ SearchTicketsInputSchema,
1234
+ SearchTicketsMetadata,
1235
+ SearchTicketsOperation,
1236
+ SearchTicketsOutputSchema,
1237
+ TicketChangeCreated,
1238
+ TicketChangeCursorInvalidError,
1239
+ TicketChangeFetcher,
1240
+ TicketChangeOverlapMs,
1241
+ TicketChangePageSize,
1242
+ TicketChangeUpdated,
1243
+ TicketChangedEventSchema,
1244
+ TicketChangedTriggerConfigurationSchema,
1245
+ TicketChangedTriggerDefinition,
1246
+ TicketConversationSchema,
1247
+ TicketDetailsSchema,
1248
+ TicketRequesterInputSchema,
1249
+ TicketRequesterSchema,
1250
+ TicketSchema,
1251
+ UpdateTicketBranch,
1252
+ UpdateTicketBranchDefect,
1253
+ UpdateTicketBranchInvalidResponse,
1254
+ UpdateTicketBranchNotFound,
1255
+ UpdateTicketBranchProviderRejected,
1256
+ UpdateTicketBranchUpdated,
1257
+ UpdateTicketDefinition,
1258
+ UpdateTicketInputSchema,
1259
+ UpdateTicketMetadata,
1260
+ UpdateTicketOperation,
1261
+ UpdateTicketOutputSchema,
1262
+ decodeCredentials,
1263
+ decodeTicketChangedEventPayload,
1264
+ defineTicketChangedTriggerBinding,
1265
+ deliversTicketChangeKind,
1266
+ newAddNoteStep,
1267
+ newConnection,
1268
+ newConnectionWithOperations,
1269
+ newCreateTicketStep,
1270
+ newGetTicketStep,
1271
+ newProjectConnection2 as newProjectConnection,
1272
+ newProjectTicketTriggerRunner,
1273
+ newSearchTicketsStep,
1274
+ newTicketChangedTrigger,
1275
+ newTicketTriggerRunner,
1276
+ newUpdateTicketStep,
1277
+ parseTicketChangedTriggerConfiguration,
1278
+ ticketChangeEventId
1279
+ };