@sinch/functions-runtime 0.5.15 → 0.5.17
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 +235 -120
- package/dist/bin/sinch-runtime.js +39 -31
- package/dist/bin/sinch-runtime.js.map +1 -1
- package/dist/chunk-GW2PELD4.js +4 -0
- package/dist/{chunk-IRSTA74R.js → chunk-VEB6FXNI.js} +1577 -49
- package/dist/chunk-VEB6FXNI.js.map +1 -0
- package/dist/index.d.ts +1891 -70
- package/dist/index.js +40 -10
- package/dist/voice/v2.d.ts +59 -572
- package/dist/voice/v2.js +26 -1230
- package/dist/voice/v2.js.map +1 -1
- package/package.json +4 -4
- package/dist/chunk-IRSTA74R.js.map +0 -1
- package/dist/chunk-X44DQ6CI.js +0 -52
- /package/dist/{chunk-X44DQ6CI.js.map → chunk-GW2PELD4.js.map} +0 -0
package/README.md
CHANGED
|
@@ -1,189 +1,304 @@
|
|
|
1
1
|
# @sinch/functions-runtime
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Node.js SDK for [Sinch Functions](https://developers.sinch.com/docs/functions): serverless functions that answer phone calls, reply to messages and serve HTTP endpoints on Sinch infrastructure.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
A function is one file, `function.ts`, that exports handlers. The runtime hosts it, gives every handler a `context` with configuration, cache, storage, a SQLite database and pre-configured Sinch API clients, and turns voice handlers' return values into the wire body the platform expects.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Functions are created and run with the Sinch CLI, which installs this package for you:
|
|
8
10
|
|
|
9
11
|
```bash
|
|
10
|
-
# Install the CLI
|
|
11
12
|
npm install -g @sinch/cli
|
|
12
|
-
|
|
13
|
-
#
|
|
14
|
-
sinch functions
|
|
13
|
+
sinch auth login
|
|
14
|
+
sinch functions init # pick a template
|
|
15
|
+
sinch functions dev # local server with hot reload and a tunnel for callbacks
|
|
16
|
+
sinch functions deploy
|
|
15
17
|
```
|
|
16
18
|
|
|
17
|
-
|
|
19
|
+
Requires Node.js 24 or later. See the [quickstart](https://developers.sinch.com/docs/functions/functions/quickstart) for the full walk-through.
|
|
18
20
|
|
|
19
|
-
|
|
20
|
-
2. Choosing a template (simple-voice-ivr recommended for first project)
|
|
21
|
-
3. Setting up your project
|
|
21
|
+
## A voice function
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
Voice API v2 is what `context.voice` is and what a new function should be written against.
|
|
24
24
|
|
|
25
|
-
```
|
|
26
|
-
sinch
|
|
25
|
+
```ts
|
|
26
|
+
import { onCall, commands } from '@sinch/functions-runtime';
|
|
27
|
+
|
|
28
|
+
export const voiceWebhook = onCall({
|
|
29
|
+
incoming: () => commands().answer().say('Thanks for calling.').hangup(),
|
|
30
|
+
completed: (event) => {
|
|
31
|
+
console.log('call ended', event.call.callId);
|
|
32
|
+
},
|
|
33
|
+
});
|
|
27
34
|
```
|
|
28
35
|
|
|
29
|
-
|
|
36
|
+
`onCall` takes handlers keyed by call lifecycle stage — `incoming`, `answered`, `manage`,
|
|
37
|
+
`completed`, a `webhooks` map for named `webhook` commands, and `fallback` — and returns the
|
|
38
|
+
`voiceWebhook` export. Return a `commands()` builder and the runtime emits the wire body;
|
|
39
|
+
return nothing and it answers `204`.
|
|
30
40
|
|
|
31
|
-
|
|
41
|
+
### Routing calls to the function
|
|
32
42
|
|
|
33
|
-
|
|
43
|
+
An inbound call reaches the function through a **Voice v2 service**. `sinch functions init`
|
|
44
|
+
picks one and writes its id to `.env` as `VOICE_SERVICE_ID`; `sinch functions deploy` then
|
|
45
|
+
points that service's webhook at the deployed function. Every `call.*` event for the service
|
|
46
|
+
arrives at that one URL, so `voiceWebhook` is the only export the platform needs.
|
|
34
47
|
|
|
35
|
-
|
|
36
|
-
|
|
48
|
+
Those events are signed. Each one carries `Authorization: service <serviceId>:<signature>` and
|
|
49
|
+
an `x-timestamp`, signed with the service secret over the raw body, the `Content-Type`, the
|
|
50
|
+
timestamp and the path. The runtime verifies that signature under the same
|
|
51
|
+
`WEBHOOK_PROTECTION` modes as the v1 callbacks (`never`, `deploy`, `always`) as soon as
|
|
52
|
+
`VOICE_SERVICE_SECRET` holds the Base64 secret, and rejects a request that fails with `401`.
|
|
53
|
+
Set `VOICE_SERVICE_ID` as well and the id in the header has to match it.
|
|
54
|
+
|
|
55
|
+
Sinch does not hand out a service's secret anywhere yet. Until it does, a function with
|
|
56
|
+
protection on but no `VOICE_SERVICE_SECRET` logs one warning per process and serves the
|
|
57
|
+
webhook — verification switches itself on the day the secret is set, with no code change.
|
|
58
|
+
List `voiceWebhook` in `auth` if you want Basic auth on the endpoint in the meantime, or if
|
|
59
|
+
you intend to drive it yourself.
|
|
60
|
+
|
|
61
|
+
### Placing calls
|
|
62
|
+
|
|
63
|
+
`context.voice` is the v2 client. It dials, bridges legs, attaches a WebSocket media stream to
|
|
64
|
+
a live call, and patches a call that is already up.
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
await context.voice.call('+15559876543', {
|
|
68
|
+
from: '+15551234567',
|
|
69
|
+
onAnswer: (c) => c.say('Your appointment is confirmed.').hangup(),
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
// Dial a human and bridge a second leg to your own audio socket
|
|
73
|
+
await context.voice.callWithStream('+15559876543', '/media', { from: '+15551234567' });
|
|
37
74
|
```
|
|
38
75
|
|
|
39
|
-
|
|
76
|
+
v2 authenticates with the project Access Key pair (`PROJECT_ID_API_KEY` /
|
|
77
|
+
`PROJECT_ID_API_SECRET`), not the v1 application key.
|
|
78
|
+
|
|
79
|
+
`createClient`, `commands`, `Client` and the core v2 types are importable from the package
|
|
80
|
+
root, as above, or from `@sinch/functions-runtime/voice/v2` — both resolve the same
|
|
81
|
+
declarations. The rest of the v2 surface (`MenuItemBuilder`, `dialPhone`, `dialSip`, etc.) is
|
|
82
|
+
subpath-only, for code that builds a client of its own.
|
|
83
|
+
|
|
84
|
+
## Voice v1 (legacy)
|
|
85
|
+
|
|
86
|
+
v1 still works, and a function already written against it needs no changes beyond the client:
|
|
87
|
+
the SDK namespace that used to be `context.voice` is now `context.voice.v1`, so
|
|
88
|
+
`context.voice.callouts.tts(...)` becomes `context.voice.v1.callouts.tts(...)`. The
|
|
89
|
+
`ice`/`ace`/`pie`/`dice`/`notify` callbacks below are untouched.
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
import type { FunctionContext, IceCallback, PieCallback } from '@sinch/functions-runtime';
|
|
93
|
+
import { IceSvamlBuilder, PieSvamlBuilder, createMenu } from '@sinch/functions-runtime';
|
|
94
|
+
|
|
95
|
+
export default {
|
|
96
|
+
async ice(context: FunctionContext, event: IceCallback) {
|
|
97
|
+
const menu = createMenu()
|
|
98
|
+
.prompt('Press 1 for sales, 2 for support.')
|
|
99
|
+
.option('1', 'return(sales)')
|
|
100
|
+
.option('2', 'return(support)')
|
|
101
|
+
.timeout(5000)
|
|
102
|
+
.repeats(2)
|
|
103
|
+
.build();
|
|
104
|
+
|
|
105
|
+
return new IceSvamlBuilder().runMenu(menu).build();
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
async pie(context: FunctionContext, event: PieCallback) {
|
|
109
|
+
if (event.menuResult?.value === 'sales') {
|
|
110
|
+
return new PieSvamlBuilder()
|
|
111
|
+
.say('Connecting you to sales.')
|
|
112
|
+
.connectPstn('+15551234567')
|
|
113
|
+
.build();
|
|
114
|
+
}
|
|
115
|
+
return new PieSvamlBuilder().say('Goodbye.').hangup().build();
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Callbacks
|
|
121
|
+
|
|
122
|
+
| Handler | Fires when | Returns |
|
|
123
|
+
| -------- | --------------------------------------------------- | ------- |
|
|
124
|
+
| `ice` | An incoming call reaches your number | SVAML |
|
|
125
|
+
| `ace` | An outbound call is answered | SVAML |
|
|
126
|
+
| `pie` | The caller pressed keys or spoke after a menu | SVAML |
|
|
127
|
+
| `dice` | The call ended | nothing |
|
|
128
|
+
| `notify` | A notification event arrives (recording, and so on) | nothing |
|
|
40
129
|
|
|
41
|
-
|
|
130
|
+
Only `ice` is required. The platform may still post the others; the runtime answers `200` for any handler you did not implement.
|
|
42
131
|
|
|
43
|
-
|
|
132
|
+
Handlers receive camelCased payloads typed as `IceCallback`, `AceCallback`, `PieCallback`, `DiceCallback` and `NotifyCallback`. The call identifier arrives as `callId`.
|
|
44
133
|
|
|
45
|
-
|
|
134
|
+
### SVAML builders
|
|
46
135
|
|
|
47
|
-
|
|
48
|
-
import { IceSvamlBuilder, AceSvamlBuilder, PieSvamlBuilder } from '@sinch/functions-runtime';
|
|
136
|
+
Each builder chains instructions (`say`, `play`, `playFiles`, `setCookie`, `sendDtmf`, `startRecording`, `stopRecording`), ends with one action and finishes with `build()`. The actions available depend on the callback:
|
|
49
137
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
138
|
+
| Builder | Actions |
|
|
139
|
+
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
140
|
+
| `IceSvamlBuilder` | `hangup`, `continue`, `connectPstn`, `connectSip`, `connectMxp`, `connectConf`, `runMenu`, `park`, `connectAgent`; also the `answer` instruction |
|
|
141
|
+
| `AceSvamlBuilder` | `hangup`, `continue` |
|
|
142
|
+
| `PieSvamlBuilder` | `hangup`, `continue`, `connectPstn`, `runMenu`, `park`, `connectAgent` |
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
new IceSvamlBuilder()
|
|
146
|
+
.say('Please hold.')
|
|
53
147
|
.connectPstn('+15551234567', {
|
|
54
|
-
cli: '+
|
|
148
|
+
cli: '+15559876543',
|
|
149
|
+
timeout: 30,
|
|
55
150
|
enableAce: true,
|
|
56
151
|
enableDice: true,
|
|
57
152
|
})
|
|
58
153
|
.build();
|
|
59
|
-
|
|
60
|
-
// ACE (Answered Call Event) - handle answered outbound calls
|
|
61
|
-
const aceResponse = new AceSvamlBuilder().say('The call has been answered.').continue().build();
|
|
62
|
-
|
|
63
|
-
// PIE (Prompt Input Event) - handle user input
|
|
64
|
-
const pieResponse = new PieSvamlBuilder()
|
|
65
|
-
.say('You pressed ' + selection)
|
|
66
|
-
.hangup()
|
|
67
|
-
.build();
|
|
68
154
|
```
|
|
69
155
|
|
|
70
|
-
###
|
|
156
|
+
### Menus
|
|
71
157
|
|
|
72
|
-
|
|
158
|
+
`createMenu()` builds a DTMF menu with prompts, options, timeouts and repeats. `MenuTemplates` has ready-made ones: `business(name)`, `yesNo(question)`, `language()`, `afterHours(name)` and `numericInput(prompt, digits)`.
|
|
73
159
|
|
|
74
|
-
|
|
75
|
-
import { MenuBuilder, MenuTemplates } from '@sinch/functions-runtime';
|
|
160
|
+
## HTTP handlers
|
|
76
161
|
|
|
77
|
-
|
|
78
|
-
const businessMenu = MenuTemplates.business('Acme Corp');
|
|
79
|
-
const yesNoMenu = MenuTemplates.yesNo('Do you want to continue?');
|
|
162
|
+
Any other exported async function is an HTTP endpoint named after the export. `export async function notes(...)` answers requests to `/notes`.
|
|
80
163
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
.prompt('Press 1 for English, 2 for Spanish')
|
|
84
|
-
.option('1', 'menu(english)')
|
|
85
|
-
.option('2', 'menu(spanish)')
|
|
86
|
-
.addSubmenu('english')
|
|
87
|
-
.prompt('Press 1 for sales, 2 for support')
|
|
88
|
-
.option('1', 'return(en-sales)')
|
|
89
|
-
.option('2', 'return(en-support)')
|
|
90
|
-
.build();
|
|
91
|
-
```
|
|
92
|
-
|
|
93
|
-
### Cache
|
|
164
|
+
```ts
|
|
165
|
+
import type { FunctionContext, FunctionRequest, FunctionResponse } from '@sinch/functions-runtime';
|
|
94
166
|
|
|
95
|
-
|
|
167
|
+
export async function notes(
|
|
168
|
+
context: FunctionContext,
|
|
169
|
+
request: FunctionRequest
|
|
170
|
+
): Promise<FunctionResponse> {
|
|
171
|
+
if (request.method === 'POST') {
|
|
172
|
+
const { key, content } = request.body as { key: string; content: string };
|
|
173
|
+
await context.storage.write(`notes/${key}.txt`, content);
|
|
174
|
+
return { statusCode: 201, body: { key } };
|
|
175
|
+
}
|
|
176
|
+
return { statusCode: 200, body: await context.storage.list('notes/') };
|
|
177
|
+
}
|
|
178
|
+
```
|
|
96
179
|
|
|
97
|
-
|
|
98
|
-
export async function ice(context, event) {
|
|
99
|
-
const cache = context.cache;
|
|
180
|
+
`FunctionRequest` carries `method`, `path`, `query`, `headers`, `body` and `params`. Return `{ statusCode, headers?, body? }`, or use `createJsonResponse`, `createResponse` and `createErrorResponse`.
|
|
100
181
|
|
|
101
|
-
|
|
102
|
-
await cache.set('call-count', 1, 3600); // TTL in seconds
|
|
182
|
+
Webhooks from other Sinch products are plain HTTP handlers too. An inbound Conversation API message, for example:
|
|
103
183
|
|
|
104
|
-
|
|
105
|
-
|
|
184
|
+
```ts
|
|
185
|
+
export async function conversationWebhook(
|
|
186
|
+
context: FunctionContext,
|
|
187
|
+
request: FunctionRequest
|
|
188
|
+
): Promise<FunctionResponse> {
|
|
189
|
+
const body = request.body as Record<string, unknown>;
|
|
190
|
+
const contactId = body.contact_id as string | undefined;
|
|
191
|
+
const text = (body.message as any)?.contact_message?.text_message?.text as string | undefined;
|
|
192
|
+
if (!contactId || !text) return { statusCode: 200, body: { ok: true } };
|
|
193
|
+
|
|
194
|
+
await context.conversation!.messages.send({
|
|
195
|
+
sendMessageRequestBody: {
|
|
196
|
+
app_id: context.env!.CONVERSATION_APP_ID!,
|
|
197
|
+
recipient: { contact_id: contactId },
|
|
198
|
+
message: { text_message: { text: 'Thanks for your message.' } },
|
|
199
|
+
},
|
|
200
|
+
});
|
|
201
|
+
return { statusCode: 200, body: { ok: true } };
|
|
106
202
|
}
|
|
107
203
|
```
|
|
108
204
|
|
|
109
|
-
|
|
205
|
+
Helpers such as `getText`, `getChannel`, `getContactId`, `isTextMessage` and `ConversationMessageBuilder` are exported for working with Conversation API payloads.
|
|
206
|
+
|
|
207
|
+
### Protecting endpoints
|
|
110
208
|
|
|
111
|
-
|
|
209
|
+
Export `auth` to require HTTP Basic authentication with your project API key and secret. `'*'` protects every endpoint; an array names the ones to protect.
|
|
112
210
|
|
|
113
|
-
```
|
|
114
|
-
|
|
211
|
+
```ts
|
|
212
|
+
export const auth = ['notes', 'config'];
|
|
213
|
+
```
|
|
115
214
|
|
|
116
|
-
|
|
117
|
-
const config = createConfig(context);
|
|
215
|
+
## Startup and WebSockets
|
|
118
216
|
|
|
119
|
-
|
|
120
|
-
const companyName = config.getVariable('COMPANY_NAME', 'Default');
|
|
217
|
+
Export `setup` to run code once before the server accepts requests, or to accept WebSocket connections (for example a `connectStream` media stream).
|
|
121
218
|
|
|
122
|
-
|
|
123
|
-
|
|
219
|
+
```ts
|
|
220
|
+
import type { SinchRuntime } from '@sinch/functions-runtime';
|
|
221
|
+
|
|
222
|
+
export function setup(runtime: SinchRuntime) {
|
|
223
|
+
runtime.onStartup(async (context) => {
|
|
224
|
+
await context.cache.set('ready', true);
|
|
225
|
+
});
|
|
226
|
+
runtime.onWebSocket('/stream', (ws, req) => {
|
|
227
|
+
ws.on('message', (frame) => {
|
|
228
|
+
/* audio */
|
|
229
|
+
});
|
|
230
|
+
});
|
|
124
231
|
}
|
|
125
232
|
```
|
|
126
233
|
|
|
127
|
-
##
|
|
234
|
+
## The context
|
|
128
235
|
|
|
129
|
-
|
|
130
|
-
| -------- | ------------------------------------------------------- | ------- |
|
|
131
|
-
| `ice` | Incoming Call Event - first callback for incoming calls | SVAML |
|
|
132
|
-
| `ace` | Answered Call Event - when outbound call is answered | SVAML |
|
|
133
|
-
| `pie` | Prompt Input Event - user input (DTMF/voice) | SVAML |
|
|
134
|
-
| `dice` | Disconnected Call Event - call ended | None |
|
|
135
|
-
| `notify` | Notification events | None |
|
|
236
|
+
Every handler receives a `FunctionContext`.
|
|
136
237
|
|
|
137
|
-
|
|
238
|
+
| Member | What it is |
|
|
239
|
+
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
|
240
|
+
| `context.config` | `projectId`, `functionName`, `environment` and the `variables` you set at init or deploy |
|
|
241
|
+
| `context.env` | Environment variables, including secrets |
|
|
242
|
+
| `context.cache` | Key-value store with TTLs: `get`, `set`, `has`, `delete`, `extend`, `keys`, `getMany`. In memory locally, shared in production |
|
|
243
|
+
| `context.storage` | Durable files: `write`, `read`, `list`, `exists`, `delete`. Local filesystem in dev, object storage in production |
|
|
244
|
+
| `context.database` | Path to a per-function SQLite file, replicated in production. Open it with `node:sqlite` or any SQLite driver |
|
|
245
|
+
| `context.assets(name)` | Reads a file from the function's `assets/` directory |
|
|
246
|
+
| `context.voice` | Voice API v2 client: `call`, `callWithStream`, `bridge`, `transfer`, `patch`, `onCall`. Always present |
|
|
247
|
+
| `context.voice.v1` | Voice API v1 client, when `VOICE_APPLICATION_KEY` and `VOICE_APPLICATION_SECRET` are set |
|
|
248
|
+
| `context.conversation` | Conversation API client, when `CONVERSATION_APP_ID` is set |
|
|
249
|
+
| `context.sms` | SMS API client, when `SMS_SERVICE_PLAN_ID` is set |
|
|
250
|
+
| `context.numbers` | Numbers API client, when `ENABLE_NUMBERS_API=true` |
|
|
138
251
|
|
|
139
|
-
|
|
252
|
+
The API clients also need `PROJECT_ID`, `PROJECT_ID_API_KEY` and `PROJECT_ID_API_SECRET`, which `sinch auth login` provides. A client whose variables are missing is `undefined` — except `context.voice`, which is always there and reports missing credentials when a request is actually sent. Full list: [SDK environment variables](https://developers.sinch.com/docs/functions/reference/sdk-env-vars).
|
|
140
253
|
|
|
141
|
-
|
|
254
|
+
```ts
|
|
255
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
142
256
|
|
|
143
|
-
|
|
257
|
+
const db = new DatabaseSync(context.database);
|
|
258
|
+
db.exec('CREATE TABLE IF NOT EXISTS visits (day TEXT PRIMARY KEY, n INTEGER NOT NULL DEFAULT 0)');
|
|
259
|
+
```
|
|
144
260
|
|
|
145
|
-
|
|
146
|
-
import type { FunctionContext, IceCallback, SvamletResponse } from '@sinch/functions-runtime';
|
|
261
|
+
`createConfig(context)` wraps the configuration with `getVariable`, `requireVariable`, `getSecret`, `requireSecret`, `isDevelopment` and `getApplicationCredentials`.
|
|
147
262
|
|
|
148
|
-
|
|
149
|
-
context: FunctionContext,
|
|
150
|
-
event: IceCallback
|
|
151
|
-
): Promise<SvamletResponse> {
|
|
152
|
-
// Full type safety and IntelliSense!
|
|
153
|
-
}
|
|
154
|
-
```
|
|
263
|
+
## Local development and production
|
|
155
264
|
|
|
156
|
-
|
|
265
|
+
This package is the local development runtime and the SDK you import from. `sinch functions dev` runs your function on `http://localhost:3000` (override with `PORT`) with hot reload, an in-memory cache, filesystem storage and a tunnel that forwards live Sinch callbacks to your machine.
|
|
157
266
|
|
|
158
|
-
|
|
159
|
-
| -------------------------------------- | ---------------------- |
|
|
160
|
-
| Request body | 10 MB (10485760 bytes) |
|
|
161
|
-
| Request/response body retained in logs | First 64 KB |
|
|
267
|
+
While the tunnel is up it repoints the callbacks at it: the v1 voice application callback when `VOICE_APPLICATION_KEY` is set, and the Voice v2 service webhook when `VOICE_SERVICE_ID` is set.
|
|
162
268
|
|
|
163
|
-
|
|
269
|
+
When you deploy, the platform installs `@sinch/functions-runtime-prod` in the container. It exposes the same API, so nothing in `function.ts` changes between environments. Do not install the prod package yourself.
|
|
164
270
|
|
|
165
|
-
|
|
166
|
-
{
|
|
167
|
-
"error": "Payload too large",
|
|
168
|
-
"message": "Request body exceeds the 10mb limit",
|
|
169
|
-
"limit": "10mb"
|
|
170
|
-
}
|
|
171
|
-
```
|
|
271
|
+
## Limits
|
|
172
272
|
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
273
|
+
| Limit | Value |
|
|
274
|
+
| ------------------------------------- | ----------- |
|
|
275
|
+
| Request body | 10 MB |
|
|
276
|
+
| Request or response body kept in logs | First 64 KB |
|
|
176
277
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
278
|
+
The 10 MB cap applies locally and deployed, so a request that works in `sinch functions dev` works in production. A deployed function rejects a larger body with `413` and a JSON body naming the limit; the platform router in front of it enforces the same cap, so a `413` without that JSON body came from the router. Deployed functions keep the first 64 KB of text bodies (JSON, XML, plain text, form data) in their logs and append `…[truncated — N bytes total]` past that. Binary bodies are never logged. See [limits](https://developers.sinch.com/docs/functions/reference/limits).
|
|
279
|
+
|
|
280
|
+
## TypeScript
|
|
281
|
+
|
|
282
|
+
Everything is typed. Import types alongside the builders:
|
|
283
|
+
|
|
284
|
+
```ts
|
|
285
|
+
import type {
|
|
286
|
+
FunctionContext,
|
|
287
|
+
IceCallback,
|
|
288
|
+
SvamletResponse,
|
|
289
|
+
VoiceFunction,
|
|
290
|
+
} from '@sinch/functions-runtime';
|
|
291
|
+
```
|
|
181
292
|
|
|
182
293
|
## Documentation
|
|
183
294
|
|
|
184
|
-
- [Sinch Functions
|
|
185
|
-
- [
|
|
186
|
-
- [
|
|
295
|
+
- [Sinch Functions](https://developers.sinch.com/docs/functions)
|
|
296
|
+
- [Your first function](https://developers.sinch.com/docs/functions/functions/quickstart)
|
|
297
|
+
- [Local development](https://developers.sinch.com/docs/functions/functions/local-development)
|
|
298
|
+
- [Function context reference](https://developers.sinch.com/docs/functions/reference/function-context)
|
|
299
|
+
- [SVAML cheatsheet](https://developers.sinch.com/docs/functions/reference/svaml-cheatsheet)
|
|
300
|
+
- [Templates](https://developers.sinch.com/docs/functions/functions/templates)
|
|
301
|
+
- [Voice API](https://developers.sinch.com/docs/voice) and [Conversation API](https://developers.sinch.com/docs/conversation)
|
|
187
302
|
|
|
188
303
|
## License
|
|
189
304
|
|
|
@@ -3,6 +3,10 @@ import { createRequire as __sinchCreateRequire } from 'node:module';
|
|
|
3
3
|
const require = __sinchCreateRequire(import.meta.url);
|
|
4
4
|
import {
|
|
5
5
|
TunnelClient,
|
|
6
|
+
__commonJS,
|
|
7
|
+
__require,
|
|
8
|
+
__toESM,
|
|
9
|
+
attachVoiceClient,
|
|
6
10
|
buildBaseContext,
|
|
7
11
|
createApp,
|
|
8
12
|
createCacheClient,
|
|
@@ -10,15 +14,10 @@ import {
|
|
|
10
14
|
createStorageClient,
|
|
11
15
|
getSinchClients,
|
|
12
16
|
installWebSocketHandlers,
|
|
13
|
-
|
|
17
|
+
isVoiceV1Callback,
|
|
14
18
|
secretsLoader,
|
|
15
19
|
setupRequestHandler
|
|
16
|
-
} from "../chunk-
|
|
17
|
-
import {
|
|
18
|
-
__commonJS,
|
|
19
|
-
__require,
|
|
20
|
-
__toESM
|
|
21
|
-
} from "../chunk-X44DQ6CI.js";
|
|
20
|
+
} from "../chunk-VEB6FXNI.js";
|
|
22
21
|
|
|
23
22
|
// ../../node_modules/dotenv/package.json
|
|
24
23
|
var require_package = __commonJS({
|
|
@@ -423,6 +422,19 @@ var import_dotenv = __toESM(require_main(), 1);
|
|
|
423
422
|
import path from "path";
|
|
424
423
|
import { pathToFileURL } from "url";
|
|
425
424
|
import fs from "fs";
|
|
425
|
+
|
|
426
|
+
// src/host/health.ts
|
|
427
|
+
function registerHealthRoute(app) {
|
|
428
|
+
app.get("/_health", (_req, res) => {
|
|
429
|
+
res.json({
|
|
430
|
+
status: "healthy",
|
|
431
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
432
|
+
uptime: process.uptime()
|
|
433
|
+
});
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// src/bin/sinch-runtime.ts
|
|
426
438
|
function findFunctionPath() {
|
|
427
439
|
const distPath = path.join(process.cwd(), "dist", "function.js");
|
|
428
440
|
const rootPath = path.join(process.cwd(), "function.js");
|
|
@@ -441,23 +453,25 @@ function loadRuntimeConfig() {
|
|
|
441
453
|
var storage = createStorageClient();
|
|
442
454
|
var databasePath = path.join(process.cwd(), ".sinch", "data", "app.db");
|
|
443
455
|
function buildLocalContext(req, runtimeConfig) {
|
|
444
|
-
const baseContext = buildBaseContext(req);
|
|
445
456
|
const cache = createCacheClient();
|
|
446
|
-
const sinchClients = getSinchClients();
|
|
447
|
-
return
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
457
|
+
const { voice: voiceV1, ...sinchClients } = getSinchClients();
|
|
458
|
+
return attachVoiceClient(
|
|
459
|
+
{
|
|
460
|
+
...buildBaseContext(req),
|
|
461
|
+
cache,
|
|
462
|
+
storage,
|
|
463
|
+
database: databasePath,
|
|
464
|
+
...sinchClients,
|
|
465
|
+
env: process.env,
|
|
466
|
+
config: {
|
|
467
|
+
projectId: runtimeConfig.projectId,
|
|
468
|
+
functionName: runtimeConfig.functionId,
|
|
469
|
+
environment: "development",
|
|
470
|
+
variables: process.env
|
|
471
|
+
}
|
|
472
|
+
},
|
|
473
|
+
voiceV1
|
|
474
|
+
);
|
|
461
475
|
}
|
|
462
476
|
function displayStartupInfo(config, verbose, _port) {
|
|
463
477
|
if (verbose) {
|
|
@@ -548,7 +562,7 @@ async function displayDetectedFunctions(port) {
|
|
|
548
562
|
if (functions.length > 0) {
|
|
549
563
|
console.log("\nDetected functions:");
|
|
550
564
|
for (const fn of functions) {
|
|
551
|
-
const type =
|
|
565
|
+
const type = isVoiceV1Callback(fn) ? "voice" : "custom";
|
|
552
566
|
console.log(` ${fn} (${type}): POST http://localhost:${port}/${fn}`);
|
|
553
567
|
}
|
|
554
568
|
}
|
|
@@ -599,6 +613,7 @@ async function main() {
|
|
|
599
613
|
console.log(`[SETUP] Registered ${result.startupHandlers.length} startup handler(s), ${result.wsHandlers.size} WebSocket endpoint(s)`);
|
|
600
614
|
}
|
|
601
615
|
}
|
|
616
|
+
registerHealthRoute(app);
|
|
602
617
|
setupRequestHandler(app, {
|
|
603
618
|
landingPageEnabled,
|
|
604
619
|
authConfig: userAuthConfig,
|
|
@@ -619,13 +634,6 @@ async function main() {
|
|
|
619
634
|
}
|
|
620
635
|
}
|
|
621
636
|
});
|
|
622
|
-
app.get("/_health", (_req, res) => {
|
|
623
|
-
res.json({
|
|
624
|
-
status: "healthy",
|
|
625
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
626
|
-
uptime: process.uptime()
|
|
627
|
-
});
|
|
628
|
-
});
|
|
629
637
|
displayStartupInfo(config, verbose, port);
|
|
630
638
|
if (setupResult?.startupHandlers.length) {
|
|
631
639
|
const context = buildLocalContext({}, config);
|