@superdurable/connector-twilio-messaging 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -7
- package/dex-connector.json +61 -4
- package/dist/{chunk-RO6VVVPT.js → chunk-6KLMYDTX.js} +36 -8
- package/dist/{connection-DU3WOoJL.d.ts → connection-BQ9-3dhC.d.ts} +7 -4
- package/dist/index.d.ts +134 -6
- package/dist/index.js +473 -30
- package/dist/mock.d.ts +1 -1
- package/dist/mock.js +1 -1
- package/package.json +7 -5
package/README.md
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
# Twilio Messaging TypeScript connector
|
|
2
2
|
|
|
3
|
-
`@superdurable/connector-twilio-messaging` provides the `sendMessage` Mutation
|
|
4
|
-
|
|
3
|
+
`@superdurable/connector-twilio-messaging` provides the `sendMessage` Mutation,
|
|
4
|
+
the `getMessage` Query, and the `messageReceived` poll Trigger for Dex
|
|
5
|
+
TypeScript applications. The package ships
|
|
5
6
|
manifest-generated contracts and Step factories; `src/client.ts` and
|
|
6
7
|
`src/operations.ts` implement the Twilio Messages HTTP behavior.
|
|
7
8
|
|
|
8
|
-
Install with `npm install @superdurable/connector-twilio-messaging@0.
|
|
9
|
+
Install with `npm install @superdurable/connector-twilio-messaging@0.2.0`.
|
|
9
10
|
Use Node.js 22 or 24 and the released Connector SDK version in `package.json`.
|
|
10
11
|
|
|
11
12
|
## Connection
|
|
@@ -18,7 +19,8 @@ secret `api_key_secret` from **Account > API keys & tokens**. The key must
|
|
|
18
19
|
belong to the same account and Region. `defaultSender` can be an E.164 number,
|
|
19
20
|
`whatsapp:` number, or Messaging Service `MG` SID; blank requires `sender` on
|
|
20
21
|
each request. Leave `endpoint` and `maxResponseBytes` blank for their manifest
|
|
21
|
-
defaults.
|
|
22
|
+
defaults. `pollInterval` is the delay between `messageReceived` polls, a Go
|
|
23
|
+
duration of at least 5 seconds. Secrets are resolved for every call and never belong in Flow input.
|
|
22
24
|
Stored credentials without `auth_method` use `auth-token`; a rejected static
|
|
23
25
|
credential requires updating the connection rather than an automatic refresh.
|
|
24
26
|
|
|
@@ -27,6 +29,42 @@ uses `newProjectConnection(project, ConnectionName)` and the generated
|
|
|
27
29
|
`newSendMessageStep` and `newGetMessageStep`. Its static connection name is
|
|
28
30
|
`twilio-messaging`.
|
|
29
31
|
|
|
32
|
+
## messageReceived Trigger
|
|
33
|
+
|
|
34
|
+
`messageReceived` polls the account's Messages list with the TypeScript poll
|
|
35
|
+
Trigger kit (`@superdurable/connectors-sdk/pollingtrigger`, Connector SDK
|
|
36
|
+
0.12.0) at behavior parity with the Go connector, and delivers one
|
|
37
|
+
`MessageReceivedEvent` per inbound message: the safe message view plus its
|
|
38
|
+
text. The binding's saved `to` (an E.164 number or `whatsapp:+E.164` sender;
|
|
39
|
+
blank receives every inbound message of the account) is sent as the list's
|
|
40
|
+
`To` filter, and outbound messages are never delivered. The first poll records
|
|
41
|
+
the last two minutes as a baseline. Later polls relist from the `date_sent`
|
|
42
|
+
watermark minus two minutes, skip SIDs already delivered, hold an MMS still in
|
|
43
|
+
`receiving` for up to ten minutes, and deliver at most 500 messages per page,
|
|
44
|
+
oldest first. A 429 pauses the connection for `Retry-After`; an undecodable
|
|
45
|
+
cursor, or one for another account or number, records a new baseline. The
|
|
46
|
+
Trigger event ID is `twilio-message-<SID>`. The
|
|
47
|
+
[connector README](../README.md#messagereceived-trigger) describes pagination
|
|
48
|
+
and window halving.
|
|
49
|
+
|
|
50
|
+
The cursor token and keyed snapshot match the Go connector byte for byte, so Go
|
|
51
|
+
and TypeScript replicas share a binding's cursor, and a message a Go replica
|
|
52
|
+
recorded in the inbox replays in TypeScript.
|
|
53
|
+
[`examples/message-received/app.ts`](examples/message-received/app.ts) records
|
|
54
|
+
each message in the binding's project Trigger inbox before the watermark
|
|
55
|
+
commits:
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
const runner = newProjectMessageTriggerRunner(project, connection, [{
|
|
59
|
+
bindingName: MessageReceivedTriggerBinding, target: newDexFlowTriggerTarget(client, flow, acceptEveryInboundMessage, resolveFlowId, mapToFlowInput, { logger: options.logger }),
|
|
60
|
+
}], options.logger);
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`newMessageTriggerRunner` takes targets and cursor stores directly, and
|
|
64
|
+
`newMessageReceivedTrigger` runs one binding with an in-memory cursor, so every
|
|
65
|
+
start records a new baseline. See the
|
|
66
|
+
[message-received example](examples/message-received/README.md).
|
|
67
|
+
|
|
30
68
|
## Behavior
|
|
31
69
|
|
|
32
70
|
`sendMessage` sends `To`, an optional body, ordered media URLs, and either
|
|
@@ -45,6 +83,9 @@ credential values, and provider error prose are excluded. Status and request
|
|
|
45
83
|
count behavior is replayed against Go recordings in
|
|
46
84
|
`conformance/connectors/twilio/messaging/scenarios.json`.
|
|
47
85
|
|
|
48
|
-
Run `npm ci && npm run check` in this directory. The
|
|
49
|
-
|
|
50
|
-
|
|
86
|
+
Run `npm ci && npm run check` in this directory. The Trigger tests replay the
|
|
87
|
+
Go fetcher and runner tests against a local Messages list fake and compare
|
|
88
|
+
cursor tokens, snapshot keys, request queries, and event payloads with
|
|
89
|
+
Go-printed values. The examples' Dex Worker and Client integration checks need
|
|
90
|
+
`dexcli dev` and `DEX_FLOW_SERVICE_ADDRESS`. Live Twilio authorization, message
|
|
91
|
+
creation, delivery, and Messages listing were not verified.
|
package/dex-connector.json
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"connectorId": "twilio-messaging",
|
|
3
|
-
"releaseTag": "connectors/twilio/messaging/go/v0.
|
|
3
|
+
"releaseTag": "connectors/twilio/messaging/go/v0.24.0",
|
|
4
4
|
"package": {
|
|
5
5
|
"ecosystem": "npm",
|
|
6
6
|
"name": "@superdurable/connector-twilio-messaging",
|
|
7
|
-
"version": "0.
|
|
7
|
+
"version": "0.2.0"
|
|
8
8
|
},
|
|
9
9
|
"factories": [
|
|
10
10
|
{
|
|
11
11
|
"name": "newSendMessageStep",
|
|
12
12
|
"kind": "mutation",
|
|
13
13
|
"operationId": "sendMessage",
|
|
14
|
+
"inputType": "SendMessageInput",
|
|
15
|
+
"description": "Send one SMS, MMS, or WhatsApp message from a Twilio number or Messaging Service to one recipient; synchronous durability makes the single-dispatch checkpoint visible to retries because Twilio provides no message idempotency key.",
|
|
14
16
|
"fields": {
|
|
15
17
|
"stepType": "stepType",
|
|
16
18
|
"annotations": "annotations",
|
|
@@ -38,12 +40,43 @@
|
|
|
38
40
|
"field": "defect",
|
|
39
41
|
"optional": true
|
|
40
42
|
}
|
|
41
|
-
]
|
|
43
|
+
],
|
|
44
|
+
"inputSchema": {
|
|
45
|
+
"additionalProperties": false,
|
|
46
|
+
"description": "SendMessageInput describes one message to one recipient.",
|
|
47
|
+
"properties": {
|
|
48
|
+
"body": {
|
|
49
|
+
"description": "Body is the message text, at most 1600 characters. It may be empty only when MediaURLs is set.",
|
|
50
|
+
"type": "string"
|
|
51
|
+
},
|
|
52
|
+
"mediaUrls": {
|
|
53
|
+
"description": "MediaURLs lists at most 10 public HTTPS URLs that Twilio fetches and attaches, which makes an SMS an MMS.",
|
|
54
|
+
"items": {
|
|
55
|
+
"type": "string"
|
|
56
|
+
},
|
|
57
|
+
"type": "array"
|
|
58
|
+
},
|
|
59
|
+
"sender": {
|
|
60
|
+
"description": "Sender overrides the connection's defaultSender with an E.164 number, a whatsapp: address, or an MG Messaging Service SID. Blank uses defaultSender.",
|
|
61
|
+
"type": "string"
|
|
62
|
+
},
|
|
63
|
+
"to": {
|
|
64
|
+
"description": "To is the recipient: an E.164 number such as +14155550100, or whatsapp:+14155550100.",
|
|
65
|
+
"type": "string"
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
"required": [
|
|
69
|
+
"to"
|
|
70
|
+
],
|
|
71
|
+
"type": "object"
|
|
72
|
+
}
|
|
42
73
|
},
|
|
43
74
|
{
|
|
44
75
|
"name": "newGetMessageStep",
|
|
45
76
|
"kind": "query",
|
|
46
77
|
"operationId": "getMessage",
|
|
78
|
+
"inputType": "GetMessageInput",
|
|
79
|
+
"description": "Read one message by SID, including its delivery status and Twilio error code.",
|
|
47
80
|
"fields": {
|
|
48
81
|
"stepType": "stepType",
|
|
49
82
|
"annotations": "annotations",
|
|
@@ -76,7 +109,31 @@
|
|
|
76
109
|
"field": "defect",
|
|
77
110
|
"optional": true
|
|
78
111
|
}
|
|
79
|
-
]
|
|
112
|
+
],
|
|
113
|
+
"inputSchema": {
|
|
114
|
+
"additionalProperties": false,
|
|
115
|
+
"description": "GetMessageInput identifies one message.",
|
|
116
|
+
"properties": {
|
|
117
|
+
"messageSid": {
|
|
118
|
+
"description": "MessageSID is the SM or MM message SID returned by sendMessage.",
|
|
119
|
+
"type": "string"
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
"required": [
|
|
123
|
+
"messageSid"
|
|
124
|
+
],
|
|
125
|
+
"type": "object"
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
"name": "defineMessageReceivedTriggerBinding",
|
|
130
|
+
"kind": "trigger",
|
|
131
|
+
"triggerName": "messageReceived",
|
|
132
|
+
"fields": {
|
|
133
|
+
"connectionName": "connectionName",
|
|
134
|
+
"bindingName": "bindingName",
|
|
135
|
+
"configurationUI": "configurationUI"
|
|
136
|
+
}
|
|
80
137
|
}
|
|
81
138
|
]
|
|
82
139
|
}
|
|
@@ -19,7 +19,9 @@ var SendMessageDefinition = {
|
|
|
19
19
|
{ id: "uncertain", description: "The request was dispatched but its outcome cannot be confirmed; Twilio has no idempotency key, so the message may exist and must not be resent automatically.", optional: true },
|
|
20
20
|
{ id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
|
|
21
21
|
],
|
|
22
|
-
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } }
|
|
22
|
+
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } },
|
|
23
|
+
repeatOnUnknown: "limited",
|
|
24
|
+
maxSends: 3
|
|
23
25
|
};
|
|
24
26
|
var GetMessageBranch = {
|
|
25
27
|
Found: "found",
|
|
@@ -48,28 +50,54 @@ var GetMessageDefinition = {
|
|
|
48
50
|
// src/generated/models.ts
|
|
49
51
|
import { z } from "zod";
|
|
50
52
|
import { SecretString } from "@superdurable/connectors-sdk";
|
|
53
|
+
var goTimeJSONPattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{1,2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|([+-])(\d{2}):(\d{2}))$/;
|
|
54
|
+
function isGoTimeJSON(value) {
|
|
55
|
+
const match = goTimeJSONPattern.exec(value);
|
|
56
|
+
if (!match) return false;
|
|
57
|
+
const [, yearText, monthText, dayText, hourText, minuteText, secondText, , zone, , zoneHourText, zoneMinuteText] = match;
|
|
58
|
+
const year = Number(yearText);
|
|
59
|
+
const month = Number(monthText);
|
|
60
|
+
const day = Number(dayText);
|
|
61
|
+
const isLeap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
62
|
+
const monthDays = [31, isLeap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
63
|
+
return month >= 1 && month <= 12 && day >= 1 && day <= monthDays[month - 1] && Number(hourText) <= 23 && Number(minuteText) <= 59 && Number(secondText) <= 59 && (zone === "Z" || Number(zoneHourText) <= 24 && Number(zoneMinuteText) <= 60);
|
|
64
|
+
}
|
|
65
|
+
function canonicalGoTimeJSON(value) {
|
|
66
|
+
const match = goTimeJSONPattern.exec(value);
|
|
67
|
+
const [, year, month, day, hour, minute, second, fraction, zone, sign, zoneHour, zoneMinute] = match;
|
|
68
|
+
const clock = year + "-" + month + "-" + day + "T" + hour.padStart(2, "0") + ":" + minute + ":" + second;
|
|
69
|
+
const digits = (fraction ?? "").slice(0, 9).replace(/0+$/, "");
|
|
70
|
+
const offsetMinutes = zone === "Z" ? 0 : (Number(zoneHour) * 60 + Number(zoneMinute)) * (sign === "+" ? 1 : -1);
|
|
71
|
+
if (Math.abs(offsetMinutes) >= 1440) return value;
|
|
72
|
+
const offset = offsetMinutes === 0 ? "Z" : (offsetMinutes > 0 ? "+" : "-") + String(Math.floor(Math.abs(offsetMinutes) / 60)).padStart(2, "0") + ":" + String(Math.abs(offsetMinutes) % 60).padStart(2, "0");
|
|
73
|
+
return clock + (digits ? "." + digits : "") + offset;
|
|
74
|
+
}
|
|
75
|
+
var GoTimeJSONSchema = z.string().refine(isGoTimeJSON, "invalid Go time.Time JSON timestamp").transform(canonicalGoTimeJSON);
|
|
51
76
|
var ConfigSchema = z.object({
|
|
52
77
|
"accountSid": z.string(),
|
|
53
78
|
"defaultSender": z.string().optional(),
|
|
54
79
|
"endpoint": z.string().optional(),
|
|
55
|
-
"maxResponseBytes": z.number().int().optional()
|
|
80
|
+
"maxResponseBytes": z.number().int().optional(),
|
|
81
|
+
"pollIntervalMs": z.number().int().optional()
|
|
56
82
|
});
|
|
57
83
|
function decodeCredentials(value) {
|
|
58
84
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential fields are invalid");
|
|
59
85
|
const fields = value;
|
|
86
|
+
const allowed = /* @__PURE__ */ new Set(["auth_method", "api_key_sid", "api_key_secret", "auth_token"]);
|
|
87
|
+
if (Object.keys(fields).some((key) => !allowed.has(key))) throw new TypeError("stored credential does not match the connector credential fields");
|
|
88
|
+
if (fields["api_key_sid"] != null && !(typeof fields["api_key_sid"] === "string")) throw new TypeError("credential api_key_sid has an invalid type");
|
|
89
|
+
if (fields["api_key_secret"] != null && !(typeof fields["api_key_secret"] === "string")) throw new TypeError("credential api_key_secret has an invalid type");
|
|
90
|
+
if (fields["auth_token"] != null && !(typeof fields["auth_token"] === "string")) throw new TypeError("credential auth_token has an invalid type");
|
|
60
91
|
const selectedMethod = fields["auth_method"] ?? "";
|
|
61
92
|
if (typeof selectedMethod !== "string") throw new TypeError("credential auth_method is invalid");
|
|
62
93
|
const method = selectedMethod || "auth-token";
|
|
63
94
|
const credentials = { authMethodId: method };
|
|
64
95
|
if (method === "auth-token") {
|
|
65
|
-
if (fields["auth_token"] != null && typeof fields["auth_token"] !== "string") throw new TypeError("credential auth_token has an invalid type");
|
|
66
96
|
if (!fields["auth_token"]) throw new TypeError("credential auth_token is required");
|
|
67
97
|
if (fields["auth_token"]) credentials.authToken = new SecretString(fields["auth_token"]);
|
|
68
98
|
} else if (method === "api-key") {
|
|
69
|
-
if (fields["api_key_sid"] != null && typeof fields["api_key_sid"] !== "string") throw new TypeError("credential api_key_sid has an invalid type");
|
|
70
99
|
if (!fields["api_key_sid"]) throw new TypeError("credential api_key_sid is required");
|
|
71
100
|
if (fields["api_key_sid"]) credentials.apiKeySid = fields["api_key_sid"];
|
|
72
|
-
if (fields["api_key_secret"] != null && typeof fields["api_key_secret"] !== "string") throw new TypeError("credential api_key_secret has an invalid type");
|
|
73
101
|
if (!fields["api_key_secret"]) throw new TypeError("credential api_key_secret is required");
|
|
74
102
|
if (fields["api_key_secret"]) credentials.apiKeySecret = new SecretString(fields["api_key_secret"]);
|
|
75
103
|
} else {
|
|
@@ -96,9 +124,9 @@ var MessageSchema = z.strictObject({
|
|
|
96
124
|
"mediaCount": z.number().int().optional(),
|
|
97
125
|
"price": z.string().optional(),
|
|
98
126
|
"priceUnit": z.string().optional(),
|
|
99
|
-
"createdAt":
|
|
100
|
-
"sentAt":
|
|
101
|
-
"updatedAt":
|
|
127
|
+
"createdAt": GoTimeJSONSchema,
|
|
128
|
+
"sentAt": GoTimeJSONSchema,
|
|
129
|
+
"updatedAt": GoTimeJSONSchema
|
|
102
130
|
});
|
|
103
131
|
var GetMessageInputSchema = z.strictObject({
|
|
104
132
|
"messageSid": z.string()
|
|
@@ -11,6 +11,8 @@ interface Config {
|
|
|
11
11
|
endpoint?: string;
|
|
12
12
|
/** Maximum complete Twilio API response in bytes. Leave blank to keep the displayed safety limit; enter a positive integer only to change it. An oversized getMessage response selects invalidResponse, and an oversized response to an accepted send selects uncertain. */
|
|
13
13
|
maxResponseBytes?: number;
|
|
14
|
+
/** Delay between messageReceived Trigger polls of the Twilio Messages list, as a Go duration of at least 5s such as 15s or 2m. Shorter intervals deliver inbound messages sooner and send more list requests, which count against the account's API concurrency limit. Leave blank to keep the displayed interval. Runtime value in milliseconds. */
|
|
15
|
+
pollIntervalMs?: number;
|
|
14
16
|
}
|
|
15
17
|
/** Runtime schema for manifest configuration. */
|
|
16
18
|
declare const ConfigSchema: z.ZodObject<{
|
|
@@ -18,6 +20,7 @@ declare const ConfigSchema: z.ZodObject<{
|
|
|
18
20
|
defaultSender: z.ZodOptional<z.ZodString>;
|
|
19
21
|
endpoint: z.ZodOptional<z.ZodString>;
|
|
20
22
|
maxResponseBytes: z.ZodOptional<z.ZodNumber>;
|
|
23
|
+
pollIntervalMs: z.ZodOptional<z.ZodNumber>;
|
|
21
24
|
}, z.core.$strip>;
|
|
22
25
|
/** Private connector credentials resolved by the host. */
|
|
23
26
|
interface Credentials {
|
|
@@ -63,7 +66,7 @@ interface Message {
|
|
|
63
66
|
/** To is the recipient in E.164 form, or a whatsapp: address. */
|
|
64
67
|
"to": string;
|
|
65
68
|
/** Status is Twilio's delivery status. */
|
|
66
|
-
"status"?: "accepted" | "canceled" | "delivered" | "failed" | "queued" | "read" | "scheduled" | "sending" | "sent" | "undelivered" | (string & {}) | undefined;
|
|
69
|
+
"status"?: "accepted" | "canceled" | "delivered" | "failed" | "queued" | "read" | "received" | "receiving" | "scheduled" | "sending" | "sent" | "undelivered" | (string & {}) | undefined;
|
|
67
70
|
/** Direction is Twilio's direction value, such as outbound-api. */
|
|
68
71
|
"direction"?: string | undefined;
|
|
69
72
|
/** ErrorCode is Twilio's numeric error code, documented at https://www.twilio.com/docs/api/errors; zero means none. */
|
|
@@ -109,9 +112,9 @@ declare const MessageSchema: z.ZodObject<{
|
|
|
109
112
|
mediaCount: z.ZodOptional<z.ZodNumber>;
|
|
110
113
|
price: z.ZodOptional<z.ZodString>;
|
|
111
114
|
priceUnit: z.ZodOptional<z.ZodString>;
|
|
112
|
-
createdAt: z.
|
|
113
|
-
sentAt: z.
|
|
114
|
-
updatedAt: z.
|
|
115
|
+
createdAt: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
116
|
+
sentAt: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
117
|
+
updatedAt: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
115
118
|
}, z.core.$strict>;
|
|
116
119
|
/** Runtime validator for GetMessageInput. */
|
|
117
120
|
declare const GetMessageInputSchema: z.ZodObject<{
|
package/dist/index.d.ts
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
import { ProviderRequest, ProviderResponse } from '@superdurable/connectors-sdk/providerhttp';
|
|
2
2
|
import * as _superdurable_connectors_sdk from '@superdurable/connectors-sdk';
|
|
3
|
-
import { Query, Mutation, Call, MutationAttempt, QueryAttempt, CredentialProvider, Failure, ReceiptDraft, QueryStepConfig, QueryResult, QueryStep, MutationStepConfig, MutationResult, MutationStep, QueryDefinition, MutationDefinition } from '@superdurable/connectors-sdk';
|
|
4
|
-
import { G as GetMessageInput, M as Message, S as SendMessageInput, C as Config, a as Credentials, b as Connection } from './connection-
|
|
5
|
-
export { c as ConfigSchema, d as GetMessageInputSchema, e as MessageSchema, f as SendMessageInputSchema, g as decodeCredentials, n as newConnectionWithOperations } from './connection-
|
|
3
|
+
import { Query, Mutation, Call, MutationAttempt, QueryAttempt, CredentialProvider, Failure, ReceiptDraft, QueryStepConfig, QueryResult, QueryStep, MutationStepConfig, MutationResult, MutationStep, QueryDefinition, MutationDefinition, ConnectorConfigurationUI, TriggerTarget, TriggerLogger, TriggerDefinition, TriggerBindingDefinition, TriggerRunner } from '@superdurable/connectors-sdk';
|
|
4
|
+
import { G as GetMessageInput, M as Message, S as SendMessageInput, C as Config, a as Credentials, b as Connection } from './connection-BQ9-3dhC.js';
|
|
5
|
+
export { c as ConfigSchema, d as GetMessageInputSchema, e as MessageSchema, f as SendMessageInputSchema, g as decodeCredentials, n as newConnectionWithOperations } from './connection-BQ9-3dhC.js';
|
|
6
6
|
import { LoadedProject } from '@superdurable/connectors-sdk/projectconfig';
|
|
7
7
|
import { StepTarget } from '@superdurable/dex';
|
|
8
|
-
import '
|
|
8
|
+
import { CursorStore, Runner } from '@superdurable/connectors-sdk/pollingtrigger';
|
|
9
|
+
import { z } from 'zod';
|
|
9
10
|
|
|
10
11
|
/** Send one Twilio message behind a durable single-dispatch fence. */
|
|
11
12
|
declare class SendMessageOperation implements Mutation<SendMessageInput, Message> {
|
|
12
13
|
private readonly client;
|
|
13
14
|
/** Bind one client. */ constructor(client: TwilioClient);
|
|
14
|
-
/** Stable manifest definition. */ definition(): _superdurable_connectors_sdk.
|
|
15
|
+
/** Stable manifest definition. */ definition(): _superdurable_connectors_sdk.MutationDefinition;
|
|
15
16
|
/** Receipt identity only; Twilio does not accept an idempotency header. */ idempotencyKey(callId: string): string;
|
|
16
17
|
/** Classify one fenced provider attempt. */
|
|
17
18
|
invoke(call: Call, input: SendMessageInput): Promise<MutationAttempt<Message>>;
|
|
@@ -64,6 +65,7 @@ declare class TwilioClient {
|
|
|
64
65
|
/** Fully qualified Messages collection URL. */ readonly messagesURL: string;
|
|
65
66
|
/** Optional default sender. */ readonly defaultSender: MessageSender;
|
|
66
67
|
/** Maximum successful response size. */ readonly maxResponseBytes: number;
|
|
68
|
+
/** Delay between messageReceived polls in milliseconds: pollIntervalMs, 30000 when omitted or zero, at least 5000. */ readonly pollIntervalMs: number;
|
|
67
69
|
private readonly credentials;
|
|
68
70
|
private readonly send;
|
|
69
71
|
private readonly now;
|
|
@@ -81,10 +83,18 @@ declare class TwilioClient {
|
|
|
81
83
|
exchange(call: Call, authorization: TwilioAuthorization, method: string, url: string, form?: URLSearchParams, signal?: AbortSignal): Promise<TwilioExchange>;
|
|
82
84
|
/** Decode a safe Twilio Message subset. */
|
|
83
85
|
decodeMessage(body: Uint8Array, authorization: TwilioAuthorization): Message;
|
|
86
|
+
/**
|
|
87
|
+
* Validate one decoded Message resource of this account and keep its safe view. rawIntegerTokens holds the
|
|
88
|
+
* source text of numeric count fields from parseTwilioJSON. Throws TypeError for another account, a
|
|
89
|
+
* malformed field, or a field that reflects the credential.
|
|
90
|
+
*/
|
|
91
|
+
convertMessageResource(value: unknown, rawIntegerTokens: WeakMap<object, Map<string, string>>, authorization: TwilioAuthorization): Message;
|
|
84
92
|
/** Make a safe receipt with exact provider IDs. */
|
|
85
93
|
receipt(call: Call, response?: ProviderResponse, objectId?: string, errorCode?: number): ReceiptDraft;
|
|
86
94
|
/** Current receipt time for Retry-After. */ currentTime(): Date;
|
|
87
95
|
}
|
|
96
|
+
/** Whether a value is an E.164 phone number such as +14155550100. */
|
|
97
|
+
declare function isE164PhoneNumber(value: string): boolean;
|
|
88
98
|
|
|
89
99
|
/** Bind a validated Twilio client to a static connection. */
|
|
90
100
|
declare function newConnection(client: TwilioClient, name: string): Connection;
|
|
@@ -152,4 +162,122 @@ declare const GetMessageBranch: {
|
|
|
152
162
|
/** Manifest definition for getMessage. */
|
|
153
163
|
declare const GetMessageDefinition: QueryDefinition;
|
|
154
164
|
|
|
155
|
-
|
|
165
|
+
/** Twilio's direction value for a message the account received. */
|
|
166
|
+
declare const InboundMessageDirection = "inbound";
|
|
167
|
+
/** Twilio received an inbound message and is still processing it, such as fetching MMS media. */
|
|
168
|
+
declare const MessageStatusReceiving = "receiving";
|
|
169
|
+
/** Twilio finished processing an inbound message. */
|
|
170
|
+
declare const MessageStatusReceived = "received";
|
|
171
|
+
/** Receiving address UI unit, which saves to. */ declare const UIUnitReceivingAddressInput = "receivingAddressInput";
|
|
172
|
+
/** Receiving address output port. */ declare const UIReceivingAddressInputPortTo = "to";
|
|
173
|
+
/**
|
|
174
|
+
* The messageReceived binding configuration the receivingAddressInput unit saves in Dex Web. to is the
|
|
175
|
+
* receiving Twilio number in E.164 form, such as +14155550100, or a WhatsApp sender written
|
|
176
|
+
* whatsapp:+14155550100; blank receives every inbound message of the connection's account. Changing it for a
|
|
177
|
+
* binding that already polled makes its next poll record a new baseline.
|
|
178
|
+
*/
|
|
179
|
+
declare const MessageReceivedTriggerConfigurationSchema: z.ZodObject<{
|
|
180
|
+
to: z.ZodOptional<z.ZodString>;
|
|
181
|
+
}, z.core.$strict>;
|
|
182
|
+
/** The receiving address one messageReceived binding watches. */
|
|
183
|
+
type MessageReceivedTriggerConfiguration = z.infer<typeof MessageReceivedTriggerConfigurationSchema>;
|
|
184
|
+
/**
|
|
185
|
+
* One inbound message read from the Twilio Messages list; field names match the Go connector. Unlike
|
|
186
|
+
* operation results, it carries the message text, because acting on an inbound message needs it. Media URLs,
|
|
187
|
+
* Twilio error text, and credentials are never included. The Trigger event ID is "twilio-message-" followed by
|
|
188
|
+
* the message SID.
|
|
189
|
+
*/
|
|
190
|
+
declare const MessageReceivedEventSchema: z.ZodObject<{
|
|
191
|
+
message: z.ZodObject<{
|
|
192
|
+
sid: z.ZodOptional<z.ZodString>;
|
|
193
|
+
accountSid: z.ZodString;
|
|
194
|
+
messagingServiceSid: z.ZodOptional<z.ZodString>;
|
|
195
|
+
from: z.ZodOptional<z.ZodString>;
|
|
196
|
+
to: z.ZodString;
|
|
197
|
+
status: z.ZodOptional<z.ZodString>;
|
|
198
|
+
direction: z.ZodOptional<z.ZodString>;
|
|
199
|
+
errorCode: z.ZodOptional<z.ZodNumber>;
|
|
200
|
+
segmentCount: z.ZodOptional<z.ZodNumber>;
|
|
201
|
+
mediaCount: z.ZodOptional<z.ZodNumber>;
|
|
202
|
+
price: z.ZodOptional<z.ZodString>;
|
|
203
|
+
priceUnit: z.ZodOptional<z.ZodString>;
|
|
204
|
+
createdAt: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
205
|
+
sentAt: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
206
|
+
updatedAt: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
207
|
+
}, z.core.$strict>;
|
|
208
|
+
body: z.ZodOptional<z.ZodString>;
|
|
209
|
+
}, z.core.$strict>;
|
|
210
|
+
/** One inbound message. */
|
|
211
|
+
type MessageReceivedEvent = z.infer<typeof MessageReceivedEventSchema>;
|
|
212
|
+
/** Manifest definition of messageReceived. */
|
|
213
|
+
declare const MessageReceivedTriggerDefinition: TriggerDefinition;
|
|
214
|
+
/** One static application binding of messageReceived. */
|
|
215
|
+
interface MessageReceivedTriggerBindingConfig {
|
|
216
|
+
/** Static connection name. */ connectionName: string;
|
|
217
|
+
/** Static binding name. */ bindingName: string;
|
|
218
|
+
/** Connector Studio configuration units for the binding, such as the receivingAddressInput unit. */ configurationUI: ConnectorConfigurationUI;
|
|
219
|
+
}
|
|
220
|
+
/** Declare a static messageReceived binding for Flow Definition tooling and Dex Web. */
|
|
221
|
+
declare function defineMessageReceivedTriggerBinding(config: MessageReceivedTriggerBindingConfig): TriggerBindingDefinition;
|
|
222
|
+
/** Decode a replayed message, including one a Go replica recorded. */
|
|
223
|
+
declare function decodeMessageReceivedPayload(_payloadJSON: string, payloadBytes: Uint8Array): MessageReceivedEvent;
|
|
224
|
+
/** Binds one messageReceived configuration to its application target and cursor. */
|
|
225
|
+
interface MessageReceivedTriggerRoute {
|
|
226
|
+
/** The stable application binding name, unique within the runner. */ bindingName: string;
|
|
227
|
+
/** Selects the receiving address; blank receives every inbound message of the account. */ configuration: MessageReceivedTriggerConfiguration;
|
|
228
|
+
/**
|
|
229
|
+
* Routes each inbound message into the application. A target from newDurableTriggerTarget records each
|
|
230
|
+
* message before the cursor commits past it; any other target consumes it first.
|
|
231
|
+
*/
|
|
232
|
+
target: TriggerTarget<MessageReceivedEvent>;
|
|
233
|
+
/**
|
|
234
|
+
* Stores the binding's DateSent watermark and delivered-message snapshot, such as LoadedProject.pollCursorStore.
|
|
235
|
+
* Omitted keeps it in memory, so every process start records a new baseline and messages received while
|
|
236
|
+
* stopped are lost.
|
|
237
|
+
*/
|
|
238
|
+
cursor?: CursorStore | undefined;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Create one poll runner for the messageReceived bindings polled through one connection. run replays each
|
|
242
|
+
* durable target, records a baseline for a binding without a cursor, then lists each binding's Messages each
|
|
243
|
+
* pollInterval with jitter. A cursor for another account or receiving address records a new baseline and logs
|
|
244
|
+
* a WARN record; messages received between the last poll and the new baseline are not delivered. A 429 pauses
|
|
245
|
+
* every binding of the connection for Retry-After, or backs off exponentially without it; other failures back
|
|
246
|
+
* off per binding up to 15 minutes. Delivery is at least once, and each message keeps one Trigger event ID,
|
|
247
|
+
* from its SID, across refetches. logger receives records with binding identity, never message bodies,
|
|
248
|
+
* addresses, or credentials. Throws for no routes, a blank or repeated binding name, a missing target, an
|
|
249
|
+
* invalid configuration, or a mock connection.
|
|
250
|
+
*/
|
|
251
|
+
declare function newMessageTriggerRunner(connection: Connection, routes: MessageReceivedTriggerRoute[], logger?: TriggerLogger): Runner;
|
|
252
|
+
/** Selects one messageReceived binding saved in the project configuration. */
|
|
253
|
+
interface ProjectMessageReceivedTriggerRoute {
|
|
254
|
+
/** The saved binding's name. */ bindingName: string;
|
|
255
|
+
/** Routes each inbound message into the application, usually newDexFlowTriggerTarget. */ target: TriggerTarget<MessageReceivedEvent>;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Create a durable runner for messageReceived bindings saved in the loaded project. connection is the
|
|
259
|
+
* project's connection from newProjectConnection; the caller shares it with the Flow. Each binding's saved
|
|
260
|
+
* receiving address is loaded (an unsaved binding receives every inbound message of the account), and each
|
|
261
|
+
* route records messages in its binding's project Trigger inbox before its watermark commits in the binding's
|
|
262
|
+
* project poll cursor, so a restarted or replaced replica neither misses nor repeats a message. logger also
|
|
263
|
+
* receives the inboxes' records. Throws for an invalid saved configuration or route, as newMessageTriggerRunner does.
|
|
264
|
+
*/
|
|
265
|
+
declare function newProjectMessageTriggerRunner(project: LoadedProject, connection: Connection, routes: ProjectMessageReceivedTriggerRoute[], logger?: TriggerLogger): Runner;
|
|
266
|
+
/** Configuration of one messageReceived Trigger with an in-memory cursor. */
|
|
267
|
+
interface MessageReceivedTriggerConfig {
|
|
268
|
+
/** Twilio connection from newProjectConnection or newConnection. */ connection: Connection;
|
|
269
|
+
/** Static connection name; must equal the connection's name. */ connectionName: string;
|
|
270
|
+
/** Static binding name. */ bindingName: string;
|
|
271
|
+
/** The receiving address; blank receives every inbound message. */ configuration: MessageReceivedTriggerConfiguration;
|
|
272
|
+
/** Routes accepted events into the application. */ target: TriggerTarget<MessageReceivedEvent>;
|
|
273
|
+
/** Receives the runner's records; omitted uses defaultTriggerLogger. */ logger?: TriggerLogger | undefined;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Create one messageReceived binding's TriggerRunner, as Go's generated NewMessageReceivedTrigger does. It has
|
|
277
|
+
* no project storage, so it keeps the cursor in memory and records a new baseline on every start; use
|
|
278
|
+
* newProjectMessageTriggerRunner for a durable cursor and inbox. Throws for a mismatched connection name, an
|
|
279
|
+
* invalid configuration, or a mock connection.
|
|
280
|
+
*/
|
|
281
|
+
declare function newMessageReceivedTrigger(config: MessageReceivedTriggerConfig): TriggerRunner;
|
|
282
|
+
|
|
283
|
+
export { Config, Connection, Credentials, GetMessageBranch, GetMessageDefinition, GetMessageInput, GetMessageOperation, InboundMessageDirection, Message, type MessageReceivedEvent, MessageReceivedEventSchema, type MessageReceivedTriggerBindingConfig, type MessageReceivedTriggerConfig, type MessageReceivedTriggerConfiguration, MessageReceivedTriggerConfigurationSchema, MessageReceivedTriggerDefinition, type MessageReceivedTriggerRoute, MessageStatusReceived, MessageStatusReceiving, type ProjectMessageReceivedTriggerRoute, SendMessageBranch, SendMessageDefinition, SendMessageInput, SendMessageOperation, TwilioClient, type TwilioClientOptions, type TwilioRequestSender, UIReceivingAddressInputPortTo, UIUnitReceivingAddressInput, decodeMessageReceivedPayload, defineMessageReceivedTriggerBinding, isE164PhoneNumber, newConnection, newGetMessageStep, newMessageReceivedTrigger, newMessageTriggerRunner, newProjectConnection, newProjectMessageTriggerRunner, newSendMessageStep };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ConfigSchema,
|
|
3
3
|
Connection,
|
|
4
|
+
ConnectorID,
|
|
4
5
|
GetMessageBranch,
|
|
5
6
|
GetMessageDefinition,
|
|
6
7
|
GetMessageInputSchema,
|
|
@@ -11,7 +12,7 @@ import {
|
|
|
11
12
|
decodeCredentials,
|
|
12
13
|
newConnection,
|
|
13
14
|
newConnectionWithOperations
|
|
14
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-6KLMYDTX.js";
|
|
15
16
|
|
|
16
17
|
// src/client.ts
|
|
17
18
|
import { AddressRefusal, BodyTooLargeError, MaxErrorBodyBytes, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, readErrorTokens, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
|
|
@@ -212,6 +213,8 @@ var zeroTime = "0001-01-01T00:00:00Z";
|
|
|
212
213
|
var defaultEndpoint = "https://api.twilio.com/2010-04-01";
|
|
213
214
|
var defaultMaxResponseBytes = 1048576;
|
|
214
215
|
var requestTimeoutMs = 2e4;
|
|
216
|
+
var defaultPollIntervalMs = 3e4;
|
|
217
|
+
var minimumPollIntervalMs = 5e3;
|
|
215
218
|
var staticCredentialRefresh = {
|
|
216
219
|
refreshRequired: () => false,
|
|
217
220
|
refresh: async () => {
|
|
@@ -227,6 +230,8 @@ var TwilioClient = class {
|
|
|
227
230
|
defaultSender;
|
|
228
231
|
/** Maximum successful response size. */
|
|
229
232
|
maxResponseBytes;
|
|
233
|
+
/** Delay between messageReceived polls in milliseconds: pollIntervalMs, 30000 when omitted or zero, at least 5000. */
|
|
234
|
+
pollIntervalMs;
|
|
230
235
|
credentials;
|
|
231
236
|
send;
|
|
232
237
|
now;
|
|
@@ -241,6 +246,8 @@ var TwilioClient = class {
|
|
|
241
246
|
this.addressPolicy = "privateNetworkHTTP";
|
|
242
247
|
this.maxResponseBytes = config.maxResponseBytes || defaultMaxResponseBytes;
|
|
243
248
|
if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0) throw new TypeError("Twilio maxResponseBytes must be positive");
|
|
249
|
+
this.pollIntervalMs = config.pollIntervalMs || defaultPollIntervalMs;
|
|
250
|
+
if (!Number.isSafeInteger(this.pollIntervalMs) || this.pollIntervalMs < minimumPollIntervalMs) throw new TypeError("Twilio pollInterval must be at least 5s");
|
|
244
251
|
this.defaultSender = config.defaultSender?.trim() ? parseSender(config.defaultSender) : { fromAddress: "", messagingServiceSid: "" };
|
|
245
252
|
if (!credentials) throw new TypeError("credential provider is required");
|
|
246
253
|
this.credentials = credentials;
|
|
@@ -320,35 +327,32 @@ var TwilioClient = class {
|
|
|
320
327
|
}
|
|
321
328
|
/** Decode a safe Twilio Message subset. */
|
|
322
329
|
decodeMessage(body, authorization) {
|
|
323
|
-
let
|
|
324
|
-
const rawIntegerTokens = /* @__PURE__ */ new WeakMap();
|
|
325
|
-
const parseWithSource = JSON.parse;
|
|
330
|
+
let parsed;
|
|
326
331
|
try {
|
|
327
|
-
|
|
328
|
-
if (key === "error_code" || key === "num_segments" || key === "num_media") {
|
|
329
|
-
let tokens = rawIntegerTokens.get(this);
|
|
330
|
-
if (!tokens) {
|
|
331
|
-
tokens = /* @__PURE__ */ new Map();
|
|
332
|
-
rawIntegerTokens.set(this, tokens);
|
|
333
|
-
}
|
|
334
|
-
tokens.set(key, context.source ?? "");
|
|
335
|
-
}
|
|
336
|
-
return value;
|
|
337
|
-
});
|
|
332
|
+
parsed = parseTwilioJSON(Buffer.from(body).toString("utf8"));
|
|
338
333
|
} catch {
|
|
339
334
|
throw new TypeError("Twilio returned an invalid message");
|
|
340
335
|
}
|
|
336
|
+
return this.convertMessageResource(parsed.value, parsed.rawIntegerTokens, authorization);
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Validate one decoded Message resource of this account and keep its safe view. rawIntegerTokens holds the
|
|
340
|
+
* source text of numeric count fields from parseTwilioJSON. Throws TypeError for another account, a
|
|
341
|
+
* malformed field, or a field that reflects the credential.
|
|
342
|
+
*/
|
|
343
|
+
convertMessageResource(value, rawIntegerTokens, authorization) {
|
|
344
|
+
const resource = value;
|
|
341
345
|
if (!resource || typeof resource !== "object" || Array.isArray(resource)) throw new TypeError("Twilio returned an invalid message");
|
|
342
346
|
const required = (key) => {
|
|
343
|
-
const
|
|
344
|
-
if (typeof
|
|
345
|
-
return
|
|
347
|
+
const value2 = resource[key];
|
|
348
|
+
if (typeof value2 !== "string") throw new TypeError("Twilio returned an invalid message");
|
|
349
|
+
return value2;
|
|
346
350
|
};
|
|
347
351
|
const optional = (key) => {
|
|
348
|
-
const
|
|
349
|
-
if (
|
|
350
|
-
if (typeof
|
|
351
|
-
return
|
|
352
|
+
const value2 = resource[key];
|
|
353
|
+
if (value2 == null) return "";
|
|
354
|
+
if (typeof value2 !== "string") throw new TypeError("Twilio returned an invalid message");
|
|
355
|
+
return value2;
|
|
352
356
|
};
|
|
353
357
|
const sid = required("sid");
|
|
354
358
|
const accountSid = required("account_sid");
|
|
@@ -376,15 +380,15 @@ var TwilioClient = class {
|
|
|
376
380
|
.../^[A-Z]{3}$/.test(priceUnit) ? { priceUnit } : {}
|
|
377
381
|
};
|
|
378
382
|
for (const [key, target] of [["error_code", "errorCode"], ["num_segments", "segmentCount"], ["num_media", "mediaCount"]]) {
|
|
379
|
-
const
|
|
380
|
-
if (
|
|
381
|
-
const decimalText = typeof
|
|
382
|
-
if (typeof
|
|
383
|
-
const count = Number(
|
|
383
|
+
const value2 = resource[key];
|
|
384
|
+
if (value2 !== null && value2 !== void 0) {
|
|
385
|
+
const decimalText = typeof value2 === "number" ? rawIntegerTokens.get(resource)?.get(key) : value2;
|
|
386
|
+
if (typeof value2 !== "string" && typeof value2 !== "number" || value2 !== "" && !/^[0-9]{1,9}$/.test(String(decimalText))) throw new TypeError("Twilio returned an invalid message");
|
|
387
|
+
const count = Number(value2);
|
|
384
388
|
if (count !== 0) message[target] = count;
|
|
385
389
|
}
|
|
386
390
|
}
|
|
387
|
-
if ([message.sid, message.accountSid, message.messagingServiceSid, message.from, message.to, message.status, message.direction, message.price, message.priceUnit].some((
|
|
391
|
+
if ([message.sid, message.accountSid, message.messagingServiceSid, message.from, message.to, message.status, message.direction, message.price, message.priceUnit].some((value2) => value2 !== void 0 && value2.includes(authorization.password))) throw new TypeError("Twilio returned an invalid message");
|
|
388
392
|
return message;
|
|
389
393
|
}
|
|
390
394
|
/** Make a safe receipt with exact provider IDs. */
|
|
@@ -406,6 +410,25 @@ var TwilioClient = class {
|
|
|
406
410
|
return this.now();
|
|
407
411
|
}
|
|
408
412
|
};
|
|
413
|
+
function parseTwilioJSON(text) {
|
|
414
|
+
const rawIntegerTokens = /* @__PURE__ */ new WeakMap();
|
|
415
|
+
const parseWithSource = JSON.parse;
|
|
416
|
+
const value = parseWithSource(text, function(key, value2, context) {
|
|
417
|
+
if (key === "error_code" || key === "num_segments" || key === "num_media") {
|
|
418
|
+
let tokens = rawIntegerTokens.get(this);
|
|
419
|
+
if (!tokens) {
|
|
420
|
+
tokens = /* @__PURE__ */ new Map();
|
|
421
|
+
rawIntegerTokens.set(this, tokens);
|
|
422
|
+
}
|
|
423
|
+
tokens.set(key, context.source ?? "");
|
|
424
|
+
}
|
|
425
|
+
return value2;
|
|
426
|
+
});
|
|
427
|
+
return { value, rawIntegerTokens };
|
|
428
|
+
}
|
|
429
|
+
function isE164PhoneNumber(value) {
|
|
430
|
+
return phonePattern.test(value);
|
|
431
|
+
}
|
|
409
432
|
function twilioFailure(operation, kind, message) {
|
|
410
433
|
return { kind, provider: "twilio", operation, message };
|
|
411
434
|
}
|
|
@@ -497,8 +520,16 @@ function newConnection2(client, name) {
|
|
|
497
520
|
function newProjectConnection(project, connectionName, options = {}) {
|
|
498
521
|
const selected = project.configuration.connections.find((entry) => entry.connectorId === "twilio-messaging" && entry.connectionName === connectionName);
|
|
499
522
|
if (!selected || selected.provider !== "twilio") throw new TypeError("Twilio project connection is not configured");
|
|
500
|
-
const settings = z.object({
|
|
501
|
-
|
|
523
|
+
const settings = z.object({
|
|
524
|
+
accountSid: z.string(),
|
|
525
|
+
defaultSender: z.string().optional(),
|
|
526
|
+
endpoint: z.string().optional(),
|
|
527
|
+
maxResponseBytes: z.number().int().optional(),
|
|
528
|
+
// pollInterval is a Go time.Duration in integer nanoseconds, as Go's json.Unmarshal reads it; zero keeps the default.
|
|
529
|
+
pollInterval: z.number().int().safe().optional()
|
|
530
|
+
}).parse(selected.configuration);
|
|
531
|
+
const { pollInterval, ...configured } = settings;
|
|
532
|
+
const config = ConfigSchema.parse({ ...configured, ...pollInterval ? { pollIntervalMs: Math.ceil(pollInterval / 1e6) } : {} });
|
|
502
533
|
const credentialProvider = newCredentialProvider(project.connections, { connectorId: "twilio-messaging", connectionName }, decodeCredentials);
|
|
503
534
|
return newConnection2(new TwilioClient(config, credentialProvider, options), connectionName);
|
|
504
535
|
}
|
|
@@ -526,6 +557,404 @@ function newGetMessageStep(configuration) {
|
|
|
526
557
|
...defect ? [goToBranch("defect", defect)] : []
|
|
527
558
|
] });
|
|
528
559
|
}
|
|
560
|
+
|
|
561
|
+
// src/trigger.ts
|
|
562
|
+
import {
|
|
563
|
+
mustTriggerBindingDefinition,
|
|
564
|
+
newTrigger
|
|
565
|
+
} from "@superdurable/connectors-sdk";
|
|
566
|
+
import { newBindingPoller, newBindingTriggerSource, newMemoryCursorStore, newRunner } from "@superdurable/connectors-sdk/pollingtrigger";
|
|
567
|
+
import { ObjectNotFoundError, decodeTriggerConfiguration, newDurableTriggerTarget, parseTriggerPayloadJSON } from "@superdurable/connectors-sdk/projectconfig";
|
|
568
|
+
import { z as z2 } from "zod";
|
|
569
|
+
|
|
570
|
+
// src/inbound_message_fetcher.ts
|
|
571
|
+
import { createHash } from "crypto";
|
|
572
|
+
import {
|
|
573
|
+
MaxChangesPerPage,
|
|
574
|
+
applyKeyedSnapshotChanges,
|
|
575
|
+
markCursorInvalid,
|
|
576
|
+
markRateLimited,
|
|
577
|
+
newTriggerCredentialCall,
|
|
578
|
+
waitForPollRequest
|
|
579
|
+
} from "@superdurable/connectors-sdk/pollingtrigger";
|
|
580
|
+
import { encodeGoJSONValue } from "@superdurable/connectors-sdk/projectconfig";
|
|
581
|
+
var inboundListPageSize = 200;
|
|
582
|
+
var maximumWindowPages = 10;
|
|
583
|
+
var maximumWindowNarrowings = 34;
|
|
584
|
+
var inboundLookbackSeconds = 120;
|
|
585
|
+
var receivingHoldLimitMs = 10 * 6e4;
|
|
586
|
+
var zeroTime2 = "0001-01-01T00:00:00Z";
|
|
587
|
+
var int64Minimum = -(2n ** 63n);
|
|
588
|
+
var int64Maximum = 2n ** 63n - 1n;
|
|
589
|
+
var loneSurrogatePattern = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
|
|
590
|
+
var resourceStringFields = ["sid", "account_sid", "messaging_service_sid", "from", "to", "status", "direction", "price", "price_unit", "date_created", "date_sent", "date_updated", "body"];
|
|
591
|
+
var inboundSnapshotOptions = {};
|
|
592
|
+
function messageReceivedEventId(messageSid) {
|
|
593
|
+
return `twilio-message-${messageSid}`;
|
|
594
|
+
}
|
|
595
|
+
function newMessageReceivedTriggerEvent(message, body, now) {
|
|
596
|
+
const dated = [message.sentAt, message.createdAt].find((value) => value !== zeroTime2);
|
|
597
|
+
const occurredAt = dated === void 0 ? now : new Date(dated);
|
|
598
|
+
return { id: messageReceivedEventId(message.sid ?? ""), occurredAt, payload: { message: MessageSchema.parse(message), ...body ? { body } : {} } };
|
|
599
|
+
}
|
|
600
|
+
var InboundSnapshotKey = class {
|
|
601
|
+
/** Wrap one dated message key. */
|
|
602
|
+
constructor(key) {
|
|
603
|
+
this.key = key;
|
|
604
|
+
}
|
|
605
|
+
key;
|
|
606
|
+
/** The dated message key. */
|
|
607
|
+
snapshotKey() {
|
|
608
|
+
return this.key;
|
|
609
|
+
}
|
|
610
|
+
/** A hash of the key; a delivered message never changes its entry. */
|
|
611
|
+
snapshotHash() {
|
|
612
|
+
return createHash("sha256").update(this.key, "utf8").digest("hex").slice(0, 16);
|
|
613
|
+
}
|
|
614
|
+
/** Undefined because entries keep no values. */
|
|
615
|
+
snapshotValue() {
|
|
616
|
+
return void 0;
|
|
617
|
+
}
|
|
618
|
+
};
|
|
619
|
+
function inboundSnapshotKeyFor(listed) {
|
|
620
|
+
const second = listed.sentAtSecond < 0 ? `-${String(-listed.sentAtSecond).padStart(10, "0")}` : String(listed.sentAtSecond).padStart(11, "0");
|
|
621
|
+
return `${second}-${listed.message.sid ?? ""}`;
|
|
622
|
+
}
|
|
623
|
+
function inboundSnapshotKeySecond(key) {
|
|
624
|
+
const separator = key.indexOf("-");
|
|
625
|
+
if (separator < 0) return void 0;
|
|
626
|
+
const prefix = key.slice(0, separator);
|
|
627
|
+
if (!/^[+-]?[0-9]+$/.test(prefix)) return void 0;
|
|
628
|
+
const second = BigInt(prefix);
|
|
629
|
+
return second < int64Minimum || second > int64Maximum ? void 0 : Number(second);
|
|
630
|
+
}
|
|
631
|
+
function latestSentAtSecond(messages) {
|
|
632
|
+
return messages.reduce((latest, listed) => Math.max(latest, listed.sentAtSecond), 0);
|
|
633
|
+
}
|
|
634
|
+
function unixSecond(moment) {
|
|
635
|
+
return Math.floor(moment.getTime() / 1e3);
|
|
636
|
+
}
|
|
637
|
+
function formatRFC3339Second(second) {
|
|
638
|
+
return new Date(second * 1e3).toISOString().replace(".000Z", "Z");
|
|
639
|
+
}
|
|
640
|
+
function goQueryEscape(value) {
|
|
641
|
+
return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, "+");
|
|
642
|
+
}
|
|
643
|
+
function encodeGoQuery(query) {
|
|
644
|
+
return Object.keys(query).sort().map((name) => `${goQueryEscape(name)}=${goQueryEscape(query[name] ?? "")}`).join("&");
|
|
645
|
+
}
|
|
646
|
+
function decodeInboundMessageCursorToken(token) {
|
|
647
|
+
const watermarkSources = /* @__PURE__ */ new Map();
|
|
648
|
+
let position;
|
|
649
|
+
try {
|
|
650
|
+
const parseWithSource = JSON.parse;
|
|
651
|
+
position = parseWithSource(token, function(key, value, context) {
|
|
652
|
+
if (key.toLowerCase() === "watermark" && typeof value === "number") watermarkSources.set(this, context.source ?? "");
|
|
653
|
+
return value;
|
|
654
|
+
});
|
|
655
|
+
} catch {
|
|
656
|
+
return void 0;
|
|
657
|
+
}
|
|
658
|
+
if (position === null || typeof position !== "object" || Array.isArray(position)) return void 0;
|
|
659
|
+
let accountSid = "", to = "", watermark = 0;
|
|
660
|
+
for (const [name, value] of Object.entries(position)) {
|
|
661
|
+
const fieldName = name.toLowerCase();
|
|
662
|
+
if (value === null || !["accountsid", "to", "watermark"].includes(fieldName)) continue;
|
|
663
|
+
if (fieldName === "watermark") {
|
|
664
|
+
const source = watermarkSources.get(position) ?? "";
|
|
665
|
+
if (typeof value !== "number" || !/^-?(0|[1-9][0-9]*)$/.test(source)) return void 0;
|
|
666
|
+
const parsed = BigInt(source);
|
|
667
|
+
if (parsed < int64Minimum || parsed > int64Maximum) return void 0;
|
|
668
|
+
watermark = Number(parsed);
|
|
669
|
+
} else if (typeof value !== "string") return void 0;
|
|
670
|
+
else if (fieldName === "accountsid") accountSid = value;
|
|
671
|
+
else to = value;
|
|
672
|
+
}
|
|
673
|
+
return watermark > 0 ? { accountSid, to, watermark } : void 0;
|
|
674
|
+
}
|
|
675
|
+
var InboundMessageFetcher = class {
|
|
676
|
+
/** Bind the client, the connection whose credential each request uses, and the receiving address. */
|
|
677
|
+
constructor(client, connection, to) {
|
|
678
|
+
this.client = client;
|
|
679
|
+
this.connection = connection;
|
|
680
|
+
this.to = to;
|
|
681
|
+
}
|
|
682
|
+
client;
|
|
683
|
+
connection;
|
|
684
|
+
to;
|
|
685
|
+
/** List the lookback before now and record every inbound message in it as already delivered. */
|
|
686
|
+
async seedCursor(context) {
|
|
687
|
+
const now = unixSecond(this.client.currentTime());
|
|
688
|
+
const since = now - inboundLookbackSeconds;
|
|
689
|
+
const window = await this.listWindow(context, since, 0);
|
|
690
|
+
if (window.upperBound !== 0) throw new Error(`Twilio listed more than ${inboundListPageSize * maximumWindowPages} messages within the baseline lookback`);
|
|
691
|
+
const watermark = Math.max(now, latestSentAtSecond(window.messages));
|
|
692
|
+
const delivered = window.messages.filter((listed) => this.isReceivedHere(listed) && listed.sentAtSecond >= since).map((listed) => new InboundSnapshotKey(inboundSnapshotKeyFor(listed)));
|
|
693
|
+
return this.encodeCursor(watermark, void 0, delivered);
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Return, oldest first, up to MaxChangesPerPage inbound messages dated from the watermark minus the lookback.
|
|
697
|
+
* A message still in receiving holds the watermark until received or ten minutes old. An undecodable cursor,
|
|
698
|
+
* or one for another account or receiving address, is marked invalid.
|
|
699
|
+
*/
|
|
700
|
+
async fetchChanges(context, cursor) {
|
|
701
|
+
const position = decodeInboundMessageCursorToken(cursor.token);
|
|
702
|
+
if (!position) throw markCursorInvalid(new Error("Twilio messageReceived cursor is not decodable"));
|
|
703
|
+
if (position.accountSid !== this.client.accountSid || position.to !== this.to) throw markCursorInvalid(new Error("Twilio messageReceived cursor belongs to another account or receiving address"));
|
|
704
|
+
const since = position.watermark - inboundLookbackSeconds;
|
|
705
|
+
const window = await this.listWindow(context, since, position.watermark + 1);
|
|
706
|
+
const now = this.client.currentTime();
|
|
707
|
+
const delivered = new Set((cursor.snapshot?.entries ?? []).map((entry) => entry.key));
|
|
708
|
+
let holdBound = 0;
|
|
709
|
+
const holdAt = (second) => {
|
|
710
|
+
if (holdBound === 0 || second < holdBound) holdBound = second;
|
|
711
|
+
};
|
|
712
|
+
let pending = [];
|
|
713
|
+
for (const listed of window.messages) {
|
|
714
|
+
if (!this.isReceivedHere(listed)) continue;
|
|
715
|
+
if (listed.sentAtSecond === 0) holdAt(position.watermark);
|
|
716
|
+
else if (listed.sentAtSecond < since || delivered.has(inboundSnapshotKeyFor(listed))) continue;
|
|
717
|
+
else if (listed.message.status === MessageStatusReceiving && now.getTime() - Date.parse(listed.message.sentAt) < receivingHoldLimitMs) holdAt(listed.sentAtSecond);
|
|
718
|
+
else pending.push(listed);
|
|
719
|
+
}
|
|
720
|
+
pending.sort((left, right) => left.sentAtSecond - right.sentAtSecond || ((left.message.sid ?? "") < (right.message.sid ?? "") ? -1 : (left.message.sid ?? "") > (right.message.sid ?? "") ? 1 : 0));
|
|
721
|
+
let watermark;
|
|
722
|
+
let hasMorePages = false;
|
|
723
|
+
const isPageFull = pending.length > MaxChangesPerPage;
|
|
724
|
+
if (isPageFull) {
|
|
725
|
+
pending = pending.slice(0, MaxChangesPerPage);
|
|
726
|
+
watermark = pending[pending.length - 1].sentAtSecond;
|
|
727
|
+
hasMorePages = true;
|
|
728
|
+
} else if (window.upperBound !== 0) {
|
|
729
|
+
watermark = window.upperBound;
|
|
730
|
+
hasMorePages = true;
|
|
731
|
+
} else watermark = latestSentAtSecond(window.messages);
|
|
732
|
+
if (holdBound !== 0 && watermark > holdBound) {
|
|
733
|
+
watermark = holdBound;
|
|
734
|
+
hasMorePages = isPageFull;
|
|
735
|
+
}
|
|
736
|
+
watermark = Math.max(watermark, position.watermark);
|
|
737
|
+
const changes = pending.map((listed) => newMessageReceivedTriggerEvent(listed.message, listed.body, now));
|
|
738
|
+
const upserted = pending.map((listed) => new InboundSnapshotKey(inboundSnapshotKeyFor(listed)));
|
|
739
|
+
return { changes, next: this.encodeCursor(watermark, cursor.snapshot, upserted), hasMorePages };
|
|
740
|
+
}
|
|
741
|
+
/** Report an inbound message to the watched address, or to any address when none is set. */
|
|
742
|
+
isReceivedHere(listed) {
|
|
743
|
+
return listed.message.direction === InboundMessageDirection && (this.to === "" || listed.message.to === this.to);
|
|
744
|
+
}
|
|
745
|
+
/** List every message dated from since, halving the upper bound toward the floor when there are too many. */
|
|
746
|
+
async listWindow(context, since, minimumUpperBound) {
|
|
747
|
+
const floor = minimumUpperBound !== 0 ? Math.max(minimumUpperBound, since) : since;
|
|
748
|
+
let span = Math.max(unixSecond(this.client.currentTime()) - floor, 0);
|
|
749
|
+
let upperBound = 0;
|
|
750
|
+
for (let narrowing = 0; narrowing <= maximumWindowNarrowings; narrowing++) {
|
|
751
|
+
const { messages, isTruncated } = await this.listMessages(context, since, upperBound);
|
|
752
|
+
if (!isTruncated) return { messages, upperBound };
|
|
753
|
+
if (upperBound === floor) break;
|
|
754
|
+
span = Math.floor(span / 2);
|
|
755
|
+
upperBound = floor + span;
|
|
756
|
+
}
|
|
757
|
+
throw new Error(`Twilio listed more than ${inboundListPageSize * maximumWindowPages} messages within 2m0s of the watermark; the messageReceived Trigger cannot page through them`);
|
|
758
|
+
}
|
|
759
|
+
/**
|
|
760
|
+
* Follow next_page_uri for at most ten pages and report whether more remain. Twilio lists newest first by
|
|
761
|
+
* DateSent, so a page reaching a message dated before since ends the listing. Bounds are inclusive and also
|
|
762
|
+
* applied locally, since Twilio documents them as dates.
|
|
763
|
+
*/
|
|
764
|
+
async listMessages(context, since, upperBound) {
|
|
765
|
+
const query = { PageSize: String(inboundListPageSize), "DateSent>": formatRFC3339Second(since) };
|
|
766
|
+
if (upperBound !== 0) query["DateSent<"] = formatRFC3339Second(upperBound);
|
|
767
|
+
if (this.to) query.To = this.to;
|
|
768
|
+
let target = `${this.client.messagesURL}.json?${encodeGoQuery(query)}`;
|
|
769
|
+
const messages = [];
|
|
770
|
+
for (let pageNumber = 0; pageNumber < maximumWindowPages; pageNumber++) {
|
|
771
|
+
const { listed, nextPageURI } = await this.listPage(context, target);
|
|
772
|
+
let hasReachedSince = false;
|
|
773
|
+
for (const entry of listed) {
|
|
774
|
+
if (entry.sentAtSecond !== 0 && entry.sentAtSecond < since) {
|
|
775
|
+
hasReachedSince = true;
|
|
776
|
+
continue;
|
|
777
|
+
}
|
|
778
|
+
if (entry.sentAtSecond !== 0 && upperBound !== 0 && entry.sentAtSecond > upperBound) continue;
|
|
779
|
+
messages.push(entry);
|
|
780
|
+
}
|
|
781
|
+
if (!nextPageURI || hasReachedSince) return { messages, isTruncated: false };
|
|
782
|
+
target = this.resolveNextPage(nextPageURI);
|
|
783
|
+
}
|
|
784
|
+
return { messages, isTruncated: true };
|
|
785
|
+
}
|
|
786
|
+
/** Accept only a next page of this account's Messages list on the configured host. */
|
|
787
|
+
resolveNextPage(nextPageURI) {
|
|
788
|
+
const base = new URL(`${this.client.messagesURL}.json`);
|
|
789
|
+
const withoutFragment = nextPageURI.split("#")[0] ?? "";
|
|
790
|
+
const queryStart = withoutFragment.indexOf("?");
|
|
791
|
+
const path = queryStart < 0 ? withoutFragment : withoutFragment.slice(0, queryStart);
|
|
792
|
+
const query = queryStart < 0 ? "" : withoutFragment.slice(queryStart + 1);
|
|
793
|
+
if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(nextPageURI) || nextPageURI.startsWith("//") || path !== base.pathname || !query) {
|
|
794
|
+
throw new Error("Twilio Messages list returned an unexpected next_page_uri");
|
|
795
|
+
}
|
|
796
|
+
return `${base.protocol}//${base.host}${path}?${query}`;
|
|
797
|
+
}
|
|
798
|
+
/** Send one Messages list request; a 429 pauses the connection for Retry-After or backs off exponentially. */
|
|
799
|
+
async listPage(context, target) {
|
|
800
|
+
await waitForPollRequest(context);
|
|
801
|
+
const call = newTriggerCredentialCall(this.connection, MessageReceivedTriggerDefinition.trigger, context.signal);
|
|
802
|
+
const resolved = await this.client.authorization(call, MessageReceivedTriggerDefinition.trigger.triggerName);
|
|
803
|
+
if ("failure" in resolved) throw new Error(resolved.isTransient ? "Twilio messageReceived credentials are unavailable" : resolved.failure.message);
|
|
804
|
+
const exchange = await this.client.exchange(call, resolved.authorization, "GET", target, void 0, context.signal);
|
|
805
|
+
if ("error" in exchange) {
|
|
806
|
+
if (context.signal.aborted) throw exchange.error;
|
|
807
|
+
throw new Error("Twilio Messages list request failed before a response");
|
|
808
|
+
}
|
|
809
|
+
const { response } = exchange;
|
|
810
|
+
if (response.status === 429) {
|
|
811
|
+
throw markRateLimited(new Error(`Twilio Messages list returned HTTP 429 (error ${errorCode(response.body)})`), retryAfter(response, this.client.currentTime()));
|
|
812
|
+
}
|
|
813
|
+
if (response.status === 401 || response.status === 403) {
|
|
814
|
+
throw new Error(`Twilio rejected the Messages list credentials (HTTP ${response.status}, error ${errorCode(response.body)}); update the connection or grant the API key Messages read access`);
|
|
815
|
+
}
|
|
816
|
+
if (response.status < 200 || response.status >= 300) throw new Error(`Twilio Messages list returned HTTP ${response.status} (error ${errorCode(response.body)})`);
|
|
817
|
+
if (exchange.isBodyReadFailed) throw new Error("Twilio Messages list response was interrupted");
|
|
818
|
+
if (exchange.isTooLarge) throw new Error("Twilio Messages list page exceeds maxResponseBytes; raise it on the connection");
|
|
819
|
+
return this.decodePage(response.body, resolved.authorization);
|
|
820
|
+
}
|
|
821
|
+
decodePage(contents, authorization) {
|
|
822
|
+
const invalidJSON = "Twilio Messages list page is not valid JSON";
|
|
823
|
+
let parsed;
|
|
824
|
+
try {
|
|
825
|
+
parsed = parseTwilioJSON(Buffer.from(contents).toString("utf8"));
|
|
826
|
+
} catch {
|
|
827
|
+
throw new Error(invalidJSON);
|
|
828
|
+
}
|
|
829
|
+
const page = parsed.value;
|
|
830
|
+
if (page === null || typeof page !== "object" || Array.isArray(page)) throw new Error(invalidJSON);
|
|
831
|
+
const { messages: resources, next_page_uri: nextPageURI } = page;
|
|
832
|
+
if (!Array.isArray(resources) || nextPageURI !== void 0 && nextPageURI !== null && typeof nextPageURI !== "string") throw new Error(invalidJSON);
|
|
833
|
+
for (const resource of resources) {
|
|
834
|
+
if (resource === null || typeof resource !== "object" || Array.isArray(resource)) throw new Error(invalidJSON);
|
|
835
|
+
const fields = resource;
|
|
836
|
+
if (resourceStringFields.some((name) => fields[name] !== void 0 && fields[name] !== null && typeof fields[name] !== "string")) throw new Error(invalidJSON);
|
|
837
|
+
}
|
|
838
|
+
const listed = resources.map((resource) => {
|
|
839
|
+
let message;
|
|
840
|
+
try {
|
|
841
|
+
message = this.client.convertMessageResource(resource, parsed.rawIntegerTokens, authorization);
|
|
842
|
+
} catch {
|
|
843
|
+
throw new Error("Twilio Messages list page has an invalid message");
|
|
844
|
+
}
|
|
845
|
+
let body = (typeof resource.body === "string" ? resource.body : "").replace(loneSurrogatePattern, "\uFFFD");
|
|
846
|
+
if (authorization.password && body.includes(authorization.password)) body = "";
|
|
847
|
+
const sentAtSecond = message.sentAt === zeroTime2 ? 0 : unixSecond(new Date(message.sentAt));
|
|
848
|
+
return { message, body, sentAtSecond };
|
|
849
|
+
});
|
|
850
|
+
return { listed, nextPageURI: typeof nextPageURI === "string" ? nextPageURI : "" };
|
|
851
|
+
}
|
|
852
|
+
/** Add upserted to the snapshot and drop keys dated before the new lookback. */
|
|
853
|
+
encodeCursor(watermark, previous, upserted) {
|
|
854
|
+
const cutoff = watermark - inboundLookbackSeconds;
|
|
855
|
+
const expired = (previous?.entries ?? []).filter((entry) => {
|
|
856
|
+
const second = inboundSnapshotKeySecond(entry.key);
|
|
857
|
+
return second === void 0 || second < cutoff;
|
|
858
|
+
}).map((entry) => entry.key);
|
|
859
|
+
let snapshot;
|
|
860
|
+
try {
|
|
861
|
+
snapshot = applyKeyedSnapshotChanges(previous, upserted, expired, inboundSnapshotOptions);
|
|
862
|
+
} catch (error) {
|
|
863
|
+
throw new Error(`Twilio messageReceived snapshot: ${error instanceof Error ? error.message : "invalid"}`, { cause: error });
|
|
864
|
+
}
|
|
865
|
+
const to = this.to ? `,"to":${encodeGoJSONValue(this.to)}` : "";
|
|
866
|
+
return { token: `{"accountSid":${encodeGoJSONValue(this.client.accountSid)}${to},"watermark":${watermark}}`, snapshot };
|
|
867
|
+
}
|
|
868
|
+
};
|
|
869
|
+
|
|
870
|
+
// src/trigger.ts
|
|
871
|
+
var InboundMessageDirection = "inbound";
|
|
872
|
+
var MessageStatusReceiving = "receiving";
|
|
873
|
+
var MessageStatusReceived = "received";
|
|
874
|
+
var UIUnitReceivingAddressInput = "receivingAddressInput";
|
|
875
|
+
var UIReceivingAddressInputPortTo = "to";
|
|
876
|
+
var MessageReceivedTriggerConfigurationSchema = z2.strictObject({
|
|
877
|
+
/** The receiving number or WhatsApp sender; blank receives every inbound message of the account. */
|
|
878
|
+
to: z2.string().refine((value) => value === value.trim(), "messageReceived to must not have surrounding whitespace").refine((value) => value === "" || isE164PhoneNumber(value) || isWhatsApp(value), "messageReceived to must be an E.164 phone number or a whatsapp:+E.164 address").optional()
|
|
879
|
+
});
|
|
880
|
+
var MessageReceivedEventSchema = z2.strictObject({
|
|
881
|
+
/** The safe message view; status is received, or receiving when processing outlasted the hold limit. */
|
|
882
|
+
message: MessageSchema,
|
|
883
|
+
/** The inbound text, omitted for a media-only MMS; Twilio may redact it per the account's retention settings. */
|
|
884
|
+
body: z2.string().optional()
|
|
885
|
+
});
|
|
886
|
+
var MessageReceivedTriggerDefinition = {
|
|
887
|
+
trigger: { connectorId: ConnectorID, triggerName: "messageReceived" },
|
|
888
|
+
description: "Receive each inbound SMS, MMS, or WhatsApp message to the account, or to one Twilio number, read by polling the Twilio Messages list; the first run records a baseline and delivers no existing messages."
|
|
889
|
+
};
|
|
890
|
+
function defineMessageReceivedTriggerBinding(config) {
|
|
891
|
+
return mustTriggerBindingDefinition({ definition: MessageReceivedTriggerDefinition, ...config });
|
|
892
|
+
}
|
|
893
|
+
function decodeMessageReceivedPayload(_payloadJSON, payloadBytes) {
|
|
894
|
+
const decoded = MessageReceivedEventSchema.parse(parseTriggerPayloadJSON(payloadBytes));
|
|
895
|
+
if (!decoded.message.sid) throw new TypeError("stored Twilio inbound message is invalid");
|
|
896
|
+
return decoded;
|
|
897
|
+
}
|
|
898
|
+
function twilioClientOf(connection) {
|
|
899
|
+
if (!(connection?.operations instanceof TwilioClient)) throw new TypeError("Twilio Messaging Triggers require a connection from newConnection or newProjectConnection, not a mock connection");
|
|
900
|
+
return connection.operations;
|
|
901
|
+
}
|
|
902
|
+
function pollScheduleOf(client) {
|
|
903
|
+
return { intervalMs: client.pollIntervalMs };
|
|
904
|
+
}
|
|
905
|
+
function parseMessageReceivedTriggerConfiguration(configuration) {
|
|
906
|
+
const parsed = MessageReceivedTriggerConfigurationSchema.safeParse(configuration ?? {});
|
|
907
|
+
if (!parsed.success) throw new TypeError(`twilio-messaging messageReceived configuration: ${parsed.error.issues[0]?.message ?? "invalid"}`);
|
|
908
|
+
return parsed.data;
|
|
909
|
+
}
|
|
910
|
+
function newMessageTriggerRunner(connection, routes, logger) {
|
|
911
|
+
const client = twilioClientOf(connection);
|
|
912
|
+
if (!routes?.length) throw new TypeError("Twilio messageReceived routes are required");
|
|
913
|
+
const pollers = routes.map((route) => {
|
|
914
|
+
if (!route.bindingName?.trim() || !route.target) throw new TypeError("Twilio messageReceived binding name and target are required");
|
|
915
|
+
const configuration = parseMessageReceivedTriggerConfiguration(route.configuration);
|
|
916
|
+
return newBindingPoller({
|
|
917
|
+
definition: MessageReceivedTriggerDefinition,
|
|
918
|
+
binding: { connection: connection.reference, trigger: MessageReceivedTriggerDefinition.trigger, name: route.bindingName },
|
|
919
|
+
cursor: route.cursor ?? newMemoryCursorStore(),
|
|
920
|
+
fetcher: new InboundMessageFetcher(client, connection.reference, configuration.to ?? ""),
|
|
921
|
+
target: route.target,
|
|
922
|
+
snapshot: inboundSnapshotOptions
|
|
923
|
+
});
|
|
924
|
+
});
|
|
925
|
+
return newRunner({ connection: connection.reference, schedule: pollScheduleOf(client), pollers, ...logger ? { logger } : {} });
|
|
926
|
+
}
|
|
927
|
+
function newProjectMessageTriggerRunner(project, connection, routes, logger) {
|
|
928
|
+
if (!project) throw new TypeError("Twilio Trigger runner requires the loaded project configuration");
|
|
929
|
+
twilioClientOf(connection);
|
|
930
|
+
const triggerName = MessageReceivedTriggerDefinition.trigger.triggerName;
|
|
931
|
+
return newMessageTriggerRunner(connection, (routes ?? []).map((route) => {
|
|
932
|
+
if (!route.target) throw new TypeError(`Twilio messageReceived binding "${route.bindingName}" target is required`);
|
|
933
|
+
const key = { connectorId: ConnectorID, connectionName: connection.reference.name, triggerName, bindingName: route.bindingName };
|
|
934
|
+
let configuration = {};
|
|
935
|
+
try {
|
|
936
|
+
configuration = decodeTriggerConfiguration(project.configuration, key, MessageReceivedTriggerConfigurationSchema);
|
|
937
|
+
} catch (error) {
|
|
938
|
+
if (!(error instanceof ObjectNotFoundError)) throw new TypeError(`twilio-messaging messageReceived binding "${route.bindingName}" configuration: ${error instanceof Error ? error.message : "invalid"}`);
|
|
939
|
+
}
|
|
940
|
+
const target = newDurableTriggerTarget(project.triggerInbox(key), key, route.target, { decodePayload: decodeMessageReceivedPayload, ...logger ? { logger } : {} });
|
|
941
|
+
return { bindingName: route.bindingName, configuration, target, cursor: project.pollCursorStore(key) };
|
|
942
|
+
}), logger);
|
|
943
|
+
}
|
|
944
|
+
function newMessageReceivedTrigger(config) {
|
|
945
|
+
if (config.connectionName !== config.connection.reference.name) throw new TypeError(`twilio-messaging connector trigger connectionName "${config.connectionName}" must equal its connection's name "${config.connection.reference.name}"`);
|
|
946
|
+
const client = twilioClientOf(config.connection);
|
|
947
|
+
const configuration = parseMessageReceivedTriggerConfiguration(config.configuration);
|
|
948
|
+
const binding = { connection: config.connection.reference, trigger: MessageReceivedTriggerDefinition.trigger, name: config.bindingName };
|
|
949
|
+
const source = newBindingTriggerSource({
|
|
950
|
+
definition: MessageReceivedTriggerDefinition,
|
|
951
|
+
binding,
|
|
952
|
+
cursor: newMemoryCursorStore(),
|
|
953
|
+
fetcher: new InboundMessageFetcher(client, config.connection.reference, configuration.to ?? ""),
|
|
954
|
+
snapshot: inboundSnapshotOptions
|
|
955
|
+
}, pollScheduleOf(client), config.logger);
|
|
956
|
+
return newTrigger({ definition: MessageReceivedTriggerDefinition, binding, source, target: config.target, ...config.logger ? { logger: config.logger } : {} });
|
|
957
|
+
}
|
|
529
958
|
export {
|
|
530
959
|
ConfigSchema,
|
|
531
960
|
Connection,
|
|
@@ -533,16 +962,30 @@ export {
|
|
|
533
962
|
GetMessageDefinition,
|
|
534
963
|
GetMessageInputSchema,
|
|
535
964
|
GetMessageOperation,
|
|
965
|
+
InboundMessageDirection,
|
|
966
|
+
MessageReceivedEventSchema,
|
|
967
|
+
MessageReceivedTriggerConfigurationSchema,
|
|
968
|
+
MessageReceivedTriggerDefinition,
|
|
536
969
|
MessageSchema,
|
|
970
|
+
MessageStatusReceived,
|
|
971
|
+
MessageStatusReceiving,
|
|
537
972
|
SendMessageBranch,
|
|
538
973
|
SendMessageDefinition,
|
|
539
974
|
SendMessageInputSchema,
|
|
540
975
|
SendMessageOperation,
|
|
541
976
|
TwilioClient,
|
|
977
|
+
UIReceivingAddressInputPortTo,
|
|
978
|
+
UIUnitReceivingAddressInput,
|
|
542
979
|
decodeCredentials,
|
|
980
|
+
decodeMessageReceivedPayload,
|
|
981
|
+
defineMessageReceivedTriggerBinding,
|
|
982
|
+
isE164PhoneNumber,
|
|
543
983
|
newConnection2 as newConnection,
|
|
544
984
|
newConnectionWithOperations,
|
|
545
985
|
newGetMessageStep,
|
|
986
|
+
newMessageReceivedTrigger,
|
|
987
|
+
newMessageTriggerRunner,
|
|
546
988
|
newProjectConnection,
|
|
989
|
+
newProjectMessageTriggerRunner,
|
|
547
990
|
newSendMessageStep
|
|
548
991
|
};
|
package/dist/mock.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { MockMutation, MockQuery, Case } from '@superdurable/connectors-sdk/connectormock';
|
|
2
2
|
import { Failure } from '@superdurable/connectors-sdk';
|
|
3
|
-
import { O as Operations, b as Connection, S as SendMessageInput, M as Message, G as GetMessageInput } from './connection-
|
|
3
|
+
import { O as Operations, b as Connection, S as SendMessageInput, M as Message, G as GetMessageInput } from './connection-BQ9-3dhC.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
|
|
6
6
|
/** Go zero value for SendMessageInput in scripted cases. */
|
package/dist/mock.js
CHANGED
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
SendMessageDefinition,
|
|
8
8
|
SendMessageInputSchema,
|
|
9
9
|
newConnectionWithOperations
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-6KLMYDTX.js";
|
|
11
11
|
|
|
12
12
|
// src/generated/mock.ts
|
|
13
13
|
import { branchCase, retryCase, uncertainCase, newMutation, newQuery } from "@superdurable/connectors-sdk/connectormock";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@superdurable/connector-twilio-messaging",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Twilio Messaging connector for Dex TypeScript applications",
|
|
6
6
|
"repository": {
|
|
@@ -22,7 +22,8 @@
|
|
|
22
22
|
"./mock": {
|
|
23
23
|
"types": "./dist/mock.d.ts",
|
|
24
24
|
"import": "./dist/mock.js"
|
|
25
|
-
}
|
|
25
|
+
},
|
|
26
|
+
"./dex-connector.json": "./dex-connector.json"
|
|
26
27
|
},
|
|
27
28
|
"files": [
|
|
28
29
|
"dist",
|
|
@@ -34,13 +35,14 @@
|
|
|
34
35
|
"build": "tsup src/index.ts src/mock.ts --format esm --dts --clean",
|
|
35
36
|
"typecheck": "tsc --noEmit",
|
|
36
37
|
"lint": "eslint src test examples",
|
|
37
|
-
"test": "vitest run --exclude test/integration/**",
|
|
38
|
+
"test": "npm run build && vitest run --exclude 'test/integration/**'",
|
|
38
39
|
"check": "npm run typecheck && npm run lint && npm test && npm run build",
|
|
39
40
|
"example:run": "npm run build && tsx examples/text-message-delivery/main.ts",
|
|
40
|
-
"example:integration": "npm run build && tsx examples/text-message-delivery/integration.ts"
|
|
41
|
+
"example:integration": "npm run build && tsx examples/text-message-delivery/integration.ts",
|
|
42
|
+
"example:message-received": "npm run build && tsx examples/message-received/main.ts"
|
|
41
43
|
},
|
|
42
44
|
"dependencies": {
|
|
43
|
-
"@superdurable/connectors-sdk": "0.
|
|
45
|
+
"@superdurable/connectors-sdk": "0.12.0",
|
|
44
46
|
"@superdurable/dex": ">=1.28.0",
|
|
45
47
|
"zod": "^4.1.0"
|
|
46
48
|
},
|