@sinch/functions-runtime 0.4.11 → 0.4.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -145,6 +145,7 @@ export interface ConnectStreamAction extends BaseAction {
145
145
  endpoint: string;
146
146
  };
147
147
  streamingOptions?: {
148
+ version?: number;
148
149
  sampleRate?: 8000 | 16000;
149
150
  maxFrameSizeMs?: 20 | 40;
150
151
  };
@@ -423,6 +424,32 @@ export interface ConnectAgentOptions {
423
424
  /** Caller ID for personalization */
424
425
  callerId?: string;
425
426
  }
427
+ /**
428
+ * Helper class for building SIP URIs for agent connections
429
+ */
430
+ export declare class AgentSipHelper {
431
+ /**
432
+ * Build a SIP URI for connecting to an ElevenLabs agent
433
+ */
434
+ static buildElevenLabsSipUri(agentId: string, options?: ConnectAgentOptions): string;
435
+ /**
436
+ * Build a SIP URI for the given provider and agent
437
+ */
438
+ static buildSipUri(provider: AgentProvider, agentId: string, options?: ConnectAgentOptions): string;
439
+ }
440
+ /**
441
+ * Create a connectSip SVAML action for SIP-based AI agent providers (e.g. ElevenLabs).
442
+ * For Sinch WebSocket agents use connectStream directly.
443
+ */
444
+ export declare function createConnectAgentAction(provider: AgentProvider, agentId: string, options?: ConnectAgentOptions): {
445
+ name: "connectSip";
446
+ destination: {
447
+ endpoint: string;
448
+ };
449
+ cli?: string;
450
+ maxDuration?: number;
451
+ suppressCallbacks?: boolean;
452
+ };
426
453
  export interface RecordingOptions {
427
454
  /** URL to send the recording to */
428
455
  destinationUrl?: string;
@@ -1346,6 +1373,15 @@ export declare function setupJsonParsing(app: Express, options?: JsonParsingOpti
1346
1373
  * - '*' — protect all handlers
1347
1374
  */
1348
1375
  export type AuthConfig = string[] | "*";
1376
+ /**
1377
+ * Validates a Basic Auth header against expected credentials.
1378
+ *
1379
+ * @param authHeader - The Authorization header value (e.g. "Basic dXNlcjpwYXNz")
1380
+ * @param expectedKey - The expected key (username)
1381
+ * @param expectedSecret - The expected secret (password)
1382
+ * @returns true if credentials match, false otherwise
1383
+ */
1384
+ export declare function validateBasicAuth(authHeader: string | undefined, expectedKey: string, expectedSecret: string): boolean;
1349
1385
  /**
1350
1386
  * Get the landing page HTML content
1351
1387
  * Exported so production runtime can also use it
@@ -1492,6 +1528,27 @@ export declare function handleCustomEndpoint(functionName: string, userFunction:
1492
1528
  * @internal
1493
1529
  */
1494
1530
  export declare function createApp(options?: AppOptions): Express;
1531
+ /**
1532
+ * Result of calling the user's setup() export
1533
+ * @internal
1534
+ */
1535
+ export interface SetupResult {
1536
+ startupHandlers: Array<(context: FunctionContext) => Promise<void> | void>;
1537
+ wsHandlers: Map<string, WebSocketHandler>;
1538
+ }
1539
+ /**
1540
+ * Create a SinchRuntime object that collects registrations from user's setup() export.
1541
+ * @internal
1542
+ */
1543
+ export declare function createSinchRuntime(): {
1544
+ runtime: SinchRuntime;
1545
+ result: SetupResult;
1546
+ };
1547
+ /**
1548
+ * Install WebSocket upgrade handlers on an HTTP server.
1549
+ * @internal
1550
+ */
1551
+ export declare function installWebSocketHandlers(server: import("http").Server, wsHandlers: Map<string, WebSocketHandler>, logger?: (...args: unknown[]) => void): void;
1495
1552
  /**
1496
1553
  * Setup the main request handler
1497
1554
  * @internal
@@ -2289,6 +2346,49 @@ export declare abstract class ConversationController {
2289
2346
  */
2290
2347
  getWebhookHandler(): (req: Request, res: Response) => Promise<void>;
2291
2348
  }
2349
+ /**
2350
+ * Security Configuration for Sinch Functions
2351
+ *
2352
+ * Provides webhook signature validation modes and helpers.
2353
+ */
2354
+ /**
2355
+ * Webhook protection mode
2356
+ * - "never": No validation (development only)
2357
+ * - "deploy": Validate in production (default)
2358
+ * - "always": Always validate
2359
+ */
2360
+ export type WebhookProtectionMode = "never" | "deploy" | "always";
2361
+ /**
2362
+ * Security configuration options for webhook validation.
2363
+ * Controls signature verification for both Voice and Conversation webhooks.
2364
+ */
2365
+ export interface SecurityOptions {
2366
+ /**
2367
+ * Controls webhook signature validation for all webhook types.
2368
+ * @default 'deploy'
2369
+ */
2370
+ webhookProtection: WebhookProtectionMode;
2371
+ }
2372
+ /**
2373
+ * Default security options
2374
+ */
2375
+ export declare const defaultSecurityOptions: SecurityOptions;
2376
+ /**
2377
+ * Determines if webhook validation should be performed based on current environment
2378
+ *
2379
+ * @param mode - The protection mode from configuration
2380
+ * @param isDevelopment - Whether running in development environment
2381
+ * @returns True if validation should be performed
2382
+ */
2383
+ export declare function shouldValidateWebhook(mode: WebhookProtectionMode | string | undefined, isDevelopment: boolean): boolean;
2384
+ export declare function getProtectionMode(config?: Record<string, unknown>): WebhookProtectionMode;
2385
+ /**
2386
+ * Create security options from environment and configuration
2387
+ *
2388
+ * @param config - Optional configuration object
2389
+ * @returns Security options
2390
+ */
2391
+ export declare function createSecurityOptions(config?: Record<string, unknown>): SecurityOptions;
2292
2392
  /**
2293
2393
  * Converts an E.164 phone number to local/national format.
2294
2394
  *
@@ -2365,6 +2465,75 @@ export declare function formatDuration(seconds: number): string;
2365
2465
  * @returns Normalized phone number
2366
2466
  */
2367
2467
  export declare function extractCallerNumber(cli: string | undefined): string | undefined;
2468
+ /**
2469
+ * Simple template renderer for HTML files
2470
+ * Replaces {{variableName}} placeholders with actual values
2471
+ */
2472
+ export declare class TemplateRender {
2473
+ /**
2474
+ * Load and render an HTML template with variables
2475
+ * @param templatePath - Path to the HTML template file
2476
+ * @param variables - Object containing variables to replace in template
2477
+ * @returns Rendered HTML string
2478
+ */
2479
+ static render(templatePath: string, variables?: Record<string, any>): string;
2480
+ /**
2481
+ * Get the absolute path to a template file relative to the current directory
2482
+ * @param templateName - Name of the template file (e.g., 'index.html')
2483
+ * @param baseDir - Base directory to search from (defaults to cwd)
2484
+ * @returns Absolute path to the template file
2485
+ */
2486
+ static getTemplatePath(templateName: string, baseDir?: string): string;
2487
+ }
2488
+ /**
2489
+ * Version extractor utility for reading template versions from README.md files
2490
+ */
2491
+ export declare class VersionExtractor {
2492
+ /**
2493
+ * Extract version from README.md file in the template directory
2494
+ * Looks for "Template Version: X.X.X" pattern in the last few lines
2495
+ * @param templateDir - Path to the template directory containing README.md
2496
+ * @returns Version string or default fallback
2497
+ */
2498
+ static getTemplateVersion(templateDir?: string): string;
2499
+ }
2500
+ export interface DefaultEndpointOptions {
2501
+ serviceName?: string;
2502
+ companyName?: string;
2503
+ templateVersion?: string;
2504
+ availableEndpoints?: Record<string, string>;
2505
+ }
2506
+ export interface HttpRequest {
2507
+ method: string;
2508
+ path: string;
2509
+ query?: Record<string, any>;
2510
+ headers?: Record<string, string>;
2511
+ body?: any;
2512
+ params?: Record<string, string>;
2513
+ }
2514
+ export interface HttpResponse {
2515
+ statusCode: number;
2516
+ headers: Record<string, string>;
2517
+ body: any;
2518
+ }
2519
+ export declare class DefaultEndpointHandler {
2520
+ /**
2521
+ * Handle the default endpoint with content negotiation
2522
+ * @param context - Function context with config and cache
2523
+ * @param request - HTTP request object with method, path, query, headers, body, params
2524
+ * @param options - Configuration options for the response
2525
+ * @returns HTTP response object with statusCode, headers, and body
2526
+ */
2527
+ static handle(context: FunctionContext, request: HttpRequest, options?: DefaultEndpointOptions): Promise<HttpResponse>;
2528
+ }
2529
+ /**
2530
+ * Function loader utilities - shared between dev and prod runtimes
2531
+ */
2532
+ /**
2533
+ * Get the path to the compiled function file.
2534
+ * TypeScript projects compile to dist/function.js
2535
+ */
2536
+ export declare function findFunctionPath(): string;
2368
2537
  /** @deprecated Import from '@sinch/voice' instead: `import type { Voice } from '@sinch/voice'` then use `Voice.IceRequest` @internal */
2369
2538
  export type IceCallbackData = Voice.IceRequest;
2370
2539
  /** @deprecated Import from '@sinch/voice' instead @internal */
package/dist/index.js CHANGED
@@ -961,6 +961,9 @@ function validateBasicAuth(authHeader, expectedKey, expectedSecret) {
961
961
  }
962
962
 
963
963
  // ../runtime-shared/dist/security/index.js
964
+ var defaultSecurityOptions = {
965
+ webhookProtection: "deploy"
966
+ };
964
967
  function shouldValidateWebhook(mode, isDevelopment) {
965
968
  const normalizedMode = (mode || "deploy").toLowerCase();
966
969
  switch (normalizedMode) {
@@ -995,6 +998,11 @@ function getProtectionMode(config) {
995
998
  }
996
999
  return "deploy";
997
1000
  }
1001
+ function createSecurityOptions(config) {
1002
+ return {
1003
+ webhookProtection: getProtectionMode(config)
1004
+ };
1005
+ }
998
1006
 
999
1007
  // ../runtime-shared/dist/sinch/index.js
1000
1008
  import { SinchClient, validateAuthenticationHeader, ConversationCallbackWebhooks } from "@sinch/sdk-core";
@@ -1381,6 +1389,42 @@ function createApp(options = {}) {
1381
1389
  app.use(express.urlencoded({ extended: true, limit: "10mb" }));
1382
1390
  return app;
1383
1391
  }
1392
+ function createSinchRuntime() {
1393
+ const result = {
1394
+ startupHandlers: [],
1395
+ wsHandlers: /* @__PURE__ */ new Map()
1396
+ };
1397
+ const runtime = {
1398
+ onStartup(handler) {
1399
+ result.startupHandlers.push(handler);
1400
+ },
1401
+ onWebSocket(path6, handler) {
1402
+ const normalizedPath = path6.startsWith("/") ? path6 : `/${path6}`;
1403
+ result.wsHandlers.set(normalizedPath, handler);
1404
+ }
1405
+ };
1406
+ return { runtime, result };
1407
+ }
1408
+ function installWebSocketHandlers(server, wsHandlers, logger = console.log) {
1409
+ if (wsHandlers.size === 0)
1410
+ return;
1411
+ const { WebSocketServer } = requireCjs2("ws");
1412
+ const wss = new WebSocketServer({ noServer: true });
1413
+ server.on("upgrade", (req, socket, head) => {
1414
+ const pathname = new URL(req.url || "/", `http://${req.headers.host}`).pathname;
1415
+ const handler = wsHandlers.get(pathname);
1416
+ if (handler) {
1417
+ logger(`[WS] Upgrade request for ${pathname}`);
1418
+ wss.handleUpgrade(req, socket, head, (ws) => {
1419
+ handler(ws, req);
1420
+ });
1421
+ } else {
1422
+ logger(`[WS] No handler for ${pathname} \u2014 rejecting upgrade`);
1423
+ socket.destroy();
1424
+ }
1425
+ });
1426
+ logger(`[WS] WebSocket endpoints registered: ${[...wsHandlers.keys()].join(", ")}`);
1427
+ }
1384
1428
  function setupRequestHandler(app, options = {}) {
1385
1429
  const { loadUserFunction = async () => {
1386
1430
  const functionPath = findFunctionPath();
@@ -2468,13 +2512,147 @@ function extractCallerNumber(cli) {
2468
2512
  // ../runtime-shared/dist/utils/templateRender.js
2469
2513
  import fs from "fs";
2470
2514
  import path from "path";
2515
+ var TemplateRender = class {
2516
+ /**
2517
+ * Load and render an HTML template with variables
2518
+ * @param templatePath - Path to the HTML template file
2519
+ * @param variables - Object containing variables to replace in template
2520
+ * @returns Rendered HTML string
2521
+ */
2522
+ static render(templatePath, variables = {}) {
2523
+ try {
2524
+ const template = fs.readFileSync(templatePath, "utf8");
2525
+ let rendered = template;
2526
+ for (const [key, value] of Object.entries(variables)) {
2527
+ const placeholder = `{{${key}}}`;
2528
+ const regex = new RegExp(placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
2529
+ rendered = rendered.replace(regex, String(value));
2530
+ }
2531
+ return rendered;
2532
+ } catch (error) {
2533
+ console.error("Error rendering template:", error);
2534
+ throw new Error(`Failed to render template: ${templatePath}`);
2535
+ }
2536
+ }
2537
+ /**
2538
+ * Get the absolute path to a template file relative to the current directory
2539
+ * @param templateName - Name of the template file (e.g., 'index.html')
2540
+ * @param baseDir - Base directory to search from (defaults to cwd)
2541
+ * @returns Absolute path to the template file
2542
+ */
2543
+ static getTemplatePath(templateName, baseDir) {
2544
+ const searchDir = baseDir || process.cwd();
2545
+ const pagesPath = path.join(searchDir, "utils", "pages", templateName);
2546
+ if (fs.existsSync(pagesPath)) {
2547
+ return pagesPath;
2548
+ }
2549
+ const directPath = path.join(searchDir, "pages", templateName);
2550
+ if (fs.existsSync(directPath)) {
2551
+ return directPath;
2552
+ }
2553
+ return path.join(searchDir, "utils", "pages", templateName);
2554
+ }
2555
+ };
2471
2556
 
2472
2557
  // ../runtime-shared/dist/utils/versionExtractor.js
2473
2558
  import fs2 from "fs";
2474
2559
  import path2 from "path";
2560
+ var VersionExtractor = class {
2561
+ /**
2562
+ * Extract version from README.md file in the template directory
2563
+ * Looks for "Template Version: X.X.X" pattern in the last few lines
2564
+ * @param templateDir - Path to the template directory containing README.md
2565
+ * @returns Version string or default fallback
2566
+ */
2567
+ static getTemplateVersion(templateDir = process.cwd()) {
2568
+ try {
2569
+ const readmePath = path2.join(templateDir, "README.md");
2570
+ if (!fs2.existsSync(readmePath)) {
2571
+ console.warn("README.md not found, using default version");
2572
+ return "v1.0.0";
2573
+ }
2574
+ const readmeContent = fs2.readFileSync(readmePath, "utf8");
2575
+ const lines = readmeContent.split("\n");
2576
+ const versionPattern = /Template Version:\s*([\d.]+)/i;
2577
+ for (let i = lines.length - 1; i >= Math.max(0, lines.length - 10); i--) {
2578
+ const match = lines[i].match(versionPattern);
2579
+ if (match) {
2580
+ return `v${match[1]}`;
2581
+ }
2582
+ }
2583
+ console.warn("Version pattern not found in README.md, using default");
2584
+ return "v1.0.0";
2585
+ } catch (error) {
2586
+ console.error("Error reading template version:", error.message);
2587
+ return "v1.0.0";
2588
+ }
2589
+ }
2590
+ };
2591
+
2592
+ // ../runtime-shared/dist/utils/defaultEndpointHandler.js
2593
+ var DefaultEndpointHandler = class {
2594
+ /**
2595
+ * Handle the default endpoint with content negotiation
2596
+ * @param context - Function context with config and cache
2597
+ * @param request - HTTP request object with method, path, query, headers, body, params
2598
+ * @param options - Configuration options for the response
2599
+ * @returns HTTP response object with statusCode, headers, and body
2600
+ */
2601
+ static async handle(context, request, options = {}) {
2602
+ const { serviceName = "Sinch Function", companyName = "Your Company", templateVersion = "v1.0.0", availableEndpoints = {} } = options;
2603
+ console.info("Default endpoint called");
2604
+ console.info(`Request: ${request.method} ${request.path}`);
2605
+ const acceptHeader = request.headers?.accept || request.headers?.Accept || "";
2606
+ const wantsHtml = acceptHeader.includes("text/html") || !acceptHeader.includes("application/json") && !acceptHeader.includes("application/*") && !acceptHeader.includes("*/*");
2607
+ if (wantsHtml) {
2608
+ try {
2609
+ const templatePath = TemplateRender.getTemplatePath("index.html");
2610
+ const html = TemplateRender.render(templatePath, {
2611
+ companyName: serviceName,
2612
+ requestId: context.requestId,
2613
+ method: request.method,
2614
+ path: request.path,
2615
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2616
+ templateVersion,
2617
+ runtime: "Node.js"
2618
+ });
2619
+ return {
2620
+ statusCode: 200,
2621
+ headers: {
2622
+ "Content-Type": "text/html; charset=utf-8"
2623
+ },
2624
+ body: html
2625
+ };
2626
+ } catch (error) {
2627
+ console.warn("HTML template not found, returning JSON");
2628
+ }
2629
+ }
2630
+ return {
2631
+ statusCode: 200,
2632
+ headers: {
2633
+ "Content-Type": "application/json"
2634
+ },
2635
+ body: {
2636
+ message: `Welcome to ${serviceName}`,
2637
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2638
+ requestId: context.requestId,
2639
+ method: request.method,
2640
+ path: request.path,
2641
+ availableEndpoints,
2642
+ usage: {
2643
+ html: "Set Accept: text/html header or visit in browser",
2644
+ json: "Set Accept: application/json header or use API client"
2645
+ }
2646
+ }
2647
+ };
2648
+ }
2649
+ };
2475
2650
 
2476
2651
  // ../runtime-shared/dist/utils/functionLoader.js
2477
2652
  import path3 from "path";
2653
+ function findFunctionPath2() {
2654
+ return path3.join(process.cwd(), "dist", "function.js");
2655
+ }
2478
2656
 
2479
2657
  // ../runtime-shared/dist/types/api.js
2480
2658
  function createResponse(statusCode, body, headers) {
@@ -3469,9 +3647,11 @@ var secretsLoader = new SecretsLoader();
3469
3647
  export {
3470
3648
  AceSvamlBuilder,
3471
3649
  AgentProvider,
3650
+ AgentSipHelper,
3472
3651
  ConversationController,
3473
3652
  ConversationMessage,
3474
3653
  ConversationMessageBuilder,
3654
+ DefaultEndpointHandler,
3475
3655
  ElevenLabsAutoConfigurator,
3476
3656
  ElevenLabsClient,
3477
3657
  ElevenLabsController,
@@ -3484,9 +3664,11 @@ export {
3484
3664
  NOTIFICATION_EVENTS,
3485
3665
  PieSvamlBuilder,
3486
3666
  SecretsLoader,
3667
+ TemplateRender,
3487
3668
  TunnelClient,
3488
3669
  UniversalConfig,
3489
3670
  VOICE_CALLBACKS,
3671
+ VersionExtractor,
3490
3672
  VoiceErrorHelper,
3491
3673
  buildBaseContext,
3492
3674
  toCamelCase as convertToCamelCase,
@@ -3495,6 +3677,7 @@ export {
3495
3677
  createCacheClient,
3496
3678
  createChannelMessage,
3497
3679
  createConfig,
3680
+ createConnectAgentAction,
3498
3681
  createElevenLabsClient,
3499
3682
  createErrorResponse,
3500
3683
  createIceBuilder,
@@ -3507,13 +3690,17 @@ export {
3507
3690
  createMessenger,
3508
3691
  createPieBuilder,
3509
3692
  createResponse,
3693
+ createSecurityOptions,
3510
3694
  createSimpleMenu,
3695
+ createSinchRuntime,
3511
3696
  createSms,
3512
3697
  createStorageClient,
3513
3698
  createUniversalConfig,
3514
3699
  createWhatsApp,
3700
+ defaultSecurityOptions,
3515
3701
  extractCallerNumber,
3516
3702
  extractFunctionName,
3703
+ findFunctionPath2 as findFunctionPath,
3517
3704
  formatCustomResponse,
3518
3705
  formatDuration,
3519
3706
  formatPhoneNumber,
@@ -3528,12 +3715,14 @@ export {
3528
3715
  getLocation,
3529
3716
  getMedia,
3530
3717
  getPostbackData,
3718
+ getProtectionMode,
3531
3719
  getSinchClients,
3532
3720
  getText,
3533
3721
  getTo,
3534
3722
  getTunnelClient,
3535
3723
  handleCustomEndpoint,
3536
3724
  handleVoiceCallback,
3725
+ installWebSocketHandlers,
3537
3726
  isMediaMessage,
3538
3727
  isNotificationEvent,
3539
3728
  isPostback,
@@ -3546,12 +3735,14 @@ export {
3546
3735
  setupJsonParsing as setupJsonMiddleware,
3547
3736
  setupJsonParsing,
3548
3737
  setupRequestHandler,
3738
+ shouldValidateWebhook,
3549
3739
  textReply,
3550
3740
  toCamelCase,
3551
3741
  toLocalPhoneNumber,
3552
3742
  transformKeys,
3553
3743
  transformKeys as transformKeysToCamelCase,
3554
3744
  tryAutoConfigureAsync,
3745
+ validateBasicAuth,
3555
3746
  validateVoiceRequest
3556
3747
  };
3557
3748
  //# sourceMappingURL=index.js.map