@sinch/functions-runtime 0.5.18 → 0.5.20

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.
@@ -17,7 +17,7 @@ import {
17
17
  isVoiceV1Callback,
18
18
  secretsLoader,
19
19
  setupRequestHandler
20
- } from "../chunk-VEB6FXNI.js";
20
+ } from "../chunk-4GLU7JTD.js";
21
21
 
22
22
  // ../../node_modules/dotenv/package.json
23
23
  var require_package = __commonJS({
@@ -18129,7 +18129,7 @@ var require_stringify = __commonJS({
18129
18129
  return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint";
18130
18130
  };
18131
18131
  var sentinel = {};
18132
- var stringify = function stringify2(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter2, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) {
18132
+ var stringify2 = function stringify3(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter2, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) {
18133
18133
  var obj = object;
18134
18134
  var tmpSc = sideChannel;
18135
18135
  var step = 0;
@@ -18205,7 +18205,7 @@ var require_stringify = __commonJS({
18205
18205
  sideChannel.set(object, step);
18206
18206
  var valueSideChannel = getSideChannel();
18207
18207
  valueSideChannel.set(sentinel, sideChannel);
18208
- pushToArray(values, stringify2(
18208
+ pushToArray(values, stringify3(
18209
18209
  value,
18210
18210
  keyPrefix,
18211
18211
  generateArrayPrefix,
@@ -18322,7 +18322,7 @@ var require_stringify = __commonJS({
18322
18322
  if (options.skipNulls && value === null) {
18323
18323
  continue;
18324
18324
  }
18325
- pushToArray(keys, stringify(
18325
+ pushToArray(keys, stringify2(
18326
18326
  value,
18327
18327
  key,
18328
18328
  generateArrayPrefix,
@@ -18646,13 +18646,13 @@ var require_parse = __commonJS({
18646
18646
  var require_lib2 = __commonJS({
18647
18647
  "../../node_modules/qs/lib/index.js"(exports, module) {
18648
18648
  "use strict";
18649
- var stringify = require_stringify();
18649
+ var stringify2 = require_stringify();
18650
18650
  var parse2 = require_parse();
18651
18651
  var formats = require_formats();
18652
18652
  module.exports = {
18653
18653
  formats,
18654
18654
  parse: parse2,
18655
- stringify
18655
+ stringify: stringify2
18656
18656
  };
18657
18657
  }
18658
18658
  });
@@ -20413,7 +20413,7 @@ var require_dist = __commonJS({
20413
20413
  exports.compile = compile;
20414
20414
  exports.match = match;
20415
20415
  exports.pathToRegexp = pathToRegexp;
20416
- exports.stringify = stringify;
20416
+ exports.stringify = stringify2;
20417
20417
  var DEFAULT_DELIMITER = "/";
20418
20418
  var NOOP_VALUE = (value) => value;
20419
20419
  var ID_START = /^[$_\p{ID_Start}]$/u;
@@ -20743,7 +20743,7 @@ var require_dist = __commonJS({
20743
20743
  }
20744
20744
  return value;
20745
20745
  }
20746
- function stringify(data) {
20746
+ function stringify2(data) {
20747
20747
  return stringifyTokens(data.tokens);
20748
20748
  }
20749
20749
  function isNameSafe(name) {
@@ -23916,7 +23916,7 @@ var require_response = __commonJS({
23916
23916
  var escape2 = app.get("json escape");
23917
23917
  var replacer = app.get("json replacer");
23918
23918
  var spaces = app.get("json spaces");
23919
- var body = stringify(obj, replacer, spaces, escape2);
23919
+ var body = stringify2(obj, replacer, spaces, escape2);
23920
23920
  if (!this.get("Content-Type")) {
23921
23921
  this.set("Content-Type", "application/json");
23922
23922
  }
@@ -23927,7 +23927,7 @@ var require_response = __commonJS({
23927
23927
  var escape2 = app.get("json escape");
23928
23928
  var replacer = app.get("json replacer");
23929
23929
  var spaces = app.get("json spaces");
23930
- var body = stringify(obj, replacer, spaces, escape2);
23930
+ var body = stringify2(obj, replacer, spaces, escape2);
23931
23931
  var callback = this.req.query[app.get("jsonp callback name")];
23932
23932
  if (!this.get("Content-Type")) {
23933
23933
  this.set("X-Content-Type-Options", "nosniff");
@@ -24235,7 +24235,7 @@ var require_response = __commonJS({
24235
24235
  }
24236
24236
  file.pipe(res2);
24237
24237
  }
24238
- function stringify(value, replacer, spaces, escape2) {
24238
+ function stringify2(value, replacer, spaces, escape2) {
24239
24239
  var json = replacer || spaces ? JSON.stringify(value, replacer, spaces) : JSON.stringify(value);
24240
24240
  if (escape2 && typeof json === "string") {
24241
24241
  json = json.replace(/[<>&]/g, function(c) {
@@ -59962,11 +59962,40 @@ function collectCredentials(value, found = /* @__PURE__ */ new Set()) {
59962
59962
  return found;
59963
59963
  }
59964
59964
 
59965
+ // ../voice-v2-preview/dist/core/json-order.js
59966
+ var ORDER = /* @__PURE__ */ Symbol("matchOrder");
59967
+ function tagOrder(obj, order) {
59968
+ Object.defineProperty(obj, ORDER, { value: order, enumerable: false });
59969
+ return obj;
59970
+ }
59971
+ function stringify(value) {
59972
+ if (value === void 0) {
59973
+ return "null";
59974
+ }
59975
+ if (value === null || typeof value !== "object") {
59976
+ return JSON.stringify(value);
59977
+ }
59978
+ if (Array.isArray(value)) {
59979
+ return `[${value.map((entry) => stringify(entry)).join(",")}]`;
59980
+ }
59981
+ const record = value;
59982
+ const order = value[ORDER] ?? Object.keys(record);
59983
+ const parts = [];
59984
+ for (const key of order) {
59985
+ const entry = record[key];
59986
+ if (entry === void 0)
59987
+ continue;
59988
+ parts.push(`${JSON.stringify(key)}:${stringify(entry)}`);
59989
+ }
59990
+ return `{${parts.join(",")}}`;
59991
+ }
59992
+
59965
59993
  // ../voice-v2-preview/dist/wire/http.js
59966
59994
  var DEFAULT_HOST = "https://voice.api.sinch.com";
59967
59995
  var FETCH_TIMEOUT_MS = 1e4;
59968
59996
  var HttpTransport = class {
59969
59997
  projectId;
59998
+ serviceId;
59970
59999
  host;
59971
60000
  fetchImpl;
59972
60001
  // The Access Key pair is held in ECMAScript private fields, not TypeScript `private` ones.
@@ -59978,6 +60007,7 @@ var HttpTransport = class {
59978
60007
  #keySecret;
59979
60008
  constructor(options) {
59980
60009
  this.projectId = options.projectId;
60010
+ this.serviceId = options.serviceId;
59981
60011
  this.#keyId = options.keyId;
59982
60012
  this.#keySecret = options.keySecret;
59983
60013
  this.host = (options.host ?? DEFAULT_HOST).replace(/\/$/, "");
@@ -59993,7 +60023,8 @@ var HttpTransport = class {
59993
60023
  return { transport: "HttpTransport", projectId: this.projectId, host: this.host };
59994
60024
  }
59995
60025
  async createCall(body) {
59996
- const response = await this.request("POST", "calls", body);
60026
+ const path6 = this.serviceId ? `calls?serviceId=${encodeURIComponent(this.serviceId)}` : "calls";
60027
+ const response = await this.request("POST", path6, body);
59997
60028
  return response;
59998
60029
  }
59999
60030
  async patchCall(target, commands2) {
@@ -60012,7 +60043,7 @@ var HttpTransport = class {
60012
60043
  const response = await this.fetchImpl(url2, {
60013
60044
  method,
60014
60045
  headers: this.authHeaders,
60015
- body: JSON.stringify(body),
60046
+ body: stringify(body),
60016
60047
  signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
60017
60048
  });
60018
60049
  if (!response.ok) {
@@ -60264,6 +60295,14 @@ function resolvePrompt(prompt) {
60264
60295
  }
60265
60296
  return prompt.build();
60266
60297
  }
60298
+ function assertCompilablePattern(pattern) {
60299
+ try {
60300
+ new RegExp(pattern);
60301
+ } catch (err) {
60302
+ const hint = pattern === "*" ? " Use '\\*' to match the DTMF star tone." : " Escape a regular-expression metacharacter you mean literally, e.g. \\* for a literal *.";
60303
+ throw new Error(`Voice v2 menu match key '${pattern}' is not a valid regular expression.${hint} (${err.message})`);
60304
+ }
60305
+ }
60267
60306
  var MenuItemBuilder = class {
60268
60307
  item = {};
60269
60308
  matchOrder = [];
@@ -60342,13 +60381,20 @@ var MenuItemBuilder = class {
60342
60381
  *
60343
60382
  * Keys may be literal digits or regular expressions, and the platform evaluates them in
60344
60383
  * definition order with first match winning — so the order these are written in is part of
60345
- * the behaviour, not decoration. {@link build} refuses to emit a menu whose keys JSON
60346
- * cannot carry in that order; see the error it throws.
60384
+ * the behaviour, not decoration. {@link build} emits `matches` tagged with that order so it
60385
+ * survives `JSON.stringify`, which would otherwise hoist integer-like keys first.
60386
+ *
60387
+ * The platform compiles every key as a regular expression (anchored, `^(?:key)$`), so a bare
60388
+ * metacharacter such as `*` or `+` is not a literal DTMF tone — it is an invalid pattern that
60389
+ * fails at deploy time. `match` rejects those up front instead. Escape a literal you mean, e.g.
60390
+ * `\*` for the star tone.
60347
60391
  *
60348
- * @param pattern - Digits, or a regular expression source
60392
+ * @param pattern - Digits, `#`, or a regular expression source
60349
60393
  * @param flow - Commands to run on a match
60394
+ * @throws If `pattern` does not compile as a regular expression
60350
60395
  */
60351
60396
  match(pattern, flow) {
60397
+ assertCompilablePattern(pattern);
60352
60398
  if (!(pattern in this.matches)) {
60353
60399
  this.matchOrder.push(pattern);
60354
60400
  }
@@ -60364,20 +60410,11 @@ var MenuItemBuilder = class {
60364
60410
  this.item.onFail = resolveFlow(flow);
60365
60411
  return this;
60366
60412
  }
60367
- /**
60368
- * Emit the menu.
60369
- *
60370
- * @throws If the `matches` keys cannot be serialised in the order they were written
60371
- */
60413
+ /** Emit the menu. */
60372
60414
  build() {
60373
60415
  const item = { ...this.item };
60374
60416
  if (this.matchOrder.length > 0) {
60375
- const emitted = Object.keys(this.matches);
60376
- const reordered = emitted.some((key, index) => key !== this.matchOrder[index]);
60377
- if (reordered) {
60378
- throw new Error(`Voice v2 menu matches are evaluated in definition order, but JSON cannot carry these keys in the order they were written (${this.matchOrder.join(", ")} would be sent as ${emitted.join(", ")}). Numeric keys always sort first, ascending. Write them in ascending numeric order, or use a regular-expression key such as '^1$'.`);
60379
- }
60380
- item.matches = { ...this.matches };
60417
+ item.matches = tagOrder({ ...this.matches }, this.matchOrder);
60381
60418
  }
60382
60419
  return item;
60383
60420
  }
@@ -60770,6 +60807,9 @@ var Client = class {
60770
60807
  projectId: options.projectId ?? env.PROJECT_ID ?? context?.config?.projectId ?? "",
60771
60808
  keyId: options.keyId ?? env.PROJECT_ID_API_KEY ?? "",
60772
60809
  keySecret: options.keySecret ?? env.PROJECT_ID_API_SECRET ?? "",
60810
+ ...(options.serviceId ?? env.VOICE_SERVICE_ID) !== void 0 && {
60811
+ serviceId: options.serviceId ?? env.VOICE_SERVICE_ID
60812
+ },
60773
60813
  ...options.host !== void 0 && { host: options.host },
60774
60814
  ...options.fetch !== void 0 && { fetch: options.fetch }
60775
60815
  });
@@ -61187,9 +61227,23 @@ function attachVoiceClient(context, v1) {
61187
61227
  });
61188
61228
  return context;
61189
61229
  }
61230
+ function bindHandler(handler, context, request) {
61231
+ return handler ? (event) => handler(event, context, request) : void 0;
61232
+ }
61190
61233
  function onCall(handlers) {
61191
- return async (context, event) => {
61192
- const response = await context.voice.onCall(handlers)(event);
61234
+ return async (context, event, request) => {
61235
+ const bind2 = (handler) => bindHandler(handler, context, request);
61236
+ const bound = {
61237
+ incoming: bind2(handlers.incoming),
61238
+ answered: bind2(handlers.answered),
61239
+ manage: bind2(handlers.manage),
61240
+ completed: bind2(handlers.completed),
61241
+ fallback: bind2(handlers.fallback),
61242
+ ...handlers.webhooks && {
61243
+ webhooks: Object.fromEntries(Object.entries(handlers.webhooks).map(([name, handler]) => [name, (event2) => handler(event2, context, request)]))
61244
+ }
61245
+ };
61246
+ const response = await context.voice.onCall(bound)(event);
61193
61247
  if (!response) {
61194
61248
  return void 0;
61195
61249
  }
@@ -61866,12 +61920,12 @@ async function handleVoiceV1Callback(functionName, userFunction, context, callba
61866
61920
  }
61867
61921
  return formatSvamlResponse(result2, functionName);
61868
61922
  }
61869
- async function handleVoiceWebhook(userFunction, context, event, logger) {
61923
+ async function handleVoiceWebhook(userFunction, context, event, request, logger) {
61870
61924
  const handler = userFunction[VOICE_WEBHOOK_HANDLER];
61871
61925
  if (!handler || typeof handler !== "function") {
61872
61926
  throw new Error(`No export '${VOICE_WEBHOOK_HANDLER}' found for Voice v2 event '${event?.event}'. Export one built with onCall({ incoming: ... }), or drop VOICE_SERVICE_ID to stay on the v1 ice/ace/pie/dice callbacks.`);
61873
61927
  }
61874
- const result2 = await handler(context, event);
61928
+ const result2 = await handler(context, event, request);
61875
61929
  if (logger) {
61876
61930
  logger("Function result:", result2);
61877
61931
  }
@@ -61882,7 +61936,7 @@ async function handleVoiceWebhook(userFunction, context, event, logger) {
61882
61936
  return formatCustomResponse(result2);
61883
61937
  }
61884
61938
  const body = await context.voice.onCall({ fallback: () => result2 })(event);
61885
- return body === void 0 ? { statusCode: 204 } : { statusCode: 200, headers: { "Content-Type": "application/json" }, body };
61939
+ return body === void 0 ? { statusCode: 204 } : { statusCode: 200, headers: { "Content-Type": "application/json" }, body: stringify(body) };
61886
61940
  }
61887
61941
  function isVoiceResult(result2) {
61888
61942
  return Array.isArray(result2) || result2 instanceof CommandBuilder || typeof result2 === "object" && Array.isArray(result2.commands);
@@ -62050,6 +62104,14 @@ function setupRequestHandler(app, options = {}) {
62050
62104
  onRequestStart({ functionName, req });
62051
62105
  const context = buildContext(req);
62052
62106
  const userFunction = await Promise.resolve(loadUserFunction());
62107
+ const request = {
62108
+ method: req.method,
62109
+ path: req.path,
62110
+ query: req.query,
62111
+ headers: req.headers,
62112
+ body: req.body,
62113
+ params: req.params
62114
+ };
62053
62115
  let response;
62054
62116
  if (isVoiceV1Callback(functionName)) {
62055
62117
  const validation = validateVoiceV1Request(req.body);
@@ -62062,16 +62124,8 @@ function setupRequestHandler(app, options = {}) {
62062
62124
  }
62063
62125
  response = await handleVoiceV1Callback(functionName, userFunction, context, req.body, logger);
62064
62126
  } else if (functionName === VOICE_WEBHOOK_HANDLER && isVoiceWebhook(req.body)) {
62065
- response = await handleVoiceWebhook(userFunction, context, req.body, logger);
62127
+ response = await handleVoiceWebhook(userFunction, context, req.body, request, logger);
62066
62128
  } else {
62067
- const request = {
62068
- method: req.method,
62069
- path: req.path,
62070
- query: req.query,
62071
- headers: req.headers,
62072
- body: req.body,
62073
- params: req.params
62074
- };
62075
62129
  response = await handleCustomEndpoint(functionName, userFunction, context, request, logger);
62076
62130
  }
62077
62131
  res.status(response.statusCode);
@@ -62085,6 +62139,8 @@ function setupRequestHandler(app, options = {}) {
62085
62139
  const isHtmlContent = contentType?.includes("text/html");
62086
62140
  if (response.body === void 0) {
62087
62141
  res.end();
62142
+ } else if (isJsonContent && typeof response.body === "string") {
62143
+ res.send(response.body);
62088
62144
  } else if (isJsonContent) {
62089
62145
  res.json(response.body);
62090
62146
  } else if (isHtmlContent) {
@@ -71338,6 +71394,7 @@ export {
71338
71394
  createUniversalConfig,
71339
71395
  REDACTED,
71340
71396
  redactCredentials,
71397
+ stringify,
71341
71398
  DEFAULT_HOST,
71342
71399
  DEFAULT_SAMPLE_RATE,
71343
71400
  DEFAULT_VOICE,
@@ -71739,4 +71796,4 @@ serve-static/index.js:
71739
71796
  * MIT Licensed
71740
71797
  *)
71741
71798
  */
71742
- //# sourceMappingURL=chunk-VEB6FXNI.js.map
71799
+ //# sourceMappingURL=chunk-4GLU7JTD.js.map