ssml-builder-js 2.15.0 → 2.16.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 CHANGED
@@ -913,7 +913,9 @@ result.bookmarks; // { name, audioOffsetMs }[]
913
913
 
914
914
  長文を分割して合成する場合は `synthesizeSsmlChunks` または `AzureTtsClient.synthesizeChunks` を使います。音声バイナリを連結し、`boundaries`、`visemes`、`bookmarks` のオフセットを累積 `durationMs` 分だけ補正します。`synthesizeSsmlSafe(client, ssml, { validation })` は検証エラー時に Azure API を呼び出さず、`status: "validation-error"` / `"azure-api-error"` / `"success"` の結果を返します。
915
915
 
916
- v2.15.0 では `synthesizeSsmlChunksSafe(client, chunks, options)` が全チャンクを事前検証し、`outputFormat`、`signal`、`timeoutMs`、`sourceNodePath` を各合成へ伝播します。`mergeAudioBuffers(buffers, { format })` と `mergeSynthesisResults(results, { format })` は形式指定を必須とし、結合結果には `mimeType` が含まれます。Ogg/WebM などは `customMerger` で外部 Muxer に委譲できます。エラーは `validation-error`、`azure-api-error`、`merge-error`、`unsupported-format-error`、`cancelled`、`timeout` の判別可能な `kind` を持ちます。同期イベントは個別の `sourceNodePath` と `originalTextRange` にマッピングされ、URL 検証コールバックには `AbortSignal` が渡されます。
916
+ v2.15.0 では `synthesizeSsmlChunksSafe(client, chunks, options)` が全チャンクを事前検証し、`outputFormat`、`signal`、`timeoutMs`、`sourceNodePath` を各合成へ伝播します。`mergeAudioBuffers(buffers, { format })` と `mergeSynthesisResults(results, { format })` は形式指定を必須とし、結合結果には `mimeType` が含まれます。Ogg/WebM などは `customMerger` で外部 Muxer に委譲できます。エラーは `validation-error`、`azure-api-error`、`merge-error`、`unsupported-format-error`、`cancelled`、`timeout` の判別可能な `kind` を持ちます。同期イベントは個別の `sourceNodePath` と `originalTextRange` にマッピングされ、URL 検証コールバックには `AbortSignal` が渡されます。
917
+
918
+ v2.16.0 では `concurrency` と `retryOptions`(429/5xx・ネットワーク障害のみ、Jitter 付き指数バックオフ)でチャンク合成を制御できます。`onProgress` には `retryAttempt`、`nextRetryDelayMs`、`isRetrying` が追加され、結合は常に `chunkIndex` 順です。`SsmlSynthesisResult.audioSpec` は WAV/MP3 ヘッダーから音声仕様を抽出し、チャンク間の仕様不一致は `AudioFormatMismatchError` になります。同期イベントには `mappingStatus`、Azure 診断には `nodePath`、`range`、`tagName`、`attributeName`、`voiceName`、`chunkIndex` が含まれます。`validateAzureSsmlChunks` は URL 検証プールを全チャンクで共有し、カスタム結合器には `inputSpecs` と `signal` を渡します。
917
919
 
918
920
  `validateAzureSsml` の `urlValidation` オプションは URL の重複排除、キャッシュ、`concurrency`、`signal`、`timeoutMs` を制御します。
919
921
 
@@ -921,6 +923,8 @@ For long documents, use `synthesizeSsmlChunks` or `AzureTtsClient.synthesizeChun
921
923
 
922
924
  In v2.15.0, `synthesizeSsmlChunksSafe(client, chunks, options)` validates every chunk before contacting Azure and propagates `outputFormat`, `signal`, `timeoutMs`, and `sourceNodePath` to each synthesis. `mergeAudioBuffers(buffers, { format })` and `mergeSynthesisResults(results, { format })` require an explicit format and merged results expose `mimeType`. Ogg and WebM can be delegated to an external Muxer through `customMerger`. Errors have discriminated `kind` values: `validation-error`, `azure-api-error`, `merge-error`, `unsupported-format-error`, `cancelled`, and `timeout`. Synchronization events receive individual `sourceNodePath` and `originalTextRange` mappings, and URL validators receive an `AbortSignal`.
923
925
 
926
+ In v2.16.0, use `concurrency` and `retryOptions` to control chunk synthesis; only 429/5xx and network failures are retried with jittered exponential backoff. Progress events include `retryAttempt`, `nextRetryDelayMs`, and `isRetrying`, while merging always follows `chunkIndex` order. `SsmlSynthesisResult.audioSpec` is extracted from WAV/MP3 headers, and incompatible chunk specs throw `AudioFormatMismatchError`. Synchronization events include `mappingStatus`, diagnostics include structured node/range/tag/attribute/voice/chunk fields, `validateAzureSsmlChunks` shares one URL validation pool, and custom mergers receive `inputSpecs` and an `AbortSignal`.
927
+
924
928
  The `urlValidation` option of `validateAzureSsml` provides URL deduplication, in-memory caching, bounded `concurrency`, `signal`, and `timeoutMs` controls.
925
929
 
926
930
  The public updater CLI is `npx ssml-builder sync-voices --region eastus --output ./azure-voices.json`. It reads the key from `AZURE_SPEECH_KEY` (or `--key`) and regions from `AZURE_SPEECH_REGION(S)` (or `--region(s)`).
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  buildSsml,
3
3
  parseSsml
4
- } from "./chunk-WXFLUCLR.mjs";
4
+ } from "./chunk-HI74FTKY.mjs";
5
5
  import {
6
6
  __export
7
7
  } from "./chunk-6S5ODO6A.mjs";
@@ -3112,4 +3112,4 @@ export {
3112
3112
  findSsmlHoverTarget,
3113
3113
  formatSsmlHover
3114
3114
  };
3115
- //# sourceMappingURL=chunk-BDY2Q2JL.mjs.map
3115
+ //# sourceMappingURL=chunk-F2EMU3HM.mjs.map
@@ -1374,6 +1374,7 @@ function tokenizeElements(source) {
1374
1374
  if (parent) parent.childElementCount += 1;
1375
1375
  const parentVoiceName = [...openElements].reverse().find((element) => element.voiceName)?.voiceName;
1376
1376
  const tokenName = nameMatch[1];
1377
+ const path = parent ? [...parent.path, `${tokenName}[${childElementIndex ?? 0}]`] : [tokenName];
1377
1378
  const tokenVoiceName = tokenName.toLowerCase() === "voice" ? attributes.get("name") : tokenName.toLowerCase() === "mstts:turn" ? attributes.get("voice") ?? parentVoiceName : parentVoiceName;
1378
1379
  tokens.push({
1379
1380
  attributes,
@@ -1384,12 +1385,14 @@ function tokenizeElements(source) {
1384
1385
  parentName: parent?.name,
1385
1386
  parentVoiceName,
1386
1387
  selfClosing,
1387
- start
1388
+ start,
1389
+ path
1388
1390
  });
1389
1391
  if (!selfClosing) {
1390
1392
  openElements.push({
1391
1393
  childElementCount: 0,
1392
1394
  name: tokenName,
1395
+ path,
1393
1396
  voiceName: tokenVoiceName
1394
1397
  });
1395
1398
  }
@@ -1402,13 +1405,14 @@ function location(source, offset) {
1402
1405
  const line = before.split("\n").length;
1403
1406
  return { line, column: before.length - (before.lastIndexOf("\n") + 1) + 1 };
1404
1407
  }
1405
- function addDiagnostic(diagnostics, source, offset, message, severity = "error", code) {
1408
+ function addDiagnostic(diagnostics, source, offset, message, severity = "error", code, metadata = {}) {
1406
1409
  diagnostics.push({
1407
1410
  ...location(source, offset),
1408
1411
  message,
1409
1412
  severity,
1410
1413
  source: "ssml-static-validator",
1411
- ...code ? { code } : {}
1414
+ ...code ? { code } : {},
1415
+ ...metadata
1412
1416
  });
1413
1417
  }
1414
1418
  function isSupportedProsodyRate(value) {
@@ -1871,9 +1875,11 @@ function validateAzureSsmlStatic(ssml, options = {}) {
1871
1875
  for (const token of tokens) {
1872
1876
  const tokenName = token.name.toLowerCase();
1873
1877
  const tokenVoiceName = tokenName === "voice" ? attr(token, "name")?.trim() : tokenName === "mstts:turn" ? attr(token, "voice")?.trim() || token.parentVoiceName : options.validateNestedVoices === false ? voiceName : token.parentVoiceName;
1878
+ const tokenDiagnosticStart = diagnostics.length;
1874
1879
  validateElement(token, ssml, diagnostics, tokenVoiceName, options, voiceCatalog);
1875
1880
  const definition = tokenVoiceName ? voiceCatalog.get(tokenVoiceName.toLowerCase()) : void 0;
1876
1881
  validateVoiceFeatureMatrix(token, ssml, diagnostics, tokenVoiceName, definition);
1882
+ annotateTokenDiagnostics(diagnostics, tokenDiagnosticStart, token, options, tokenVoiceName);
1877
1883
  if (tokenName === "voice" && options.model && definition?.models && !definition.models.some((model) => model.toLowerCase() === options.model?.toLowerCase())) {
1878
1884
  addDiagnostic(
1879
1885
  diagnostics,
@@ -1895,12 +1901,30 @@ function urlAttributes(token) {
1895
1901
  return value === void 0 ? [] : [{ attribute, value }];
1896
1902
  });
1897
1903
  }
1904
+ function annotateTokenDiagnostics(diagnostics, startIndex, token, options, voiceName) {
1905
+ const attributes = [...token.attributes.keys()];
1906
+ for (const diagnostic of diagnostics.slice(startIndex)) {
1907
+ const attributeName = attributes.find(
1908
+ (attribute) => new RegExp(`(?:<[^> ]+\\s+|")${attribute}(?:"|>|\\s)`, "i").test(diagnostic.message)
1909
+ );
1910
+ const nodePath = options.sourceNodePath ? [...options.sourceNodePath] : [...token.path];
1911
+ Object.assign(diagnostic, {
1912
+ range: { start: token.start, end: token.end + 1 },
1913
+ tagName: token.name,
1914
+ ...attributeName ? { attributeName } : {},
1915
+ ...voiceName ? { voiceName } : {},
1916
+ ...options.chunkIndex !== void 0 ? { chunkIndex: options.chunkIndex } : {},
1917
+ nodePath,
1918
+ targetNodePath: [...token.path]
1919
+ });
1920
+ }
1921
+ }
1898
1922
  function validateAzureSsml(ssml, options = {}) {
1899
1923
  const diagnostics = validateAzureSsmlStatic(ssml, options);
1900
1924
  const validator = options.urlValidator ?? options.customUrlValidator;
1901
1925
  if (!validator || typeof ssml !== "string") return diagnostics;
1902
1926
  const runnerOptions = options.urlValidation ?? {};
1903
- const boundedValidator = createAzureUrlValidatorRunner(validator, {
1927
+ const boundedValidator = options.urlValidatorRunner ?? createAzureUrlValidatorRunner(validator, {
1904
1928
  ...runnerOptions,
1905
1929
  ...options.urlValidatorConcurrency !== void 0 ? { concurrency: options.urlValidatorConcurrency } : {},
1906
1930
  ...options.urlValidatorTimeoutMs !== void 0 ? { timeoutMs: options.urlValidatorTimeoutMs } : {},
@@ -1925,21 +1949,25 @@ function validateAzureSsml(ssml, options = {}) {
1925
1949
  const valid = typeof result === "boolean" ? result : result.valid;
1926
1950
  if (!valid) {
1927
1951
  const reason = typeof result === "boolean" ? void 0 : result.reason;
1952
+ const diagnosticStart = diagnostics.length;
1928
1953
  addDiagnostic(
1929
1954
  diagnostics,
1930
1955
  ssml,
1931
1956
  token.start,
1932
1957
  `<${token.name} ${attribute}> was rejected by the custom URL validator${reason ? `: ${reason}` : "."}`
1933
1958
  );
1959
+ annotateTokenDiagnostics(diagnostics, diagnosticStart, token, options, token.parentVoiceName);
1934
1960
  }
1935
1961
  } catch (error) {
1936
1962
  const reason = error instanceof Error ? error.message : String(error);
1963
+ const diagnosticStart = diagnostics.length;
1937
1964
  addDiagnostic(
1938
1965
  diagnostics,
1939
1966
  ssml,
1940
1967
  token.start,
1941
1968
  `<${token.name} ${attribute}> could not be validated by the custom URL validator: ${reason}`
1942
1969
  );
1970
+ annotateTokenDiagnostics(diagnostics, diagnosticStart, token, options, token.parentVoiceName);
1943
1971
  }
1944
1972
  })
1945
1973
  );
@@ -1958,6 +1986,7 @@ export {
1958
1986
  buildPartialSsml,
1959
1987
  getSsmlSourceMap,
1960
1988
  validateSsml,
1989
+ createAzureUrlValidatorRunner,
1961
1990
  validateAzureSsml
1962
1991
  };
1963
- //# sourceMappingURL=chunk-WXFLUCLR.mjs.map
1992
+ //# sourceMappingURL=chunk-HI74FTKY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../packages/ssml-core/src/constants/ssml.ts","../packages/ssml-core/src/builder.ts","../packages/ssml-core/src/parser.ts","../packages/ssml-core/src/partial.ts","../packages/ssml-core/src/textNodes.ts","../packages/ssml-core/src/split.ts","../packages/ssml-core/src/validation.ts","../packages/ssml-core/src/migration.ts","../packages/ssml-core/src/generated/azureVoiceDefinitions.ts","../packages/ssml-core/src/azureValidation.ts","../packages/ssml-core/src/generated/azureVoiceCatalog.ts","../packages/ssml-core/src/voiceCatalog.ts"],"sourcesContent":["export const SYNTHESIS_NAMESPACE = \"http://www.w3.org/2001/10/synthesis\" as const;\nexport const MSTTS_NAMESPACE = \"http://www.w3.org/2001/mstts\" as const;\nexport const DEFAULT_SSML_VERSION = \"1.0\" as const;\nexport const DEFAULT_SSML_LANGUAGE = \"en-US\" as const;\nexport const MAX_NESTING_DEPTH = 1000;\nexport const XML_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_.:-]*$/;\nexport const MSTTS_TAG_PREFIX = \"mstts:\" as const;\n\nexport const SSML_TAGS = {\n SPEAK: \"speak\",\n VOICE: \"voice\",\n PROSODY: \"prosody\",\n BREAK: \"break\",\n EXPRESS_AS: \"express-as\",\n EXPRESS_AS_CAMEL: \"expressAs\",\n MSTTS_EXPRESS_AS: \"mstts:express-as\",\n SAY_AS: \"say-as\",\n SAY_AS_CAMEL: \"sayAs\",\n PHONEME: \"phoneme\",\n EMPHASIS: \"emphasis\",\n AUDIO: \"audio\",\n SUB: \"sub\",\n LANG: \"lang\",\n MARK: \"mark\",\n BOOKMARK: \"bookmark\",\n LEXICON: \"lexicon\",\n PARAGRAPH: \"p\",\n SENTENCE: \"s\",\n WORD: \"w\",\n MSTTS_SILENCE: \"mstts:silence\",\n SILENCE: \"silence\",\n MSTTS_VISEME: \"mstts:viseme\",\n VISEME: \"viseme\",\n MSTTS_AUDIO_DURATION: \"mstts:audioduration\",\n MSTTS_DIALOG: \"mstts:dialog\",\n MSTTS_TURN: \"mstts:turn\",\n MSTTS_BACKGROUND_AUDIO: \"mstts:backgroundaudio\",\n MSTTS_TTS_EMBEDDING: \"mstts:ttsembedding\",\n MSTTS_EMBEDDING: \"mstts:embedding\",\n MSTTS_VOICE_CONVERSION: \"mstts:voiceconversion\",\n} as const;\n\nexport const SSML_ATTRS = {\n VERSION: \"version\",\n XMLNS: \"xmlns\",\n XML_LANG: \"xml:lang\",\n LANG: \"lang\",\n MSTTS_XMLNS: \"xmlns:mstts\",\n NAME: \"name\",\n VOICE: \"voice\",\n SPEAKER: \"speaker\",\n EFFECT: \"effect\",\n RATE: \"rate\",\n PITCH: \"pitch\",\n VOLUME: \"volume\",\n CONTOUR: \"contour\",\n RANGE: \"range\",\n TIME: \"time\",\n STRENGTH: \"strength\",\n STYLE: \"style\",\n STYLE_DEGREE: \"styledegree\",\n STYLE_DEGREE_CAMEL: \"styleDegree\",\n STYLE_DEGREE_HYPHEN: \"style-degree\",\n ROLE: \"role\",\n INTERPRET_AS: \"interpret-as\",\n FORMAT: \"format\",\n DETAIL: \"detail\",\n ALPHABET: \"alphabet\",\n PH: \"ph\",\n LEVEL: \"level\",\n SRC: \"src\",\n DESC: \"desc\",\n CLIP_BEGIN: \"clipBegin\",\n CLIP_END: \"clipEnd\",\n SPEED: \"speed\",\n REPEAT_COUNT: \"repeatCount\",\n REPEAT_DURATION: \"repeatDuration\",\n SOUND_LEVEL: \"soundLevel\",\n ALIAS: \"alias\",\n MARK: \"mark\",\n URI: \"uri\",\n ID: \"id\",\n MODEL: \"model\",\n PROFILE: \"profile\",\n URL: \"url\",\n SPEAKER_PROFILE_ID: \"speakerProfileId\",\n TYPE: \"type\",\n VALUE: \"value\",\n FADE_IN: \"fadein\",\n FADE_OUT: \"fadeout\",\n} as const;\n","import type {\n SsmlAttributeValue,\n SsmlAttributes,\n SsmlDocument,\n SsmlElement,\n SsmlElementBase,\n SsmlNode,\n} from \"./types.ts\";\nimport {\n DEFAULT_SSML_LANGUAGE,\n DEFAULT_SSML_VERSION,\n MSTTS_NAMESPACE,\n MSTTS_TAG_PREFIX,\n SSML_ATTRS,\n SSML_TAGS,\n SYNTHESIS_NAMESPACE,\n XML_NAME_PATTERN,\n} from \"./constants/ssml.ts\";\n\nfunction escapeText(value: string): string {\n return value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction escapeAttribute(value: string): string {\n return escapeText(value).replace(/\"/g, \"&quot;\").replace(/'/g, \"&apos;\");\n}\n\nfunction addAttribute(attributes: SsmlAttributes, name: string, value: SsmlAttributeValue | undefined): void {\n if (value !== undefined) {\n attributes[name] = value;\n }\n}\n\nfunction getAttributes(element: SsmlElement): SsmlAttributes {\n const attributes: SsmlAttributes = {\n ...(element.attributes ?? {}),\n };\n\n switch (element.type) {\n case SSML_TAGS.VOICE:\n addAttribute(attributes, SSML_ATTRS.NAME, element.name);\n addAttribute(attributes, SSML_ATTRS.EFFECT, element.effect);\n break;\n case SSML_TAGS.PROSODY:\n addAttribute(attributes, SSML_ATTRS.RATE, element.rate);\n addAttribute(attributes, SSML_ATTRS.PITCH, element.pitch);\n addAttribute(attributes, SSML_ATTRS.VOLUME, element.volume);\n addAttribute(attributes, SSML_ATTRS.CONTOUR, element.contour);\n addAttribute(attributes, SSML_ATTRS.RANGE, element.range);\n break;\n case SSML_TAGS.BREAK:\n addAttribute(attributes, SSML_ATTRS.TIME, element.time);\n addAttribute(attributes, SSML_ATTRS.STRENGTH, element.strength);\n break;\n case SSML_TAGS.EXPRESS_AS:\n case SSML_TAGS.EXPRESS_AS_CAMEL:\n case SSML_TAGS.MSTTS_EXPRESS_AS:\n addAttribute(attributes, SSML_ATTRS.STYLE, element.style);\n addAttribute(attributes, SSML_ATTRS.STYLE_DEGREE, element.styleDegree);\n addAttribute(attributes, SSML_ATTRS.ROLE, element.role);\n break;\n case SSML_TAGS.SAY_AS:\n case SSML_TAGS.SAY_AS_CAMEL:\n addAttribute(attributes, SSML_ATTRS.INTERPRET_AS, element.interpretAs);\n addAttribute(attributes, SSML_ATTRS.FORMAT, element.format);\n addAttribute(attributes, SSML_ATTRS.DETAIL, element.detail);\n break;\n case SSML_TAGS.PHONEME:\n addAttribute(attributes, SSML_ATTRS.ALPHABET, element.alphabet);\n addAttribute(attributes, SSML_ATTRS.PH, element.ph);\n break;\n case SSML_TAGS.EMPHASIS:\n addAttribute(attributes, SSML_ATTRS.LEVEL, element.level);\n break;\n case SSML_TAGS.AUDIO:\n addAttribute(attributes, SSML_ATTRS.SRC, element.src);\n addAttribute(attributes, SSML_ATTRS.DESC, element.desc);\n addAttribute(attributes, SSML_ATTRS.CLIP_BEGIN, element.clipBegin);\n addAttribute(attributes, SSML_ATTRS.CLIP_END, element.clipEnd);\n addAttribute(attributes, SSML_ATTRS.SPEED, element.speed);\n addAttribute(attributes, SSML_ATTRS.REPEAT_COUNT, element.repeatCount);\n addAttribute(attributes, SSML_ATTRS.REPEAT_DURATION, element.repeatDuration);\n addAttribute(attributes, SSML_ATTRS.SOUND_LEVEL, element.soundLevel);\n break;\n case SSML_TAGS.SUB:\n addAttribute(attributes, SSML_ATTRS.ALIAS, element.alias);\n break;\n case SSML_TAGS.LANG:\n addAttribute(attributes, SSML_ATTRS.XML_LANG, element.lang);\n break;\n case SSML_TAGS.MARK:\n addAttribute(attributes, SSML_ATTRS.NAME, element.name);\n break;\n case SSML_TAGS.BOOKMARK:\n addAttribute(attributes, SSML_ATTRS.MARK, element.mark);\n break;\n case SSML_TAGS.LEXICON:\n addAttribute(attributes, SSML_ATTRS.URI, element.uri);\n break;\n case SSML_TAGS.MSTTS_SILENCE:\n case SSML_TAGS.SILENCE:\n addAttribute(attributes, SSML_ATTRS.TYPE, element.typeValue ?? element.silenceType);\n addAttribute(attributes, SSML_ATTRS.VALUE, element.value);\n break;\n case SSML_TAGS.MSTTS_VISEME:\n case SSML_TAGS.VISEME:\n addAttribute(attributes, SSML_ATTRS.TYPE, element.typeValue ?? element.visemeType);\n break;\n case SSML_TAGS.MSTTS_AUDIO_DURATION:\n addAttribute(attributes, SSML_ATTRS.VALUE, element.value);\n break;\n case SSML_TAGS.MSTTS_TURN:\n addAttribute(attributes, SSML_ATTRS.VOICE, element.voice);\n addAttribute(attributes, SSML_ATTRS.SPEAKER, element.speaker);\n break;\n case SSML_TAGS.MSTTS_BACKGROUND_AUDIO:\n addAttribute(attributes, SSML_ATTRS.SRC, element.src);\n addAttribute(attributes, SSML_ATTRS.VOLUME, element.volume);\n addAttribute(attributes, SSML_ATTRS.FADE_IN, element.fadeIn ?? element.fadein);\n addAttribute(attributes, SSML_ATTRS.FADE_OUT, element.fadeOut ?? element.fadeout);\n break;\n case SSML_TAGS.MSTTS_DIALOG:\n break;\n case SSML_TAGS.MSTTS_TTS_EMBEDDING:\n addAttribute(attributes, SSML_ATTRS.SPEAKER_PROFILE_ID, element.speakerProfileId);\n break;\n case SSML_TAGS.MSTTS_EMBEDDING:\n addAttribute(attributes, SSML_ATTRS.ID, element.id);\n addAttribute(attributes, SSML_ATTRS.SPEAKER_PROFILE_ID, element.speakerProfileId);\n break;\n case SSML_TAGS.MSTTS_VOICE_CONVERSION:\n addAttribute(attributes, SSML_ATTRS.URL, element.url);\n addAttribute(attributes, SSML_ATTRS.PROFILE, element.profile);\n addAttribute(attributes, SSML_ATTRS.SPEAKER_PROFILE_ID, element.speakerProfileId);\n break;\n case SSML_TAGS.PARAGRAPH:\n case SSML_TAGS.SENTENCE:\n case SSML_TAGS.WORD:\n case \"element\":\n case \"custom\":\n break;\n }\n\n return attributes;\n}\n\nfunction getTagName(element: SsmlElement): string {\n switch (element.type) {\n case SSML_TAGS.EXPRESS_AS:\n case SSML_TAGS.EXPRESS_AS_CAMEL:\n case SSML_TAGS.MSTTS_EXPRESS_AS:\n return SSML_TAGS.MSTTS_EXPRESS_AS;\n case SSML_TAGS.SAY_AS:\n case SSML_TAGS.SAY_AS_CAMEL:\n return SSML_TAGS.SAY_AS;\n case SSML_TAGS.SILENCE:\n case SSML_TAGS.MSTTS_SILENCE:\n return SSML_TAGS.MSTTS_SILENCE;\n case SSML_TAGS.VISEME:\n case SSML_TAGS.MSTTS_VISEME:\n return SSML_TAGS.MSTTS_VISEME;\n case SSML_TAGS.MSTTS_AUDIO_DURATION:\n return SSML_TAGS.MSTTS_AUDIO_DURATION;\n case \"element\":\n case \"custom\":\n return element.name;\n default:\n return element.type;\n }\n}\n\nfunction getChildren(element: SsmlElementBase): SsmlNode[] {\n return element.children ?? [];\n}\n\nfunction validateName(name: string, kind: \"element\" | \"attribute\"): void {\n if (!XML_NAME_PATTERN.test(name)) {\n throw new Error(`Invalid XML ${kind} name: ${name}`);\n }\n}\n\nfunction serializeAttributes(attributes: SsmlAttributes): string {\n return Object.entries(attributes)\n .map(([name, value]) => {\n validateName(name, \"attribute\");\n return ` ${name}=\"${escapeAttribute(String(value))}\"`;\n })\n .join(\"\");\n}\n\nfunction serializeNode(node: SsmlNode): string {\n if (typeof node === \"string\") {\n return escapeText(node);\n }\n\n if (node.type === \"text\") {\n return escapeText(node.value);\n }\n\n const tagName = getTagName(node);\n validateName(tagName, \"element\");\n\n const attributes = serializeAttributes(getAttributes(node));\n const children = getChildren(node);\n if (children.length === 0) {\n return `<${tagName}${attributes}/>`;\n }\n\n return `<${tagName}${attributes}>${children.map(serializeNode).join(\"\")}</${tagName}>`;\n}\n\nfunction usesMsttsNamespace(nodes: SsmlNode[]): boolean {\n return nodes.some((node) => {\n if (typeof node === \"string\" || node.type === \"text\") {\n return false;\n }\n\n const tagName = getTagName(node);\n return tagName.startsWith(MSTTS_TAG_PREFIX) || usesMsttsNamespace(getChildren(node));\n });\n}\n\nfunction serializeDocument(document: SsmlDocument): string {\n const children = document.children ?? (document.content === undefined ? [] : [document.content]);\n const attributes: SsmlAttributes = {\n ...(document.attributes ?? {}),\n [SSML_ATTRS.VERSION]: document.version,\n [SSML_ATTRS.XMLNS]: SYNTHESIS_NAMESPACE,\n [SSML_ATTRS.XML_LANG]: document.lang,\n };\n\n if (usesMsttsNamespace(children) && attributes[SSML_ATTRS.MSTTS_XMLNS] === undefined) {\n attributes[SSML_ATTRS.MSTTS_XMLNS] = MSTTS_NAMESPACE;\n }\n\n return `<${SSML_TAGS.SPEAK}${serializeAttributes(attributes)}>${children.map(serializeNode).join(\"\")}</${SSML_TAGS.SPEAK}>`;\n}\n\nexport function buildSsml(document: SsmlDocument): string;\nexport function buildSsml(content: string, lang?: string): SsmlDocument;\nexport function buildSsml(\n documentOrContent: SsmlDocument | string,\n lang: string = DEFAULT_SSML_LANGUAGE,\n): string | SsmlDocument {\n if (typeof documentOrContent === \"string\") {\n return {\n version: DEFAULT_SSML_VERSION,\n lang,\n content: documentOrContent,\n };\n }\n\n return serializeDocument(documentOrContent);\n}\n","import type {\n AudioElement,\n BookmarkElement,\n BreakElement,\n CustomElement,\n EmphasisElement,\n ExpressAsElement,\n LangElement,\n LexiconElement,\n MarkElement,\n MsttsSilenceElement,\n MsttsVisemeElement,\n MsttsAudioDurationElement,\n MsttsEmbeddingElement,\n MsttsTtsEmbeddingElement,\n MsttsVoiceConversionElement,\n ParagraphElement,\n PhonemeElement,\n ProsodyElement,\n SayAsElement,\n SentenceElement,\n SsmlAttributes,\n SsmlBackgroundAudioNode,\n SsmlDialogNode,\n SsmlDocument,\n SsmlElement,\n SsmlNode,\n SsmlTurnNode,\n SubElement,\n VoiceElement,\n WordElement,\n} from \"./types.ts\";\nimport { MAX_NESTING_DEPTH, MSTTS_NAMESPACE, SSML_ATTRS, SSML_TAGS, SYNTHESIS_NAMESPACE } from \"./constants/ssml.ts\";\n\ninterface XmlElementNode {\n name: string;\n attributes: SsmlAttributes;\n children: XmlNode[];\n}\n\ntype XmlNode = string | XmlElementNode;\n\nconst XML_ENTITIES: Record<string, string> = {\n amp: \"&\",\n apos: \"'\",\n gt: \">\",\n lt: \"<\",\n quot: '\"',\n};\n\nfunction hasOwn(object: object, property: PropertyKey): boolean {\n return Object.getOwnPropertyDescriptor(object, property) !== undefined;\n}\n\nfunction setAttribute(attributes: SsmlAttributes, name: string, value: string): void {\n Object.defineProperty(attributes, name, {\n configurable: true,\n enumerable: true,\n value,\n writable: true,\n });\n}\n\nfunction decodeEntity(entity: string): string {\n const namedValue = hasOwn(XML_ENTITIES, entity) ? XML_ENTITIES[entity] : undefined;\n if (namedValue !== undefined) {\n return namedValue;\n }\n\n const isHexadecimal = entity.startsWith(\"#x\") || entity.startsWith(\"#X\");\n const isDecimal = entity.startsWith(\"#\");\n if (!isHexadecimal && !isDecimal) {\n throw new Error(`Unknown XML entity: &${entity};`);\n }\n\n const digits = entity.slice(isHexadecimal ? 2 : 1);\n const codePoint = Number.parseInt(digits, isHexadecimal ? 16 : 10);\n if (\n !digits ||\n !Number.isInteger(codePoint) ||\n codePoint < 0 ||\n codePoint > 0x10ffff ||\n (codePoint >= 0xd800 && codePoint <= 0xdfff) ||\n (codePoint < 0x20 && ![9, 10, 13].includes(codePoint))\n ) {\n throw new Error(`Invalid XML character reference: &${entity};`);\n }\n\n return String.fromCodePoint(codePoint);\n}\n\nfunction decodeXmlEntities(value: string): string {\n let result = \"\";\n let start = 0;\n\n while (true) {\n const ampersand = value.indexOf(\"&\", start);\n if (ampersand === -1) {\n return result + value.slice(start);\n }\n\n result += value.slice(start, ampersand);\n const semicolon = value.indexOf(\";\", ampersand + 1);\n if (semicolon === -1) {\n throw new Error(\"Unterminated XML entity reference\");\n }\n\n result += decodeEntity(value.slice(ampersand + 1, semicolon));\n start = semicolon + 1;\n }\n}\n\nfunction isXmlNameStart(value: string | undefined): boolean {\n return value !== undefined && /[A-Za-z_]/.test(value);\n}\n\nfunction isXmlNameCharacter(value: string | undefined): boolean {\n return value !== undefined && /[A-Za-z0-9_.:-]/.test(value);\n}\n\nfunction isXmlWhitespace(value: string | undefined): boolean {\n return value === \" \" || value === \"\\t\" || value === \"\\r\" || value === \"\\n\";\n}\n\nfunction removeStandardNamespaceAttributes(attributes: SsmlAttributes): void {\n if (attributes[SSML_ATTRS.XMLNS] === SYNTHESIS_NAMESPACE) {\n delete attributes[SSML_ATTRS.XMLNS];\n }\n if (attributes[SSML_ATTRS.MSTTS_XMLNS] === MSTTS_NAMESPACE) {\n delete attributes[SSML_ATTRS.MSTTS_XMLNS];\n }\n}\n\nclass XmlParser {\n #index = 0;\n private readonly source: string;\n\n constructor(source: string) {\n this.source = source;\n }\n\n parse(): XmlElementNode {\n if (this.source.charCodeAt(0) === 0xfeff) {\n this.#index += 1;\n }\n\n this.skipMisc();\n if (this.#index >= this.source.length) {\n this.fail(\"SSML input is empty\");\n }\n if (this.source[this.#index] !== \"<\") {\n this.fail(\"SSML input must start with an XML element\");\n }\n\n const root = this.parseElement(0);\n this.skipMisc();\n if (this.#index !== this.source.length) {\n this.fail(\"Unexpected content after the root XML element\");\n }\n return root;\n }\n\n private parseElement(depth: number): XmlElementNode {\n if (depth > MAX_NESTING_DEPTH) {\n this.fail(\"XML nesting depth exceeds the supported limit\");\n }\n\n this.expect(\"<\");\n if (this.source[this.#index] === \"/\") {\n this.fail(\"Unexpected closing XML element\");\n }\n\n const name = this.parseName();\n const { attributes, selfClosing } = this.parseStartTag();\n if (selfClosing) {\n return { name, attributes, children: [] };\n }\n\n const children: XmlNode[] = [];\n while (this.#index < this.source.length) {\n if (this.source.startsWith(\"</\", this.#index)) {\n this.#index += 2;\n const closingName = this.parseName();\n this.skipWhitespace();\n this.expect(\">\");\n if (closingName !== name) {\n this.fail(`Mismatched closing element: expected </${name}> but found </${closingName}>`);\n }\n return { name, attributes, children };\n }\n\n if (this.source.startsWith(\"<!--\", this.#index)) {\n this.skipComment();\n continue;\n }\n\n if (this.source.startsWith(\"<![CDATA[\", this.#index)) {\n this.appendText(children, this.parseCdata());\n continue;\n }\n\n if (this.source.startsWith(\"<?\", this.#index)) {\n this.skipProcessingInstruction();\n continue;\n }\n\n if (this.source.startsWith(\"<!\", this.#index)) {\n this.fail(\"Unsupported XML declaration inside an element\");\n }\n\n if (this.source[this.#index] === \"<\") {\n children.push(this.parseElement(depth + 1));\n } else {\n this.appendText(children, this.parseText());\n }\n }\n\n this.fail(`Unclosed XML element: <${name}>`);\n }\n\n private parseStartTag(): {\n attributes: SsmlAttributes;\n selfClosing: boolean;\n } {\n const attributes: SsmlAttributes = {};\n\n while (this.#index < this.source.length) {\n this.skipWhitespace();\n\n if (this.source.startsWith(\"/>\", this.#index)) {\n this.#index += 2;\n return { attributes, selfClosing: true };\n }\n if (this.source[this.#index] === \">\") {\n this.#index += 1;\n return { attributes, selfClosing: false };\n }\n\n const name = this.parseName();\n this.skipWhitespace();\n this.expect(\"=\");\n this.skipWhitespace();\n\n const quote = this.source[this.#index];\n if (quote !== '\"' && quote !== \"'\") {\n this.fail(`XML attribute ${name} must use a quoted value`);\n }\n this.#index += 1;\n\n const valueStart = this.#index;\n while (this.#index < this.source.length && this.source[this.#index] !== quote) {\n if (this.source[this.#index] === \"<\") {\n this.fail(`Invalid \"<\" in XML attribute ${name}`);\n }\n this.#index += 1;\n }\n if (this.#index >= this.source.length) {\n this.fail(`Unclosed XML attribute ${name}`);\n }\n\n const value = decodeXmlEntities(this.source.slice(valueStart, this.#index));\n this.#index += 1;\n\n if (hasOwn(attributes, name)) {\n this.fail(`Duplicate XML attribute: ${name}`);\n }\n setAttribute(attributes, name, value);\n }\n\n this.fail(\"Unclosed XML start tag\");\n }\n\n private parseText(): string {\n const start = this.#index;\n while (this.#index < this.source.length && this.source[this.#index] !== \"<\") {\n this.#index += 1;\n }\n\n const value = this.source.slice(start, this.#index);\n if (value.includes(\"]]>\")) {\n this.fail(\"CDATA termination is not valid in ordinary XML text\");\n }\n return decodeXmlEntities(value);\n }\n\n private parseCdata(): string {\n this.#index += \"<![CDATA[\".length;\n const end = this.source.indexOf(\"]]>\", this.#index);\n if (end === -1) {\n this.fail(\"Unclosed XML CDATA section\");\n }\n\n const value = this.source.slice(this.#index, end);\n this.#index = end + 3;\n return value;\n }\n\n private skipComment(): void {\n this.#index += \"<!--\".length;\n const end = this.source.indexOf(\"-->\", this.#index);\n if (end === -1) {\n this.fail(\"Unclosed XML comment\");\n }\n if (this.source.slice(this.#index, end).includes(\"--\")) {\n this.fail(\"XML comments cannot contain consecutive hyphens\");\n }\n this.#index = end + 3;\n }\n\n private skipProcessingInstruction(): void {\n this.#index += \"<?\".length;\n this.parseName();\n const end = this.source.indexOf(\"?>\", this.#index);\n if (end === -1) {\n this.fail(\"Unclosed XML processing instruction\");\n }\n this.#index = end + 2;\n }\n\n private skipMisc(): void {\n while (this.#index < this.source.length) {\n this.skipWhitespace();\n if (this.source.startsWith(\"<!--\", this.#index)) {\n this.skipComment();\n continue;\n }\n if (this.source.startsWith(\"<?\", this.#index)) {\n this.skipProcessingInstruction();\n continue;\n }\n if (this.source.startsWith(\"<!DOCTYPE\", this.#index)) {\n this.fail(\"DOCTYPE declarations are not supported\");\n }\n break;\n }\n }\n\n private parseName(): string {\n const first = this.source[this.#index];\n if (!isXmlNameStart(first)) {\n this.fail(\"Invalid XML name\");\n }\n\n const start = this.#index;\n this.#index += 1;\n while (isXmlNameCharacter(this.source[this.#index])) {\n this.#index += 1;\n }\n return this.source.slice(start, this.#index);\n }\n\n private appendText(children: XmlNode[], value: string): void {\n if (!value) {\n return;\n }\n\n const previous = children[children.length - 1];\n if (typeof previous === \"string\") {\n children[children.length - 1] = previous + value;\n } else {\n children.push(value);\n }\n }\n\n private skipWhitespace(): void {\n while (isXmlWhitespace(this.source[this.#index])) {\n this.#index += 1;\n }\n }\n\n private expect(value: string): void {\n if (!this.source.startsWith(value, this.#index)) {\n this.fail(`Expected \"${value}\"`);\n }\n this.#index += value.length;\n }\n\n private fail(message: string): never {\n throw new Error(`${message} at position ${this.#index}`);\n }\n}\n\nfunction readAttribute(attributes: SsmlAttributes, ...names: string[]): string | undefined {\n let found = false;\n let value: string | undefined;\n\n for (const name of names) {\n if (hasOwn(attributes, name)) {\n if (!found) {\n value = String(attributes[name]);\n found = true;\n }\n delete attributes[name];\n }\n }\n\n return value;\n}\n\nfunction getElementAttributes(node: XmlElementNode): SsmlAttributes {\n const attributes: SsmlAttributes = { ...node.attributes };\n removeStandardNamespaceAttributes(attributes);\n return attributes;\n}\n\nfunction finishElement<T extends SsmlElement>(element: T, node: XmlElementNode, attributes: SsmlAttributes): T {\n if (node.children.length > 0) {\n element.children = node.children.map(convertNode);\n }\n if (Object.keys(attributes).length > 0) {\n element.attributes = attributes;\n }\n return element;\n}\n\nfunction convertElement(node: XmlElementNode): SsmlElement {\n const attributes = getElementAttributes(node);\n\n switch (node.name) {\n case SSML_TAGS.VOICE: {\n const element: VoiceElement = { type: SSML_TAGS.VOICE };\n const name = readAttribute(attributes, SSML_ATTRS.NAME);\n const effect = readAttribute(attributes, SSML_ATTRS.EFFECT);\n if (name !== undefined) element.name = name;\n if (effect !== undefined) element.effect = effect;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.PROSODY: {\n const element: ProsodyElement = { type: SSML_TAGS.PROSODY };\n const rate = readAttribute(attributes, SSML_ATTRS.RATE);\n const pitch = readAttribute(attributes, SSML_ATTRS.PITCH);\n const volume = readAttribute(attributes, SSML_ATTRS.VOLUME);\n const contour = readAttribute(attributes, SSML_ATTRS.CONTOUR);\n const range = readAttribute(attributes, SSML_ATTRS.RANGE);\n if (rate !== undefined) element.rate = rate;\n if (pitch !== undefined) element.pitch = pitch;\n if (volume !== undefined) element.volume = volume;\n if (contour !== undefined) element.contour = contour;\n if (range !== undefined) element.range = range;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.BREAK: {\n const element: BreakElement = { type: SSML_TAGS.BREAK };\n const time = readAttribute(attributes, SSML_ATTRS.TIME);\n const strength = readAttribute(attributes, SSML_ATTRS.STRENGTH);\n if (time !== undefined) element.time = time;\n if (strength !== undefined) element.strength = strength;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.EXPRESS_AS:\n case SSML_TAGS.EXPRESS_AS_CAMEL:\n case SSML_TAGS.MSTTS_EXPRESS_AS: {\n const element: ExpressAsElement = { type: node.name };\n const style = readAttribute(attributes, SSML_ATTRS.STYLE);\n const styleDegree = readAttribute(\n attributes,\n SSML_ATTRS.STYLE_DEGREE,\n SSML_ATTRS.STYLE_DEGREE_CAMEL,\n SSML_ATTRS.STYLE_DEGREE_HYPHEN,\n );\n const role = readAttribute(attributes, SSML_ATTRS.ROLE);\n if (style !== undefined) element.style = style;\n if (styleDegree !== undefined) element.styleDegree = styleDegree;\n if (role !== undefined) element.role = role;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.SAY_AS:\n case SSML_TAGS.SAY_AS_CAMEL: {\n const element: SayAsElement = { type: node.name };\n const interpretAs = readAttribute(attributes, SSML_ATTRS.INTERPRET_AS);\n const format = readAttribute(attributes, SSML_ATTRS.FORMAT);\n const detail = readAttribute(attributes, SSML_ATTRS.DETAIL);\n if (interpretAs !== undefined) element.interpretAs = interpretAs;\n if (format !== undefined) element.format = format;\n if (detail !== undefined) element.detail = detail;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.PHONEME: {\n const element: PhonemeElement = { type: SSML_TAGS.PHONEME };\n const alphabet = readAttribute(attributes, SSML_ATTRS.ALPHABET);\n const ph = readAttribute(attributes, SSML_ATTRS.PH);\n if (alphabet !== undefined) element.alphabet = alphabet;\n if (ph !== undefined) element.ph = ph;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.EMPHASIS: {\n const element: EmphasisElement = { type: SSML_TAGS.EMPHASIS };\n const level = readAttribute(attributes, SSML_ATTRS.LEVEL);\n if (level !== undefined) element.level = level;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.AUDIO: {\n const element: AudioElement = { type: SSML_TAGS.AUDIO };\n const src = readAttribute(attributes, SSML_ATTRS.SRC);\n const desc = readAttribute(attributes, SSML_ATTRS.DESC);\n const clipBegin = readAttribute(attributes, SSML_ATTRS.CLIP_BEGIN);\n const clipEnd = readAttribute(attributes, SSML_ATTRS.CLIP_END);\n const speed = readAttribute(attributes, SSML_ATTRS.SPEED);\n const repeatCount = readAttribute(attributes, SSML_ATTRS.REPEAT_COUNT);\n const repeatDuration = readAttribute(attributes, SSML_ATTRS.REPEAT_DURATION);\n const soundLevel = readAttribute(attributes, SSML_ATTRS.SOUND_LEVEL);\n if (src !== undefined) element.src = src;\n if (desc !== undefined) element.desc = desc;\n if (clipBegin !== undefined) element.clipBegin = clipBegin;\n if (clipEnd !== undefined) element.clipEnd = clipEnd;\n if (speed !== undefined) element.speed = speed;\n if (repeatCount !== undefined) element.repeatCount = repeatCount;\n if (repeatDuration !== undefined) element.repeatDuration = repeatDuration;\n if (soundLevel !== undefined) element.soundLevel = soundLevel;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.SUB: {\n const element: SubElement = { type: SSML_TAGS.SUB };\n const alias = readAttribute(attributes, SSML_ATTRS.ALIAS);\n if (alias !== undefined) element.alias = alias;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.LANG: {\n const element: LangElement = { type: SSML_TAGS.LANG };\n const lang = readAttribute(attributes, SSML_ATTRS.XML_LANG, SSML_ATTRS.LANG);\n if (lang !== undefined) element.lang = lang;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.MARK: {\n const element: MarkElement = { type: SSML_TAGS.MARK };\n const name = readAttribute(attributes, SSML_ATTRS.NAME);\n if (name !== undefined) element.name = name;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.BOOKMARK: {\n const element: BookmarkElement = { type: SSML_TAGS.BOOKMARK };\n const mark = readAttribute(attributes, SSML_ATTRS.MARK);\n if (mark !== undefined) element.mark = mark;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.LEXICON: {\n const element: LexiconElement = { type: SSML_TAGS.LEXICON };\n const uri = readAttribute(attributes, SSML_ATTRS.URI);\n if (uri !== undefined) element.uri = uri;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.PARAGRAPH: {\n const element: ParagraphElement = { type: SSML_TAGS.PARAGRAPH };\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.SENTENCE: {\n const element: SentenceElement = { type: SSML_TAGS.SENTENCE };\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.WORD: {\n const element: WordElement = { type: SSML_TAGS.WORD };\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.MSTTS_SILENCE:\n case SSML_TAGS.SILENCE: {\n const element: MsttsSilenceElement = {\n type: node.name === SSML_TAGS.MSTTS_SILENCE ? SSML_TAGS.MSTTS_SILENCE : SSML_TAGS.SILENCE,\n };\n const typeValue = readAttribute(attributes, SSML_ATTRS.TYPE);\n const value = readAttribute(attributes, SSML_ATTRS.VALUE);\n if (typeValue !== undefined) element.typeValue = typeValue;\n if (value !== undefined) element.value = value;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.MSTTS_VISEME:\n case SSML_TAGS.VISEME: {\n const element: MsttsVisemeElement = {\n type: node.name === SSML_TAGS.MSTTS_VISEME ? SSML_TAGS.MSTTS_VISEME : SSML_TAGS.VISEME,\n };\n const typeValue = readAttribute(attributes, SSML_ATTRS.TYPE);\n if (typeValue !== undefined) element.typeValue = typeValue;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.MSTTS_AUDIO_DURATION: {\n const element: MsttsAudioDurationElement = { type: SSML_TAGS.MSTTS_AUDIO_DURATION };\n const value = readAttribute(attributes, SSML_ATTRS.VALUE);\n if (value !== undefined) element.value = value;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.MSTTS_DIALOG: {\n const element: SsmlDialogNode = { type: SSML_TAGS.MSTTS_DIALOG };\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.MSTTS_TURN: {\n const element: SsmlTurnNode = { type: SSML_TAGS.MSTTS_TURN };\n const voice = readAttribute(attributes, SSML_ATTRS.VOICE);\n const speaker = readAttribute(attributes, SSML_ATTRS.SPEAKER);\n if (voice !== undefined) element.voice = voice;\n if (speaker !== undefined) element.speaker = speaker;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.MSTTS_BACKGROUND_AUDIO: {\n const element: SsmlBackgroundAudioNode = { type: SSML_TAGS.MSTTS_BACKGROUND_AUDIO };\n const src = readAttribute(attributes, SSML_ATTRS.SRC);\n const volume = readAttribute(attributes, SSML_ATTRS.VOLUME);\n const fadeIn = readAttribute(attributes, SSML_ATTRS.FADE_IN);\n const fadeOut = readAttribute(attributes, SSML_ATTRS.FADE_OUT);\n if (src !== undefined) element.src = src;\n if (volume !== undefined) element.volume = volume;\n if (fadeIn !== undefined) element.fadeIn = fadeIn;\n if (fadeOut !== undefined) element.fadeOut = fadeOut;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.MSTTS_TTS_EMBEDDING: {\n const element: MsttsTtsEmbeddingElement = { type: SSML_TAGS.MSTTS_TTS_EMBEDDING };\n const speakerProfileId = readAttribute(attributes, SSML_ATTRS.SPEAKER_PROFILE_ID);\n if (speakerProfileId !== undefined) element.speakerProfileId = speakerProfileId;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.MSTTS_EMBEDDING: {\n const element: MsttsEmbeddingElement = { type: SSML_TAGS.MSTTS_EMBEDDING };\n const id = readAttribute(attributes, SSML_ATTRS.ID);\n const speakerProfileId = readAttribute(attributes, SSML_ATTRS.SPEAKER_PROFILE_ID);\n if (id !== undefined) element.id = id;\n if (speakerProfileId !== undefined) element.speakerProfileId = speakerProfileId;\n return finishElement(element, node, attributes);\n }\n case SSML_TAGS.MSTTS_VOICE_CONVERSION: {\n const element: MsttsVoiceConversionElement = { type: SSML_TAGS.MSTTS_VOICE_CONVERSION };\n const url = readAttribute(attributes, SSML_ATTRS.URL);\n const profile = readAttribute(attributes, SSML_ATTRS.PROFILE);\n const speakerProfileId = readAttribute(attributes, SSML_ATTRS.SPEAKER_PROFILE_ID);\n if (url !== undefined) element.url = url;\n if (profile !== undefined) element.profile = profile;\n if (speakerProfileId !== undefined) element.speakerProfileId = speakerProfileId;\n return finishElement(element, node, attributes);\n }\n default: {\n const element: CustomElement = {\n name: node.name,\n type: \"custom\",\n };\n return finishElement(element, node, attributes);\n }\n }\n}\n\nfunction convertNode(node: XmlNode): SsmlNode {\n return typeof node === \"string\" ? node : convertElement(node);\n}\n\nexport function parseSsml(xmlString: string): SsmlDocument {\n if (typeof xmlString !== \"string\") {\n throw new TypeError(\"SSML input must be a string\");\n }\n\n const root = new XmlParser(xmlString).parse();\n if (root.name !== SSML_TAGS.SPEAK) {\n throw new Error(`SSML root element must be <${SSML_TAGS.SPEAK}>, found <${root.name}>`);\n }\n\n const attributes: SsmlAttributes = { ...root.attributes };\n const version = readAttribute(attributes, SSML_ATTRS.VERSION);\n const lang = readAttribute(attributes, SSML_ATTRS.XML_LANG, SSML_ATTRS.LANG);\n if (version === undefined) {\n throw new Error(`SSML <${SSML_TAGS.SPEAK}> element is missing the \"${SSML_ATTRS.VERSION}\" attribute`);\n }\n if (lang === undefined) {\n throw new Error(`SSML <${SSML_TAGS.SPEAK}> element is missing the \"${SSML_ATTRS.XML_LANG}\" attribute`);\n }\n\n removeStandardNamespaceAttributes(attributes);\n const document: SsmlDocument = {\n children: root.children.map(convertNode),\n lang,\n type: SSML_TAGS.SPEAK,\n version,\n };\n if (Object.keys(attributes).length > 0) {\n document.attributes = attributes;\n }\n return document;\n}\n","import { buildSsml } from \"./builder.ts\";\nimport {\n DEFAULT_SSML_LANGUAGE,\n DEFAULT_SSML_VERSION,\n SSML_ATTRS,\n SSML_TAGS,\n SYNTHESIS_NAMESPACE,\n} from \"./constants/ssml.ts\";\nimport { parseSsml } from \"./parser.ts\";\nimport type { ProsodyElement, SsmlAttributes, SsmlDocument, SsmlNode, VoiceElement } from \"./types.ts\";\n\nexport type SsmlPartialVoice = Pick<VoiceElement, \"name\" | \"effect\" | \"attributes\">;\n\nexport type SsmlPartialProsody = Pick<ProsodyElement, \"rate\" | \"pitch\" | \"volume\" | \"contour\" | \"range\" | \"attributes\">;\n\nexport interface SsmlPartialContext {\n /** SSML version used for the generated document. */\n version?: string;\n /** BCP-47 language tag used for the generated document. */\n lang?: string;\n /** Preferred voice name; a voice object takes precedence, while this overrides a string `voice` shorthand. */\n voiceName?: string;\n /** Optional Azure voice effect used with `voiceName` or a string `voice` shorthand. */\n voiceEffect?: string;\n /** A voice name shorthand or a voice object whose attributes are preserved. */\n voice?: string | SsmlPartialVoice;\n /** Optional prosody values applied around the partial text. */\n prosody?: SsmlPartialProsody;\n /** Additional attributes added to the generated `speak` element. */\n attributes?: SsmlAttributes;\n}\n\nexport interface BuildPartialSsmlOptions extends SsmlPartialContext {\n text: string;\n}\n\nfunction escapeAttribute(value: string): string {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/'/g, \"&apos;\");\n}\n\nfunction getPartialTextNodes(text: string, version: string, lang: string): SsmlNode[] {\n if (!text.includes(\"<\")) {\n return [text];\n }\n\n try {\n const openingTag = `<${SSML_TAGS.SPEAK} ${SSML_ATTRS.VERSION}=\"${escapeAttribute(version)}\" ${SSML_ATTRS.XMLNS}=\"${SYNTHESIS_NAMESPACE}\" ${SSML_ATTRS.XML_LANG}=\"${escapeAttribute(lang)}\">`;\n return parseSsml(`${openingTag}${text}</${SSML_TAGS.SPEAK}>`).children ?? [];\n } catch {\n return [{ type: \"text\", value: text }];\n }\n}\n\nfunction getVoiceContext(context: SsmlPartialContext): SsmlPartialVoice | undefined {\n const voice = context.voice;\n if (typeof voice === \"object\" && voice !== null) {\n return voice;\n }\n\n if (context.voiceName === undefined && context.voiceEffect === undefined && typeof voice !== \"string\") {\n return undefined;\n }\n\n return {\n name: context.voiceName ?? voice,\n effect: context.voiceEffect,\n };\n}\n\nfunction serializePartialSsml(text: string, context: SsmlPartialContext): string {\n const version = context.version ?? DEFAULT_SSML_VERSION;\n const lang = context.lang ?? DEFAULT_SSML_LANGUAGE;\n let children = getPartialTextNodes(text, version, lang);\n\n if (context.prosody) {\n children = [\n {\n type: SSML_TAGS.PROSODY,\n ...context.prosody,\n children,\n },\n ];\n }\n\n const voice = getVoiceContext(context);\n if (voice) {\n children = [\n {\n type: SSML_TAGS.VOICE,\n ...voice,\n children,\n },\n ];\n }\n\n const document: SsmlDocument = {\n type: SSML_TAGS.SPEAK,\n version,\n lang,\n attributes: context.attributes,\n children,\n };\n return buildSsml(document);\n}\n\nexport function buildPartialSsml(text: string, context?: SsmlPartialContext): string;\nexport function buildPartialSsml(options: BuildPartialSsmlOptions): string;\nexport function buildPartialSsml(\n textOrOptions: string | BuildPartialSsmlOptions,\n context?: SsmlPartialContext,\n): string {\n if (typeof textOrOptions === \"string\") {\n return serializePartialSsml(textOrOptions, context ?? {});\n }\n\n return serializePartialSsml(textOrOptions.text, textOrOptions);\n}\n","import { parseSsml } from \"./parser.ts\";\n\nexport interface SsmlTextNodeContext {\n parentTag: string;\n parentAttributes: Record<string, string>;\n ancestorTags: string[];\n path: string[];\n}\n\nexport interface SsmlSourceTextSegment {\n text: string;\n range: { start: number; end: number };\n sourceNodePath: string[];\n}\n\nexport interface SsmlSourceMarker {\n kind: \"mark\" | \"bookmark\";\n name: string;\n originalTextRange: { start: number; end: number };\n sourceNodePath: string[];\n}\n\nexport interface SsmlSourceMap {\n text: string;\n segments: SsmlSourceTextSegment[];\n markers: SsmlSourceMarker[];\n}\n\nexport interface MapSsmlTextNodesOptions {\n /** Element names whose text should not be passed to the transform. */\n skipTags?: readonly string[];\n /** Decides whether an individual text node should be passed to the transform. */\n filter?: (context: SsmlTextNodeContext) => boolean;\n}\n\ninterface TextNodeRecord {\n context: SsmlTextNodeContext;\n decodedText: string;\n end: number;\n sourceEnd: number;\n sourceStart: number;\n start: number;\n}\n\ninterface OpenElement {\n attributes: Record<string, string>;\n name: string;\n}\n\nfunction decodeXmlText(value: string): string {\n return value.replace(/&(?:amp|apos|gt|lt|quot);|&#(?:x[\\da-f]+|\\d+);/gi, (entity) => {\n if (entity === \"&amp;\") return \"&\";\n if (entity === \"&apos;\") return \"'\";\n if (entity === \"&gt;\") return \">\";\n if (entity === \"&lt;\") return \"<\";\n if (entity === \"&quot;\") return '\"';\n const hexadecimal = entity.toLowerCase().startsWith(\"&#x\");\n const digits = entity.slice(hexadecimal ? 3 : 2, -1);\n return String.fromCodePoint(Number.parseInt(digits, hexadecimal ? 16 : 10));\n });\n}\n\nfunction encodeXmlText(value: string): string {\n return value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction decodeXmlAttribute(value: string): string {\n return decodeXmlText(value);\n}\n\nfunction findTagEnd(source: string, start: number): number {\n let quote = \"\";\n for (let index = start; index < source.length; index += 1) {\n const character = source[index];\n if (quote) {\n if (character === quote) quote = \"\";\n } else if (character === '\"' || character === \"'\") {\n quote = character;\n } else if (character === \">\") {\n return index;\n }\n }\n return source.length - 1;\n}\n\nfunction readTagName(tag: string): string | undefined {\n const match = /^<\\s*([A-Za-z_][A-Za-z0-9_.:-]*)/.exec(tag);\n return match?.[1];\n}\n\nfunction readTagAttributes(tag: string, name: string): Record<string, string> {\n const attributes: Record<string, string> = {};\n const nameStart = tag.indexOf(name);\n const attributeSource = tag.slice(nameStart + name.length, tag.length - 1).replace(/\\/\\s*$/, \"\");\n const attributePattern = /([A-Za-z_][A-Za-z0-9_.:-]*)\\s*=\\s*([\"'])([\\s\\S]*?)\\2/g;\n for (const match of attributeSource.matchAll(attributePattern)) {\n attributes[match[1].toLowerCase()] = decodeXmlAttribute(match[3]);\n }\n return attributes;\n}\n\nfunction collectTextNodes(source: string): TextNodeRecord[] {\n const nodes: TextNodeRecord[] = [];\n const elements: OpenElement[] = [];\n let index = 0;\n\n const addText = (start: number, end: number, rawText: string, sourceStart = start, sourceEnd = end): void => {\n if (!rawText) return;\n const path = elements.map((element) => element.name);\n const parent = elements[elements.length - 1];\n nodes.push({\n context: {\n ancestorTags: path.slice(0, -1),\n parentAttributes: { ...(parent?.attributes ?? {}) },\n parentTag: parent?.name ?? \"\",\n path,\n },\n decodedText: decodeXmlText(rawText),\n end,\n sourceEnd,\n sourceStart,\n start,\n });\n };\n\n while (index < source.length) {\n if (source[index] !== \"<\") {\n const nextTag = source.indexOf(\"<\", index);\n const end = nextTag === -1 ? source.length : nextTag;\n addText(index, end, source.slice(index, end));\n index = end;\n continue;\n }\n\n if (source.startsWith(\"<!--\", index)) {\n const end = source.indexOf(\"-->\", index + 4);\n index = end === -1 ? source.length : end + 3;\n continue;\n }\n if (source.startsWith(\"<![CDATA[\", index)) {\n const contentStart = index + 9;\n const end = source.indexOf(\"]]>\", contentStart);\n const contentEnd = end === -1 ? source.length : end;\n addText(\n contentStart,\n contentEnd,\n source.slice(contentStart, contentEnd),\n index,\n end === -1 ? source.length : end + 3,\n );\n index = end === -1 ? source.length : end + 3;\n continue;\n }\n if (source.startsWith(\"<?\", index)) {\n const end = source.indexOf(\"?>\", index + 2);\n index = end === -1 ? source.length : end + 2;\n continue;\n }\n if (source.startsWith(\"</\", index)) {\n const end = findTagEnd(source, index + 2);\n elements.pop();\n index = end + 1;\n continue;\n }\n\n const end = findTagEnd(source, index + 1);\n const tag = source.slice(index, end + 1);\n const name = readTagName(tag);\n if (name && !/\\/\\s*>$/.test(tag)) elements.push({ attributes: readTagAttributes(tag, name), name });\n index = end + 1;\n }\n\n return nodes;\n}\n\ninterface SourceMapElement {\n name: string;\n path: string[];\n nextChildIndex: number;\n}\n\nfunction collectSourceMap(source: string): SsmlSourceMap {\n const segments: SsmlSourceTextSegment[] = [];\n const markers: SsmlSourceMarker[] = [];\n const elements: SourceMapElement[] = [];\n let textOffset = 0;\n let index = 0;\n const textParts: string[] = [];\n\n const addText = (value: string): void => {\n if (!value) return;\n const parent = elements[elements.length - 1];\n if (parent) parent.nextChildIndex += 1;\n const sourceNodePath = parent?.path ?? [\"speak\"];\n const start = textOffset;\n textOffset += value.length;\n textParts.push(value);\n segments.push({ text: value, range: { start, end: textOffset }, sourceNodePath: [...sourceNodePath] });\n };\n\n while (index < source.length) {\n if (source[index] !== \"<\") {\n const end = source.indexOf(\"<\", index);\n const textEnd = end === -1 ? source.length : end;\n addText(decodeXmlText(source.slice(index, textEnd)));\n index = textEnd;\n continue;\n }\n if (source.startsWith(\"<!--\", index)) {\n const end = source.indexOf(\"-->\", index + 4);\n index = end === -1 ? source.length : end + 3;\n continue;\n }\n if (source.startsWith(\"<![CDATA[\", index)) {\n const contentStart = index + 9;\n const end = source.indexOf(\"]]>\", contentStart);\n const contentEnd = end === -1 ? source.length : end;\n addText(source.slice(contentStart, contentEnd));\n index = end === -1 ? source.length : end + 3;\n continue;\n }\n if (source.startsWith(\"<?\", index)) {\n const end = source.indexOf(\"?>\", index + 2);\n index = end === -1 ? source.length : end + 2;\n continue;\n }\n\n const end = findTagEnd(source, index + 1);\n const rawTag = source.slice(index, end + 1);\n if (rawTag.startsWith(\"</\")) {\n elements.pop();\n index = end + 1;\n continue;\n }\n const name = readTagName(rawTag);\n if (!name) {\n index = end + 1;\n continue;\n }\n const parent = elements[elements.length - 1];\n const childIndex = parent?.nextChildIndex ?? 0;\n if (parent) parent.nextChildIndex += 1;\n const path = parent ? [...parent.path, `${name}[${childIndex}]`] : [name];\n const attributes = readTagAttributes(rawTag, name);\n const normalizedName = name.toLowerCase();\n if (normalizedName === \"mark\" || normalizedName === \"bookmark\") {\n const markerName = attributes[normalizedName === \"mark\" ? \"name\" : \"mark\"];\n if (markerName) {\n markers.push({\n kind: normalizedName,\n name: markerName,\n originalTextRange: { start: textOffset, end: textOffset },\n sourceNodePath: [...path],\n });\n }\n }\n if (!/\\/\\s*>$/.test(rawTag)) elements.push({ name, path, nextChildIndex: 0 });\n index = end + 1;\n }\n return { text: textParts.join(\"\"), segments, markers };\n}\n\n/** Returns decoded source text segments and marker locations with indexed SSML paths. */\nexport function getSsmlSourceMap(ssml: string): SsmlSourceMap {\n parseSsml(ssml);\n return collectSourceMap(ssml);\n}\n\nexport function extractSsmlText(ssml: string): string[] {\n parseSsml(ssml);\n return collectTextNodes(ssml).map((node) => node.decodedText);\n}\n\nexport async function mapSsmlTextNodes(\n ssml: string,\n transform: (text: string, context: SsmlTextNodeContext) => string | Promise<string>,\n options: MapSsmlTextNodesOptions = {},\n): Promise<string> {\n parseSsml(ssml);\n const nodes = collectTextNodes(ssml);\n const skipTags = new Set((options.skipTags ?? [\"phoneme\", \"say-as\", \"sub\"]).map((tag) => tag.toLowerCase()));\n const replacements = await Promise.all(\n nodes.map(async (node) => {\n const context = {\n ancestorTags: [...node.context.ancestorTags],\n parentAttributes: { ...node.context.parentAttributes },\n parentTag: node.context.parentTag,\n path: [...node.context.path],\n };\n const shouldTransform = !skipTags.has(context.parentTag.toLowerCase()) && (options.filter?.(context) ?? true);\n if (!shouldTransform) return ssml.slice(node.sourceStart, node.sourceEnd);\n const transformed = await transform(node.decodedText, context);\n if (typeof transformed !== \"string\") {\n throw new TypeError(\"SSML text node transform must return a string\");\n }\n return transformed === node.decodedText\n ? ssml.slice(node.sourceStart, node.sourceEnd)\n : encodeXmlText(transformed);\n }),\n );\n\n let result = \"\";\n let cursor = 0;\n nodes.forEach((node, nodeIndex) => {\n result += ssml.slice(cursor, node.sourceStart) + replacements[nodeIndex];\n cursor = node.sourceEnd;\n });\n return result + ssml.slice(cursor);\n}\n","import { buildSsml } from \"./builder.ts\";\nimport { getSsmlSourceMap } from \"./textNodes.ts\";\nimport { parseSsml } from \"./parser.ts\";\nimport type { SsmlDocument, SsmlElement, SsmlNode } from \"./types.ts\";\nimport type { SsmlSourceMap, SsmlSourceMarker, SsmlSourceTextSegment } from \"./textNodes.ts\";\n\nconst DEFAULT_MAX_LENGTH = 10_000;\n\nexport interface SsmlTextRange {\n start: number;\n end: number;\n}\n\nexport interface SsmlChunkContext {\n voice?: string;\n lang?: string;\n prosody?: Record<string, string>;\n}\n\nexport interface SsmlChunk {\n chunkIndex: number;\n ssml: string;\n originalTextRange: SsmlTextRange;\n inheritedContext: SsmlChunkContext;\n containedMarks: string[];\n hasBackgroundAudio: boolean;\n /** Best-effort path to the first source element represented by this chunk. */\n sourceNodePath?: string[];\n /** Exact source segments represented by this chunk, used for event mapping. */\n sourceTextSegments?: SsmlSourceTextSegment[];\n /** Exact marker locations represented by this chunk, used for bookmark mapping. */\n sourceMarkers?: SsmlSourceMarker[];\n}\n\nexport interface SplitSsmlOptions {\n maxLength?: number;\n /** Keeps `<mstts:backgroundaudio>` in every chunk instead of the first chunk only. */\n replicateBackgroundAudio?: boolean;\n}\n\nfunction cloneElement(element: SsmlElement, children: SsmlNode[]): SsmlElement {\n return { ...element, children };\n}\n\nfunction documentWithChildren(document: SsmlDocument, children: SsmlNode[]): string {\n return buildSsml({ ...document, children });\n}\n\nfunction wrapWithContext(node: SsmlNode, context: SsmlElement[]): SsmlNode {\n return context.reduceRight<SsmlNode>((current, parent) => cloneElement(parent, [current]), node);\n}\n\nfunction documentWithNode(document: SsmlDocument, node: SsmlNode, context: SsmlElement[]): string {\n return documentWithChildren(document, [wrapWithContext(node, context)]);\n}\n\nfunction splitTextNode(text: string, document: SsmlDocument, context: SsmlElement[], maxLength: number): SsmlNode[] {\n if (!text) return [text];\n const parts: string[] = [];\n let start = 0;\n while (start < text.length) {\n let end = start + 1;\n let bestEnd = end;\n while (end <= text.length) {\n if (documentWithNode(document, text.slice(start, end), context).length > maxLength) break;\n bestEnd = end;\n end += 1;\n }\n if (bestEnd === start) {\n throw new RangeError(\"maxLength is too small to contain the SSML document wrapper\");\n }\n\n // Prefer a word boundary, but fall back to a character for long words.\n const segment = text.slice(start, bestEnd);\n const boundary = Math.max(segment.lastIndexOf(\" \"), segment.lastIndexOf(\"\\n\"), segment.lastIndexOf(\"\\t\"));\n const splitEnd = boundary > 0 ? start + boundary + 1 : bestEnd;\n parts.push(text.slice(start, splitEnd));\n start = splitEnd;\n }\n return parts;\n}\n\nfunction splitNode(document: SsmlDocument, node: SsmlNode, maxLength: number, context: SsmlElement[] = []): SsmlNode[] {\n if (typeof node === \"string\" || node.type === \"text\") {\n const value = typeof node === \"string\" ? node : node.value;\n if (documentWithNode(document, node, context).length <= maxLength) return [node];\n return splitTextNode(value, document, context, maxLength);\n }\n\n if (documentWithNode(document, node, context).length <= maxLength) return [node];\n const children = node.children ?? [];\n if (children.length === 0) {\n throw new RangeError(`maxLength is too small to contain <${node.type}>`);\n }\n\n const splitChildren = children.flatMap((child) => splitNode(document, child, maxLength, [...context, node]));\n const parts: SsmlNode[] = [];\n let group: SsmlNode[] = [];\n const flush = (): void => {\n if (group.length > 0) {\n parts.push(cloneElement(node, group));\n group = [];\n }\n };\n\n for (const child of splitChildren) {\n const candidate = cloneElement(node, [...group, child]);\n if (documentWithNode(document, candidate, context).length <= maxLength) {\n group.push(child);\n continue;\n }\n flush();\n if (documentWithNode(document, cloneElement(node, [child]), context).length > maxLength) {\n throw new RangeError(`maxLength is too small to contain <${node.type}>`);\n }\n group.push(child);\n }\n flush();\n return parts;\n}\n\nfunction textFromNode(node: SsmlNode): string {\n if (typeof node === \"string\") return node;\n if (node.type === \"text\") return node.value;\n return (node.children ?? []).map(textFromNode).join(\"\");\n}\n\nfunction collectMarks(node: SsmlNode, marks: string[]): void {\n if (typeof node === \"string\" || node.type === \"text\") return;\n if (node.type === \"mark\" && node.name) marks.push(node.name);\n if (node.type === \"bookmark\" && node.mark) marks.push(node.mark);\n for (const child of node.children ?? []) collectMarks(child, marks);\n}\n\nfunction collectInheritedContext(nodes: SsmlNode[]): SsmlChunkContext {\n const context: SsmlChunkContext = {};\n const visit = (node: SsmlNode): void => {\n if (typeof node === \"string\" || node.type === \"text\") return;\n if (context.voice === undefined && node.type === \"voice\" && node.name) context.voice = node.name;\n if (context.lang === undefined && node.type === \"lang\" && node.lang) context.lang = node.lang;\n if (context.prosody === undefined && node.type === \"prosody\") {\n const prosody: Record<string, string> = {};\n for (const [key, value] of Object.entries(node.attributes ?? {})) prosody[key] = String(value);\n for (const key of [\"rate\", \"pitch\", \"volume\", \"contour\", \"range\"] as const) {\n const value = node[key];\n if (value !== undefined) prosody[key] = String(value);\n }\n if (Object.keys(prosody).length > 0) context.prosody = prosody;\n }\n for (const child of node.children ?? []) visit(child);\n };\n nodes.forEach(visit);\n return context;\n}\n\nfunction elementName(node: SsmlElement): string {\n return node.type === \"custom\" || node.type === \"element\" ? node.name : node.type;\n}\n\nfunction findSourceNodePath(nodes: SsmlNode[], targetOffset: number): string[] | undefined {\n let textOffset = 0;\n let firstPath: string[] | undefined;\n let foundPath: string[] | undefined;\n const visit = (node: SsmlNode, path: string[]): void => {\n if (typeof node === \"string\" || node.type === \"text\") {\n const text = typeof node === \"string\" ? node : node.value;\n if (text && firstPath === undefined) firstPath = [...path];\n if (text && foundPath === undefined && targetOffset < textOffset + text.length) foundPath = [...path];\n textOffset += text.length;\n return;\n }\n node.children?.forEach((child, index) => {\n const childPath =\n typeof child === \"string\" || child.type === \"text\" ? path : [...path, `${elementName(child)}[${index}]`];\n visit(child, childPath);\n });\n };\n nodes.forEach((node, index) => {\n if (!foundPath) {\n if (typeof node === \"string\" || node.type === \"text\") visit(node, [\"speak\"]);\n else visit(node, [\"speak\", `${elementName(node)}[${index}]`]);\n }\n });\n return foundPath ?? firstPath;\n}\n\nfunction createChunk(\n document: SsmlDocument,\n nodes: SsmlNode[],\n chunkIndex: number,\n textStart: number,\n backgroundAudio: SsmlNode | undefined,\n replicateBackgroundAudio: boolean,\n sourceMap: SsmlSourceMap,\n includeEndMarkers: boolean,\n): SsmlChunk {\n const chunkNodes =\n backgroundAudio && (replicateBackgroundAudio || chunkIndex === 0) ? [backgroundAudio, ...nodes] : nodes;\n const text = nodes.map(textFromNode).join(\"\");\n const marks: string[] = [];\n for (const node of nodes) collectMarks(node, marks);\n const inheritedContext = collectInheritedContext(nodes);\n if (inheritedContext.lang === undefined && document.lang) inheritedContext.lang = document.lang;\n return {\n chunkIndex,\n ssml: documentWithChildren(document, chunkNodes),\n originalTextRange: { start: textStart, end: textStart + text.length },\n inheritedContext,\n containedMarks: marks,\n hasBackgroundAudio: chunkNodes.some(\n (node) => typeof node !== \"string\" && node.type !== \"text\" && node.type === \"mstts:backgroundaudio\",\n ),\n sourceNodePath: findSourceNodePath(document.children ?? [], textStart),\n sourceTextSegments: sourceMap.segments\n .filter(({ range }) => range.end > textStart && range.start < textStart + text.length)\n .map((segment) => {\n const start = Math.max(segment.range.start, textStart);\n const end = Math.min(segment.range.end, textStart + text.length);\n return {\n text: segment.text.slice(start - segment.range.start, end - segment.range.start),\n range: { start, end },\n sourceNodePath: [...segment.sourceNodePath],\n };\n }),\n sourceMarkers: sourceMap.markers\n .filter(\n ({ originalTextRange }) =>\n originalTextRange.start >= textStart &&\n (originalTextRange.start < textStart + text.length ||\n (includeEndMarkers && originalTextRange.start === textStart + text.length)),\n )\n .map((marker) => ({\n ...marker,\n originalTextRange: { ...marker.originalTextRange },\n sourceNodePath: [...marker.sourceNodePath],\n })),\n };\n}\n\n/**\n * Splits SSML into independently synthesizable documents without breaking XML\n * elements. Parent elements such as `<voice>` and `<prosody>` are copied into\n * every block. Paragraph and sentence elements therefore remain the natural\n * split points, while oversized text is split at word/character boundaries.\n */\nexport function splitSsmlDocument(\n ssml: string,\n maxLength: number | SplitSsmlOptions = DEFAULT_MAX_LENGTH,\n options: SplitSsmlOptions = {},\n): SsmlChunk[] {\n const resolvedMaxLength = typeof maxLength === \"number\" ? maxLength : (maxLength.maxLength ?? DEFAULT_MAX_LENGTH);\n const resolvedOptions = typeof maxLength === \"number\" ? options : maxLength;\n if (!Number.isInteger(resolvedMaxLength) || resolvedMaxLength <= 0) {\n throw new RangeError(\"maxLength must be a positive integer\");\n }\n const document = parseSsml(ssml);\n const sourceMap = getSsmlSourceMap(ssml);\n const backgroundAudio = (document.children ?? []).find(\n (node): node is SsmlElement =>\n typeof node !== \"string\" && node.type !== \"text\" && node.type === \"mstts:backgroundaudio\",\n );\n if (ssml.length <= resolvedMaxLength) {\n return [createChunk(document, document.children ?? [], 0, 0, backgroundAudio, true, sourceMap, true)];\n }\n\n const contentChildren = (document.children ?? []).filter((node) => node !== backgroundAudio);\n const plainDocumentLength = documentWithChildren(document, []).length;\n const backgroundDocumentLength = backgroundAudio\n ? documentWithChildren(document, [backgroundAudio]).length\n : plainDocumentLength;\n const backgroundOverhead = Math.max(0, backgroundDocumentLength - plainDocumentLength);\n const contentMaxLength = Math.max(1, resolvedMaxLength - backgroundOverhead);\n const splitChildren = contentChildren.flatMap((child) => splitNode(document, child, contentMaxLength));\n const chunks: SsmlNode[][] = [];\n let group: SsmlNode[] = [];\n for (const child of splitChildren) {\n const candidate = [...group, child];\n if (documentWithChildren(document, candidate).length <= contentMaxLength) {\n group = candidate;\n continue;\n }\n if (group.length > 0) chunks.push(group);\n group = [child];\n if (documentWithChildren(document, group).length > contentMaxLength) {\n throw new RangeError(\"maxLength is too small to contain the SSML document wrapper\");\n }\n }\n if (group.length > 0) chunks.push(group);\n if (chunks.length === 0) {\n const result = createChunk(\n document,\n [],\n 0,\n 0,\n backgroundAudio,\n resolvedOptions.replicateBackgroundAudio ?? false,\n sourceMap,\n true,\n );\n if (result.ssml.length > resolvedMaxLength) {\n throw new RangeError(\"maxLength is too small to contain the SSML document wrapper\");\n }\n return [result];\n }\n let textStart = 0;\n return chunks.map((chunk, chunkIndex) => {\n const result = createChunk(\n document,\n chunk,\n chunkIndex,\n textStart,\n backgroundAudio,\n resolvedOptions.replicateBackgroundAudio ?? false,\n sourceMap,\n chunkIndex === chunks.length - 1,\n );\n textStart = result.originalTextRange.end;\n return result;\n });\n}\n","import { parseSsml } from \"./parser.ts\";\n\nconst PARSER_POSITION_SUFFIX = / at position (\\d+)$/;\n\nexport interface SsmlValidationError {\n message: string;\n position: number;\n}\n\nexport function validateSsml(xmlString: string): SsmlValidationError | null {\n try {\n parseSsml(xmlString);\n return null;\n } catch (error) {\n const rawMessage = error instanceof Error ? error.message : String(error);\n const positionMatch = PARSER_POSITION_SUFFIX.exec(rawMessage);\n\n return {\n message: positionMatch ? rawMessage.slice(0, positionMatch.index) : rawMessage,\n position: positionMatch ? Number.parseInt(positionMatch[1], 10) : 0,\n };\n }\n}\n","import { parseSsml } from \"./parser.ts\";\nimport type { SsmlAttributeValue, SsmlAttributes, SsmlDocument, SsmlElement, SsmlNode } from \"./types.ts\";\nimport type { SsmlTextNodeContext } from \"./textNodes.ts\";\n\nconst DEFAULT_TRANSLATION_SKIP_TAGS = [\"phoneme\", \"say-as\", \"sayAs\", \"sub\"] as const;\n\nexport interface ExtractSsmlTranslatableTextOptions {\n /** Element names whose descendants are not translation targets. */\n skipTags?: readonly string[];\n /** Include indentation and whitespace-only text nodes. Defaults to false. */\n includeWhitespace?: boolean;\n /** Further restrict text nodes after the skip-tag check. */\n filter?: (context: SsmlTextNodeContext) => boolean;\n}\n\nexport interface FromPlainTextToSsmlOptions {\n version?: string;\n lang?: string;\n /** Alias for lang, useful when options come from an application form. */\n language?: string;\n /** Wrap generated paragraphs in a voice element. */\n voice?: string;\n /** Alias for voice. */\n voiceName?: string;\n /** Generate sentence elements inside paragraphs. Defaults to true. */\n includeSentences?: boolean;\n /** Alias for includeSentences. */\n splitSentences?: boolean;\n}\n\nexport interface SsmlStructureMismatch {\n kind: \"element\" | \"attribute\" | \"parse\";\n path: string;\n original?: string;\n translated?: string;\n message: string;\n}\n\nexport interface SsmlStructureIntegrityResult {\n isValid: boolean;\n /** Alias for isValid for callers that prefer a shorter result property. */\n valid: boolean;\n errors: string[];\n mismatches: SsmlStructureMismatch[];\n /** Element or attribute names involved in each mismatch. */\n mismatchedTags: string[];\n}\n\nfunction elementName(element: SsmlElement): string {\n switch (element.type) {\n case \"custom\":\n case \"element\":\n return element.name;\n case \"expressAs\":\n return \"mstts:express-as\";\n case \"sayAs\":\n return \"say-as\";\n case \"silence\":\n return \"mstts:silence\";\n case \"viseme\":\n return \"mstts:viseme\";\n default:\n return element.type;\n }\n}\n\nfunction addAttribute(attributes: SsmlAttributes, name: string, value: SsmlAttributeValue | string | undefined): void {\n if (value !== undefined) attributes[name] = value;\n}\n\nfunction elementAttributes(element: SsmlElement): Record<string, string> {\n const attributes: SsmlAttributes = { ...(element.attributes ?? {}) };\n switch (element.type) {\n case \"voice\":\n addAttribute(attributes, \"name\", element.name);\n addAttribute(attributes, \"effect\", element.effect);\n break;\n case \"prosody\":\n addAttribute(attributes, \"rate\", element.rate);\n addAttribute(attributes, \"pitch\", element.pitch);\n addAttribute(attributes, \"volume\", element.volume);\n addAttribute(attributes, \"contour\", element.contour);\n addAttribute(attributes, \"range\", element.range);\n break;\n case \"break\":\n addAttribute(attributes, \"time\", element.time);\n addAttribute(attributes, \"strength\", element.strength);\n break;\n case \"express-as\":\n case \"expressAs\":\n case \"mstts:express-as\":\n addAttribute(attributes, \"style\", element.style);\n addAttribute(attributes, \"styledegree\", element.styleDegree);\n addAttribute(attributes, \"role\", element.role);\n break;\n case \"say-as\":\n case \"sayAs\":\n addAttribute(attributes, \"interpret-as\", element.interpretAs);\n addAttribute(attributes, \"format\", element.format);\n addAttribute(attributes, \"detail\", element.detail);\n break;\n case \"phoneme\":\n addAttribute(attributes, \"alphabet\", element.alphabet);\n addAttribute(attributes, \"ph\", element.ph);\n break;\n case \"emphasis\":\n addAttribute(attributes, \"level\", element.level);\n break;\n case \"audio\":\n addAttribute(attributes, \"src\", element.src);\n addAttribute(attributes, \"desc\", element.desc);\n addAttribute(attributes, \"clipBegin\", element.clipBegin);\n addAttribute(attributes, \"clipEnd\", element.clipEnd);\n addAttribute(attributes, \"speed\", element.speed);\n addAttribute(attributes, \"repeatCount\", element.repeatCount);\n addAttribute(attributes, \"repeatDuration\", element.repeatDuration);\n addAttribute(attributes, \"soundLevel\", element.soundLevel);\n break;\n case \"sub\":\n addAttribute(attributes, \"alias\", element.alias);\n break;\n case \"lang\":\n addAttribute(attributes, \"xml:lang\", element.lang);\n break;\n case \"mark\":\n addAttribute(attributes, \"name\", element.name);\n break;\n case \"bookmark\":\n addAttribute(attributes, \"mark\", element.mark);\n break;\n case \"lexicon\":\n addAttribute(attributes, \"uri\", element.uri);\n break;\n case \"mstts:silence\":\n case \"silence\":\n addAttribute(attributes, \"type\", element.typeValue ?? element.silenceType);\n addAttribute(attributes, \"value\", element.value);\n break;\n case \"mstts:viseme\":\n case \"viseme\":\n addAttribute(attributes, \"type\", element.typeValue ?? element.visemeType);\n break;\n case \"mstts:audioduration\":\n addAttribute(attributes, \"value\", element.value);\n break;\n case \"mstts:turn\":\n addAttribute(attributes, \"voice\", element.voice);\n addAttribute(attributes, \"speaker\", element.speaker);\n break;\n case \"mstts:backgroundaudio\":\n addAttribute(attributes, \"src\", element.src);\n addAttribute(attributes, \"volume\", element.volume);\n addAttribute(attributes, \"fadein\", element.fadeIn ?? element.fadein);\n addAttribute(attributes, \"fadeout\", element.fadeOut ?? element.fadeout);\n break;\n case \"mstts:ttsembedding\":\n addAttribute(attributes, \"speakerProfileId\", element.speakerProfileId);\n break;\n case \"mstts:embedding\":\n addAttribute(attributes, \"id\", element.id);\n addAttribute(attributes, \"speakerProfileId\", element.speakerProfileId);\n break;\n case \"mstts:voiceconversion\":\n addAttribute(attributes, \"url\", element.url);\n addAttribute(attributes, \"profile\", element.profile);\n addAttribute(attributes, \"speakerProfileId\", element.speakerProfileId);\n break;\n }\n return Object.fromEntries(Object.entries(attributes).map(([name, value]) => [name, String(value)]));\n}\n\nfunction childrenOf(node: SsmlDocument | SsmlElement): SsmlNode[] {\n return node.children ?? [];\n}\n\nexport function extractSsmlTranslatableText(ssml: string, options: ExtractSsmlTranslatableTextOptions = {}): string[] {\n const document = parseSsml(ssml);\n const skipTags = new Set((options.skipTags ?? DEFAULT_TRANSLATION_SKIP_TAGS).map((tag) => tag.toLowerCase()));\n const result: string[] = [];\n\n const visit = (nodes: SsmlNode[], ancestors: string[], path: string[]): void => {\n nodes.forEach((node, index) => {\n if (typeof node === \"string\") {\n if (options.includeWhitespace || node.trim().length > 0) {\n const context: SsmlTextNodeContext = {\n ancestorTags: [...ancestors],\n parentAttributes: {},\n parentTag: ancestors[ancestors.length - 1] ?? \"\",\n path: [...path, String(index)],\n };\n if (options.filter?.(context) ?? true) result.push(node);\n }\n return;\n }\n if (node.type === \"text\") {\n if (options.includeWhitespace || node.value.trim().length > 0) {\n const context: SsmlTextNodeContext = {\n ancestorTags: [...ancestors],\n parentAttributes: {},\n parentTag: ancestors[ancestors.length - 1] ?? \"\",\n path: [...path, String(index)],\n };\n if (options.filter?.(context) ?? true) result.push(node.value);\n }\n return;\n }\n\n const tag = elementName(node);\n if (skipTags.has(tag.toLowerCase())) return;\n visit(childrenOf(node), [...ancestors, tag], [...path, String(index)]);\n });\n };\n\n visit(childrenOf(document), [\"speak\"], []);\n return result;\n}\n\nfunction splitSentences(text: string): string[] {\n const sentences: string[] = [];\n let start = 0;\n for (let index = 0; index < text.length; index += 1) {\n const character = text[index];\n const isTerminator = \"。!?!?\".includes(character) || (character === \".\" && /\\s|$/.test(text[index + 1] ?? \"\"));\n if (isTerminator) {\n const value = text.slice(start, index + 1).trim();\n if (value) sentences.push(value);\n start = index + 1;\n }\n }\n const tail = text.slice(start).trim();\n if (tail) sentences.push(tail);\n return sentences;\n}\n\nexport function fromPlainTextToSsml(text: string, options: FromPlainTextToSsmlOptions = {}): string {\n if (typeof text !== \"string\") throw new TypeError(\"Plain text must be a string\");\n const paragraphs = text\n .replace(/\\r\\n?/g, \"\\n\")\n .split(/\\n\\s*\\n/)\n .map((paragraph) => paragraph.replace(/\\s*\\n\\s*/g, \" \").trim())\n .filter(Boolean);\n const useSentences = options.splitSentences ?? options.includeSentences ?? true;\n const paragraphNodes = paragraphs.map((paragraph) => ({\n type: \"p\" as const,\n children: useSentences\n ? splitSentences(paragraph).map((sentence) => ({ type: \"s\" as const, children: [sentence] }))\n : [paragraph],\n }));\n const voiceName = options.voice ?? options.voiceName;\n const children: SsmlNode[] = voiceName\n ? [{ type: \"voice\", name: voiceName, children: paragraphNodes }]\n : paragraphNodes;\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n${serializeDocument({\n version: options.version ?? \"1.0\",\n lang: options.lang ?? options.language ?? \"en-US\",\n children,\n })}`;\n}\n\nfunction serializeDocument(document: SsmlDocument): string {\n const attributes = [`version=\"${document.version}\"`, `xml:lang=\"${document.lang}\"`];\n const serialize = (node: SsmlNode): string => {\n if (typeof node === \"string\") return node.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n if (node.type === \"text\") return serialize(node.value);\n const tag = elementName(node);\n const nodeAttributes = elementAttributes(node);\n const serializedAttributes = Object.entries(nodeAttributes)\n .map(([name, value]) => ` ${name}=\"${serialize(value).replace(/\"/g, \"&quot;\")}\"`)\n .join(\"\");\n const children = childrenOf(node).map(serialize).join(\"\");\n return children ? `<${tag}${serializedAttributes}>${children}</${tag}>` : `<${tag}${serializedAttributes}/>`;\n };\n return `<speak ${attributes.join(\" \")} xmlns=\"http://www.w3.org/2001/10/synthesis\">${(document.children ?? [])\n .map(serialize)\n .join(\"\")}</speak>`;\n}\n\ninterface FlatElement {\n name: string;\n attributes: Record<string, string>;\n path: string;\n}\n\nfunction flatten(document: SsmlDocument): FlatElement[] {\n const result: FlatElement[] = [];\n const visit = (nodes: SsmlNode[], path: string): void => {\n nodes.forEach((node, index) => {\n if (typeof node === \"string\" || node.type === \"text\") return;\n const currentPath = `${path}/${index}`;\n result.push({ name: elementName(node), attributes: elementAttributes(node), path: currentPath });\n visit(childrenOf(node), currentPath);\n });\n };\n result.push({ name: \"speak\", attributes: { version: document.version, \"xml:lang\": document.lang }, path: \"0\" });\n visit(childrenOf(document), \"0\");\n return result;\n}\n\nexport function validateSsmlStructureIntegrity(\n originalSsml: string,\n translatedSsml: string,\n): SsmlStructureIntegrityResult {\n const mismatches: SsmlStructureMismatch[] = [];\n let original: SsmlDocument;\n let translated: SsmlDocument;\n try {\n original = parseSsml(originalSsml);\n } catch (error) {\n mismatches.push({ kind: \"parse\", message: `Original SSML cannot be parsed: ${String(error)}`, path: \"0\" });\n return {\n isValid: false,\n valid: false,\n errors: mismatches.map((item) => item.message),\n mismatches,\n mismatchedTags: [],\n };\n }\n try {\n translated = parseSsml(translatedSsml);\n } catch (error) {\n mismatches.push({ kind: \"parse\", message: `Translated SSML cannot be parsed: ${String(error)}`, path: \"0\" });\n return {\n isValid: false,\n valid: false,\n errors: mismatches.map((item) => item.message),\n mismatches,\n mismatchedTags: [],\n };\n }\n\n const originalElements = flatten(original);\n const translatedElements = flatten(translated);\n const count = Math.max(originalElements.length, translatedElements.length);\n for (let index = 0; index < count; index += 1) {\n const originalElement = originalElements[index];\n const translatedElement = translatedElements[index];\n if (!originalElement || !translatedElement || originalElement.name !== translatedElement.name) {\n mismatches.push({\n kind: \"element\",\n message: `SSML element structure differs at index ${index}`,\n original: originalElement?.name,\n path: originalElement?.path ?? translatedElement?.path ?? String(index),\n translated: translatedElement?.name,\n });\n continue;\n }\n const attributeNames = new Set([\n ...Object.keys(originalElement.attributes),\n ...Object.keys(translatedElement.attributes),\n ]);\n for (const attribute of attributeNames) {\n if (originalElement.attributes[attribute] !== translatedElement.attributes[attribute]) {\n mismatches.push({\n kind: \"attribute\",\n message: `Attribute ${attribute} differs on <${originalElement.name}>`,\n original: originalElement.attributes[attribute],\n path: originalElement.path,\n translated: translatedElement.attributes[attribute],\n });\n }\n }\n }\n\n const mismatchedTags = [\n ...new Set(mismatches.flatMap((mismatch) => [mismatch.original, mismatch.translated].filter(Boolean) as string[])),\n ];\n const errors = mismatches.map((mismatch) => mismatch.message);\n return { isValid: mismatches.length === 0, valid: mismatches.length === 0, errors, mismatches, mismatchedTags };\n}\n","/** Generated by scripts/sync-azure-voices.ts. */\nimport type { AzureVoiceDefinition } from \"../azureValidation.ts\";\n\nexport const AZURE_VOICE_DEFINITIONS: readonly AzureVoiceDefinition[] = [\n { name: \"de-DE-ConradNeural\", locale: \"de-DE\", styles: [\"cheerful\", \"sad\"] },\n { name: \"de-DE-KatjaNeural\", locale: \"de-DE\", styles: [\"cheerful\", \"sad\"] },\n { name: \"en-US-AndrewNeural\", locale: \"en-US\", styles: [\"empathetic\", \"relieved\"] },\n {\n name: \"en-US-GuyNeural\",\n locale: \"en-US\",\n styles: [\n \"angry\",\n \"cheerful\",\n \"excited\",\n \"friendly\",\n \"hopeful\",\n \"newscast\",\n \"sad\",\n \"shouting\",\n \"terrified\",\n \"unfriendly\",\n \"whispering\",\n ],\n },\n {\n name: \"en-US-JennyMultilingualNeural\",\n locale: \"en-US\",\n styles: [\n \"cheerful\",\n \"empathetic\",\n \"excited\",\n \"friendly\",\n \"hopeful\",\n \"sad\",\n \"shouting\",\n \"terrified\",\n \"unfriendly\",\n \"whispering\",\n ],\n },\n {\n name: \"en-US-JennyNeural\",\n locale: \"en-US\",\n styles: [\n \"assistant\",\n \"chat\",\n \"customerservice\",\n \"newscast\",\n \"cheerful\",\n \"empathetic\",\n \"excited\",\n \"friendly\",\n \"hopeful\",\n \"sad\",\n \"shouting\",\n \"terrified\",\n \"unfriendly\",\n \"whispering\",\n ],\n },\n { name: \"es-ES-ElviraNeural\", locale: \"es-ES\" },\n { name: \"fil-PH-AngeloNeural\", locale: \"fil-PH\" },\n { name: \"fil-PH-Angelo:DragonHDLatestNeural\", locale: \"fil-PH\" },\n { name: \"fil-PH-BlessicaNeural\", locale: \"fil-PH\" },\n { name: \"fil-PH-Blessica:DragonHDLatestNeural\", locale: \"fil-PH\" },\n { name: \"fr-FR-DeniseNeural\", locale: \"fr-FR\", styles: [\"cheerful\", \"sad\"] },\n { name: \"fr-FR-HenriNeural\", locale: \"fr-FR\", styles: [\"cheerful\", \"sad\"] },\n { name: \"id-ID-GadisNeural\", locale: \"id-ID\" },\n { name: \"it-IT-ElsaNeural\", locale: \"it-IT\", styles: [\"cheerful\", \"sad\"] },\n { name: \"ja-JP-KeitaNeural\", locale: \"ja-JP\", styles: [\"chat\"] },\n { name: \"ja-JP-MayuNeural\", locale: \"ja-JP\", styles: [\"calm\", \"cheerful\", \"sad\"] },\n { name: \"ja-JP-NanamiNeural\", locale: \"ja-JP\", styles: [\"chat\", \"customerservice\", \"cheerful\", \"whispering\", \"sad\"] },\n { name: \"ko-KR-SunHiNeural\", locale: \"ko-KR\", styles: [\"cheerful\", \"sad\"] },\n { name: \"ms-MY-YasminNeural\", locale: \"ms-MY\" },\n { name: \"pt-BR-FranciscaNeural\", locale: \"pt-BR\", styles: [\"calm\"] },\n {\n name: \"ru-RU-SvetlanaNeural\",\n locale: \"ru-RU\",\n styles: [\"cheerful\", \"sad\", \"angry\", \"disgruntled\", \"embarrassed\", \"fearful\"],\n },\n { name: \"th-TH-PremwadeeNeural\", locale: \"th-TH\" },\n { name: \"vi-VN-HoaiMyNeural\", locale: \"vi-VN\" },\n {\n name: \"zh-CN-XiaoxiaoNeural\",\n locale: \"zh-CN\",\n styles: [\n \"assistant\",\n \"chat\",\n \"customerservice\",\n \"newscast\",\n \"cheerful\",\n \"empathetic\",\n \"excited\",\n \"friendly\",\n \"hopeful\",\n \"sad\",\n \"terrified\",\n \"whispering\",\n \"poetry-reading\",\n \"sports_commentary\",\n \"sports_commentary_excited\",\n \"story\",\n ],\n },\n {\n name: \"zh-CN-YunxiNeural\",\n locale: \"zh-CN\",\n styles: [\n \"narration-relaxed\",\n \"embarrassed\",\n \"fearful\",\n \"sad\",\n \"disgruntled\",\n \"serious\",\n \"angry\",\n \"depressed\",\n \"chat\",\n \"cheerful\",\n \"assistant\",\n ],\n },\n { name: \"zh-TW-HsiaoChenNeural\", locale: \"zh-TW\" },\n];\n","import { parseSsml } from \"./parser.ts\";\nimport { AZURE_VOICE_DEFINITIONS } from \"./generated/azureVoiceDefinitions.ts\";\n\nexport type SsmlDiagnosticSeverity = \"error\" | \"warning\" | \"info\";\nexport type SsmlDiagnosticSource = \"ssml-static-validator\";\n\nexport type AzureDiagnosticCode =\n | \"azure-unknown-voice\"\n | \"azure-unsupported-style\"\n | \"azure-locale-mismatch\"\n | \"azure-unsupported-tag-for-voice\"\n | \"azure-unsupported-model-for-voice\"\n | \"azure-preview-voice\"\n | \"azure-deprecated-voice\"\n | \"azure-preview-tag\"\n | \"azure-deprecated-tag\";\n\nexport interface SsmlDiagnostic {\n code?: AzureDiagnosticCode;\n line: number;\n column: number;\n message: string;\n severity: SsmlDiagnosticSeverity;\n source: SsmlDiagnosticSource;\n /** Structured location and source metadata; message parsing is not required. */\n targetNodePath?: string[];\n /** Alias retained for callers using the shorter terminology. */\n nodePath?: string[];\n range?: { start: number; end: number };\n tagName?: string;\n attributeName?: string;\n voiceName?: string;\n chunkIndex?: number;\n}\n\n/** Generic name for a structured SSML diagnostic. */\nexport type Diagnostic = SsmlDiagnostic;\n\nexport interface AzureVoiceDefinition {\n name: string;\n locale: string;\n secondaryLocales?: readonly string[];\n styles?: readonly string[];\n supportedTags?: readonly string[];\n unsupportedTags?: readonly string[];\n models?: readonly string[];\n regions?: readonly string[];\n status?: \"ga\" | \"preview\" | \"deprecated\";\n}\n\n/** Alias retained for consumers that prefer the metadata terminology. */\nexport interface AzureVoiceMetadata extends AzureVoiceDefinition {}\n\nexport interface AzureValidationOptions {\n allowedAudioOrigins?: readonly string[];\n allowExternalAudio?: boolean;\n allowHttpAudio?: boolean;\n customVoiceStyleMap?: Record<string, readonly string[]>;\n customVoiceDefinitions?: readonly AzureVoiceDefinition[];\n /** Host-side validation hook for URL-bearing SSML attributes. */\n urlValidator?: AzureUrlValidator;\n /** Source path associated with a chunk being validated. */\n sourceNodePath?: readonly string[];\n chunkIndex?: number;\n /** Alias for urlValidator retained for applications that use the longer name. */\n customUrlValidator?: AzureUrlValidator;\n /** Controls deduplication, caching, cancellation, and concurrency for URL checks. */\n urlValidation?: AzureUrlValidationRunnerOptions;\n /** Flat aliases retained for callers that prefer not to nest URL runner options. */\n urlValidatorConcurrency?: number;\n urlValidatorTimeoutMs?: number;\n urlValidatorSignal?: AbortSignal;\n urlValidatorCache?: Map<string, AzureUrlValidationResult>;\n /** Shared runner used by chunk orchestration to deduplicate in-flight checks. */\n urlValidatorRunner?: AzureUrlValidator;\n languageAliases?: Record<string, string | readonly string[]>;\n maxLength?: number;\n /** Maximum XML element nesting depth, counting `<speak>` as depth 1. */\n maxXmlDepth?: number;\n /** Optional model identifier used to validate a voice's model compatibility. */\n model?: string;\n normalizeLanguage?: (lang: string) => string;\n /** Overrides the built-in preview tag list for this validation run. */\n previewTags?: readonly string[];\n /** Adds tags that should be reported as deprecated for this validation run. */\n deprecatedTags?: readonly string[];\n /** Explicit tag lifecycle metadata. This takes precedence over previewTags/deprecatedTags. */\n tagStatuses?: Readonly<Record<string, \"ga\" | \"preview\" | \"deprecated\">>;\n unknownVoicePolicy?: \"error\" | \"warn\" | \"ignore\";\n unsupportedStylePolicy?: \"error\" | \"warn\" | \"ignore\";\n validateNestedVoices?: boolean;\n voiceCatalog?: readonly AzureVoiceDefinition[];\n voiceDefinitions?: readonly AzureVoiceDefinition[];\n}\n\nexport type AzureUrlValidationResult = boolean | { valid: boolean; reason?: string };\nexport type AzureUrlValidator = (\n url: string,\n context: { tag: string; attribute: string; sourceNodePath?: readonly string[] },\n signal: AbortSignal,\n) => AzureUrlValidationResult | Promise<AzureUrlValidationResult>;\n\nexport interface AzureUrlValidationRunnerOptions {\n concurrency?: number;\n cache?: Map<string, AzureUrlValidationResult>;\n signal?: AbortSignal;\n timeoutMs?: number;\n}\n\n/** Wraps a URL validator with URL deduplication, bounded concurrency, caching, and cancellation. */\nexport function createAzureUrlValidatorRunner(\n validator: AzureUrlValidator,\n options: AzureUrlValidationRunnerOptions = {},\n): AzureUrlValidator {\n if (typeof validator !== \"function\") throw new TypeError(\"A URL validator function is required.\");\n const concurrency =\n options.concurrency === undefined\n ? Infinity\n : Number.isFinite(options.concurrency)\n ? Math.max(1, Math.floor(options.concurrency))\n : Infinity;\n const cache = options.cache ?? new Map<string, AzureUrlValidationResult>();\n const inFlight = new Map<string, Promise<AzureUrlValidationResult>>();\n const waiters: Array<() => void> = [];\n let active = 0;\n\n const configuredSignal = options.signal ?? new AbortController().signal;\n const acquire = async (signal: AbortSignal): Promise<void> => {\n if (signal.aborted) throw new Error(\"URL validation was aborted.\");\n if (active < concurrency) {\n active += 1;\n return;\n }\n await new Promise<void>((resolve, reject) => {\n let waiter: () => void;\n const abortHandler = () => {\n const index = waiters.indexOf(waiter);\n if (index >= 0) waiters.splice(index, 1);\n signal.removeEventListener(\"abort\", abortHandler);\n reject(new Error(\"URL validation was aborted.\"));\n };\n signal.addEventListener(\"abort\", abortHandler, { once: true });\n waiter = () => {\n signal.removeEventListener(\"abort\", abortHandler);\n resolve();\n };\n waiters.push(waiter);\n });\n active += 1;\n };\n const release = (): void => {\n active -= 1;\n waiters.shift()?.();\n };\n const check = async (\n url: string,\n context: { tag: string; attribute: string; sourceNodePath?: readonly string[] },\n signal = configuredSignal,\n ): Promise<AzureUrlValidationResult> => {\n if (signal.aborted) throw new Error(\"URL validation was aborted.\");\n const key = `${context.tag}:${context.attribute}:${url}`;\n const cached = cache.get(key);\n if (cached !== undefined) return cached;\n const existing = inFlight.get(key);\n if (existing) return existing;\n const promise = (async () => {\n await acquire(signal);\n try {\n if (signal.aborted) throw new Error(\"URL validation was aborted.\");\n const validation = Promise.resolve(validator(url, context, signal));\n let timer: ReturnType<typeof setTimeout> | undefined;\n let abortHandler: (() => void) | undefined;\n const cancellation = new Promise<AzureUrlValidationResult>((_resolve, reject) => {\n abortHandler = () => reject(new Error(\"URL validation was aborted.\"));\n signal.addEventListener(\"abort\", abortHandler, { once: true });\n if (options.timeoutMs !== undefined && options.timeoutMs > 0) {\n timer = setTimeout(\n () => reject(new Error(`URL validation timed out after ${options.timeoutMs} ms.`)),\n options.timeoutMs,\n );\n }\n });\n try {\n const result = await (timer || abortHandler ? Promise.race([validation, cancellation]) : validation);\n cache.set(key, result);\n return result;\n } finally {\n if (timer) clearTimeout(timer);\n if (abortHandler) signal.removeEventListener(\"abort\", abortHandler);\n }\n } finally {\n release();\n }\n })();\n inFlight.set(key, promise);\n try {\n return await promise;\n } finally {\n inFlight.delete(key);\n }\n };\n return (url, context, signal) => check(url, context, signal ?? configuredSignal);\n}\n\nexport type AzureLanguageNormalizationOptions = Pick<AzureValidationOptions, \"languageAliases\" | \"normalizeLanguage\">;\n\n/** @deprecated Use AzureValidationOptions instead. */\nexport type AzureSsmlValidationOptions = AzureValidationOptions;\n\ninterface ElementToken {\n attributes: Map<string, string>;\n childElementIndex?: number;\n end: number;\n depth: number;\n parentName?: string;\n name: string;\n parentVoiceName?: string;\n start: number;\n selfClosing: boolean;\n path: string[];\n}\n\nconst ALLOWED_BREAK_STRENGTHS = new Set([\"none\", \"x-weak\", \"weak\", \"medium\", \"strong\", \"x-strong\"]);\nconst ALLOWED_SAY_AS = new Set([\n \"characters\",\n \"spell-out\",\n \"cardinal\",\n \"ordinal\",\n \"number\",\n \"date\",\n \"time\",\n \"telephone\",\n \"fraction\",\n \"address\",\n \"name\",\n \"currency\",\n \"number_digit\",\n]);\nconst ALLOWED_ROLES = new Set([\n \"Girl\",\n \"Boy\",\n \"YoungAdultFemale\",\n \"YoungAdultMale\",\n \"OlderAdultFemale\",\n \"OlderAdultMale\",\n \"SeniorFemale\",\n \"SeniorMale\",\n]);\nconst ALLOWED_EMPHASIS_LEVELS = new Set([\"strong\", \"moderate\", \"reduced\", \"none\"]);\nconst ALLOWED_SILENCE_TYPES = new Set([\n \"Leading\",\n \"Tailing\",\n \"Sentenceboundary\",\n \"Comma\",\n \"Semicolon\",\n \"Enumerationcomma\",\n]);\nconst ALLOWED_VISEME_TYPES = new Set([\"redlips_front\", \"FacialExpression\"]);\nconst DEFAULT_PREVIEW_TAGS = new Set([\"mstts:voiceconversion\"]);\n\nfunction featureStatusForTag(\n name: string,\n options: AzureValidationOptions,\n): \"ga\" | \"preview\" | \"deprecated\" | undefined {\n const tagName = canonicalTagName(name);\n const configured = Object.entries(options.tagStatuses ?? {}).find(\n ([candidate]) => canonicalTagName(candidate) === tagName,\n )?.[1];\n if (configured) return configured;\n if ((options.previewTags ?? [...DEFAULT_PREVIEW_TAGS]).some((candidate) => canonicalTagName(candidate) === tagName))\n return \"preview\";\n if ((options.deprecatedTags ?? []).some((candidate) => canonicalTagName(candidate) === tagName)) return \"deprecated\";\n return undefined;\n}\n\nfunction decodeAttribute(value: string): string {\n return value.replace(\n /&(?:amp|apos|gt|lt|quot);/gi,\n (entity) =>\n ({ \"&amp;\": \"&\", \"&apos;\": \"'\", \"&gt;\": \">\", \"&lt;\": \"<\", \"&quot;\": '\"' })[entity.toLowerCase()] ?? entity,\n );\n}\n\nfunction findTagEnd(source: string, start: number): number {\n let quote = \"\";\n for (let index = start; index < source.length; index += 1) {\n const character = source[index];\n if (quote) {\n if (character === quote) quote = \"\";\n } else if (character === '\"' || character === \"'\") quote = character;\n else if (character === \">\") return index;\n }\n return source.length - 1;\n}\n\nfunction tokenizeElements(source: string): ElementToken[] {\n const tokens: ElementToken[] = [];\n const openElements: Array<{ childElementCount: number; name: string; path: string[]; voiceName?: string }> = [];\n let index = 0;\n while (index < source.length) {\n const start = source.indexOf(\"<\", index);\n if (start === -1) break;\n if (source.startsWith(\"<!--\", start)) {\n const end = source.indexOf(\"-->\", start + 4);\n index = end === -1 ? source.length : end + 3;\n continue;\n }\n if (source.startsWith(\"<![CDATA[\", start)) {\n const end = source.indexOf(\"]]>\", start + 9);\n index = end === -1 ? source.length : end + 3;\n continue;\n }\n if (source.startsWith(\"<?\", start)) {\n const end = source.indexOf(\"?>\", start + 2);\n index = end === -1 ? source.length : end + 2;\n continue;\n }\n const end = findTagEnd(source, start + 1);\n const raw = source.slice(start, end + 1);\n if (raw.startsWith(\"</\")) {\n openElements.pop();\n index = end + 1;\n continue;\n }\n const nameMatch = /^<\\s*([A-Za-z_][A-Za-z0-9_.:-]*)/.exec(raw);\n if (!nameMatch?.[1]) {\n index = end + 1;\n continue;\n }\n const attributes = new Map<string, string>();\n const attributeSource = raw.slice(nameMatch[0].length, raw.length - 1).replace(/\\/\\s*$/, \"\");\n const attributePattern = /([A-Za-z_][A-Za-z0-9_.:-]*)\\s*=\\s*([\"'])([\\s\\S]*?)\\2/g;\n for (const match of attributeSource.matchAll(attributePattern)) {\n attributes.set(match[1].toLowerCase(), decodeAttribute(match[3]));\n }\n const selfClosing = /\\/\\s*>$/.test(raw);\n const parent = openElements[openElements.length - 1];\n const childElementIndex = parent?.childElementCount;\n if (parent) parent.childElementCount += 1;\n const parentVoiceName = [...openElements].reverse().find((element) => element.voiceName)?.voiceName;\n const tokenName = nameMatch[1];\n const path = parent ? [...parent.path, `${tokenName}[${childElementIndex ?? 0}]`] : [tokenName];\n const tokenVoiceName =\n tokenName.toLowerCase() === \"voice\"\n ? attributes.get(\"name\")\n : tokenName.toLowerCase() === \"mstts:turn\"\n ? (attributes.get(\"voice\") ?? parentVoiceName)\n : parentVoiceName;\n tokens.push({\n attributes,\n childElementIndex,\n end,\n depth: openElements.length + 1,\n name: tokenName,\n parentName: parent?.name,\n parentVoiceName,\n selfClosing,\n start,\n path,\n });\n if (!selfClosing) {\n openElements.push({\n childElementCount: 0,\n name: tokenName,\n path,\n voiceName: tokenVoiceName,\n });\n }\n index = end + 1;\n }\n return tokens;\n}\n\nfunction location(source: string, offset: number): { column: number; line: number } {\n const before = source.slice(0, Math.max(0, offset));\n const line = before.split(\"\\n\").length;\n return { line, column: before.length - (before.lastIndexOf(\"\\n\") + 1) + 1 };\n}\n\nfunction addDiagnostic(\n diagnostics: SsmlDiagnostic[],\n source: string,\n offset: number,\n message: string,\n severity: SsmlDiagnosticSeverity = \"error\",\n code?: AzureDiagnosticCode,\n metadata: Partial<\n Pick<\n SsmlDiagnostic,\n \"tagName\" | \"attributeName\" | \"voiceName\" | \"chunkIndex\" | \"range\" | \"nodePath\" | \"targetNodePath\"\n >\n > = {},\n): void {\n diagnostics.push({\n ...location(source, offset),\n message,\n severity,\n source: \"ssml-static-validator\",\n ...(code ? { code } : {}),\n ...metadata,\n });\n}\n\nfunction isSupportedProsodyRate(value: string): boolean {\n const trimmed = value.trim();\n if (/^(x-slow|slow|medium|fast|x-fast|[+-]?\\d+(?:\\.\\d+)?%)$/.test(trimmed)) return true;\n const multiplier = /^(\\d+(?:\\.\\d+)?)(x)?$/i.exec(trimmed);\n if (!multiplier) return false;\n const numericValue = Number(multiplier[1]);\n return numericValue >= 0.5 && numericValue <= 2;\n}\n\n/** Returns whether a value is a positive Azure SSML audio duration. */\nexport function isValidAzureAudioDuration(value: string): boolean {\n const trimmed = value.trim();\n const numeric = /^(\\d+(?:\\.\\d+)?)(ms|s)$/.exec(trimmed);\n if (numeric) return Number(numeric[1]) > 0;\n\n const clock = /^(\\d{2,}):([0-5]\\d):([0-5]\\d)(?:\\.(\\d{1,3}))?$/.exec(trimmed);\n if (!clock) return false;\n return Number(clock[1]) > 0 || Number(clock[2]) > 0 || Number(clock[3]) > 0 || Number(clock[4] ?? 0) > 0;\n}\n\nfunction isValidAzureBackgroundAudioDuration(value: string): boolean {\n const match = /^(\\d+)$/.exec(value.trim());\n if (!match) return false;\n const milliseconds = Number(match[1]);\n return Number.isFinite(milliseconds) && milliseconds >= 0 && milliseconds <= 10_000;\n}\n\nfunction attr(token: ElementToken, name: string): string | undefined {\n return token.attributes.get(name.toLowerCase());\n}\n\nconst DEFAULT_LANGUAGE_ALIASES: Readonly<Record<string, readonly string[]>> = {\n \"zh-CN\": [\"zh-Hans\"],\n \"zh-TW\": [\"zh-Hant\"],\n};\n\nfunction canonicalLanguageTag(language: string): string {\n const trimmed = language.trim();\n if (!trimmed) return \"\";\n try {\n return new Intl.Locale(trimmed).toString().toLowerCase();\n } catch {\n return trimmed.toLowerCase();\n }\n}\n\nfunction createLanguageNormalizer(options: AzureValidationOptions): (language: string) => string {\n const aliases = new Map<string, string>();\n const addAliasGroup = (canonical: string, values: readonly string[]): void => {\n const normalizedCanonical = canonicalLanguageTag(canonical);\n if (!normalizedCanonical) return;\n aliases.set(normalizedCanonical, normalizedCanonical);\n for (const value of values) {\n const normalizedValue = canonicalLanguageTag(value);\n if (normalizedValue) aliases.set(normalizedValue, normalizedCanonical);\n }\n };\n for (const [canonical, values] of Object.entries(DEFAULT_LANGUAGE_ALIASES)) addAliasGroup(canonical, values);\n for (const [canonical, valueOrValues] of Object.entries(options.languageAliases ?? {}))\n addAliasGroup(canonical, typeof valueOrValues === \"string\" ? [valueOrValues] : valueOrValues);\n\n return (language: string): string => {\n const customValue = options.normalizeLanguage ? options.normalizeLanguage(language) : language;\n const normalized = canonicalLanguageTag(customValue);\n return aliases.get(normalized) ?? normalized;\n };\n}\n\n/** Normalizes an Azure language tag using BCP 47 and the configured aliases. */\nexport function normalizeAzureLanguage(language: string, options: AzureLanguageNormalizationOptions = {}): string {\n return createLanguageNormalizer(options)(language);\n}\n\n/** Compares two Azure language tags after BCP 47 and alias normalization. */\nexport function areAzureLanguagesEquivalent(\n first: string,\n second: string,\n options: AzureLanguageNormalizationOptions = {},\n): boolean {\n const normalize = createLanguageNormalizer(options);\n const normalizedFirst = normalize(first);\n const normalizedSecond = normalize(second);\n if (normalizedFirst === normalizedSecond) return true;\n return (\n normalizedFirst === languagePart(normalizedFirst) &&\n languagePart(normalizedFirst) === languagePart(normalizedSecond)\n );\n}\n\nfunction voiceLocalePrefix(voiceName: string): { language: string; region: string; tag: string } | undefined {\n const match = /^(?<language>[A-Za-z]{2,3})-(?<region>[A-Za-z]{2}|\\d{3})(?:-|$)/.exec(voiceName.trim());\n if (!match?.groups) return undefined;\n const tag = `${match.groups.language}-${match.groups.region}`;\n return {\n language: match.groups.language.toLowerCase(),\n region: match.groups.region.toLowerCase(),\n tag,\n };\n}\n\nfunction definitionFromStyleMap(voiceName: string, styles: readonly string[]): AzureVoiceDefinition {\n return {\n name: voiceName,\n locale: voiceLocalePrefix(voiceName)?.tag ?? \"\",\n styles,\n };\n}\n\nfunction normalizeVoiceCatalog(options: AzureValidationOptions): ReadonlyMap<string, AzureVoiceDefinition> {\n const definitions = new Map<string, AzureVoiceDefinition>();\n for (const definition of AZURE_VOICE_DEFINITIONS) definitions.set(definition.name.toLowerCase(), definition);\n for (const definition of options.voiceCatalog ?? []) definitions.set(definition.name.toLowerCase(), definition);\n for (const definition of options.voiceDefinitions ?? []) definitions.set(definition.name.toLowerCase(), definition);\n for (const definition of options.customVoiceDefinitions ?? [])\n definitions.set(definition.name.toLowerCase(), definition);\n for (const [voiceName, styles] of Object.entries(options.customVoiceStyleMap ?? {})) {\n const key = voiceName.toLowerCase();\n const current = definitions.get(key);\n definitions.set(key, {\n ...(current ?? definitionFromStyleMap(voiceName, styles)),\n name: current?.name ?? voiceName,\n styles: styles.map((style) => style.toLowerCase()),\n });\n }\n return definitions;\n}\n\nfunction diagnosticSeverity(policy: AzureValidationOptions[\"unknownVoicePolicy\"]): SsmlDiagnosticSeverity | undefined {\n if (policy === \"ignore\") return undefined;\n return policy === \"error\" ? \"error\" : \"warning\";\n}\n\nfunction languagePart(language: string): string {\n try {\n return new Intl.Locale(language).language.toLowerCase();\n } catch {\n return language.split(\"-\")[0]?.toLowerCase() ?? \"\";\n }\n}\n\nfunction definitionMatchesLanguage(\n definition: AzureVoiceDefinition | undefined,\n voiceName: string,\n language: string,\n normalizeLanguage: (language: string) => string,\n): boolean | undefined {\n const candidateLanguages = definition\n ? [definition.locale, ...(definition.secondaryLocales ?? [])].filter(Boolean)\n : [voiceLocalePrefix(voiceName)?.tag ?? \"\"];\n if (candidateLanguages.length === 0 || !language.trim()) return undefined;\n const normalizedLanguage = normalizeLanguage(language);\n const normalizedCandidates = candidateLanguages.map(normalizeLanguage);\n if (normalizedCandidates.includes(normalizedLanguage)) return true;\n if (!normalizedLanguage || !normalizedCandidates.some(Boolean)) return undefined;\n return normalizedLanguage === languagePart(normalizedLanguage)\n ? normalizedCandidates.some((candidate) => languagePart(candidate) === normalizedLanguage)\n : false;\n}\n\nfunction canonicalTagName(name: string): string {\n const normalized = name.toLowerCase();\n if (normalized === \"express-as\" || normalized === \"expressas\") return \"mstts:express-as\";\n if (normalized === \"sayas\") return \"say-as\";\n return normalized;\n}\n\nfunction validateVoiceFeatureMatrix(\n token: ElementToken,\n source: string,\n diagnostics: SsmlDiagnostic[],\n voiceName: string | undefined,\n definition: AzureVoiceDefinition | undefined,\n): void {\n if (!voiceName || !definition || token.name.toLowerCase() === \"voice\" || token.name.toLowerCase() === \"mstts:turn\")\n return;\n\n const tagName = canonicalTagName(token.name);\n const unsupportedTags = new Set((definition.unsupportedTags ?? []).map(canonicalTagName));\n const supportedTags = definition.supportedTags?.map(canonicalTagName);\n if (unsupportedTags.has(tagName) || (supportedTags !== undefined && !supportedTags.includes(tagName))) {\n addDiagnostic(\n diagnostics,\n source,\n token.start,\n `Tag <${token.name}> is not supported by voice \"${voiceName}\" according to the configured feature matrix.`,\n \"error\",\n \"azure-unsupported-tag-for-voice\",\n );\n }\n}\n\nfunction validateAudioSource(\n token: ElementToken,\n source: string,\n diagnostics: SsmlDiagnostic[],\n options: AzureValidationOptions,\n elementName: \"audio\" | \"mstts:backgroundaudio\",\n): void {\n const src = attr(token, \"src\");\n if (!src) {\n addDiagnostic(diagnostics, source, token.start, `<${elementName}> requires a \"src\" attribute.`);\n return;\n }\n\n let parsed: URL;\n try {\n parsed = new URL(src);\n } catch {\n addDiagnostic(diagnostics, source, token.start, `<${elementName} src> must be an absolute HTTP(S) URL.`);\n return;\n }\n if (parsed.username || parsed.password)\n addDiagnostic(diagnostics, source, token.start, `<${elementName} src> must not contain URL credentials.`);\n if (parsed.protocol !== \"https:\" && !(options.allowHttpAudio && parsed.protocol === \"http:\"))\n addDiagnostic(diagnostics, source, token.start, `<${elementName} src> must use HTTPS.`);\n const isAllowedOrigin =\n options.allowedAudioOrigins?.some((allowedOrigin) => {\n try {\n const configured = new URL(allowedOrigin);\n if (\n (configured.protocol !== \"https:\" && configured.protocol !== \"http:\") ||\n configured.username ||\n configured.password ||\n configured.pathname !== \"/\" ||\n configured.search ||\n configured.hash\n )\n return false;\n return configured.origin === parsed.origin;\n } catch {\n return false;\n }\n }) ?? false;\n if (options.allowedAudioOrigins && !isAllowedOrigin)\n addDiagnostic(diagnostics, source, token.start, `<${elementName} src> origin \"${parsed.origin}\" is not allowed.`);\n else if (!isAllowedOrigin && !options.allowExternalAudio)\n addDiagnostic(\n diagnostics,\n source,\n token.start,\n `<${elementName} src> external origin \"${parsed.origin}\" is blocked by default; set allowExternalAudio to true or provide allowedAudioOrigins.`,\n );\n}\n\nfunction validateElement(\n token: ElementToken,\n source: string,\n diagnostics: SsmlDiagnostic[],\n voiceName: string | undefined,\n options: AzureValidationOptions,\n voiceCatalog: ReadonlyMap<string, AzureVoiceDefinition>,\n): void {\n const name = token.name.toLowerCase();\n const tagStatus = featureStatusForTag(token.name, options);\n if (tagStatus === \"preview\")\n addDiagnostic(\n diagnostics,\n source,\n token.start,\n `<${token.name}> is an Azure Speech preview feature and may change or require preview access.`,\n \"warning\",\n \"azure-preview-tag\",\n );\n if (tagStatus === \"deprecated\")\n addDiagnostic(\n diagnostics,\n source,\n token.start,\n `<${token.name}> is deprecated by Azure Speech; migrate to a supported alternative.`,\n \"info\",\n \"azure-deprecated-tag\",\n );\n if (name === \"voice\" && !attr(token, \"name\")?.trim())\n addDiagnostic(diagnostics, source, token.start, '<voice> requires a non-empty \"name\" attribute.');\n if (name === \"break\") {\n const time = attr(token, \"time\");\n const strength = attr(token, \"strength\");\n if (!time && !strength)\n addDiagnostic(diagnostics, source, token.start, '<break> requires either \"time\" or \"strength\".');\n if (time && strength)\n addDiagnostic(diagnostics, source, token.start, '<break> must not specify both \"time\" and \"strength\".');\n if (time && !/^\\d+(?:\\.\\d+)?(?:ms|s)$/.test(time.trim()))\n addDiagnostic(diagnostics, source, token.start, '<break time> must use a numeric value followed by \"ms\" or \"s\".');\n if (strength && !ALLOWED_BREAK_STRENGTHS.has(strength))\n addDiagnostic(diagnostics, source, token.start, `Unsupported <break strength> value \"${strength}\".`);\n }\n if (name === \"prosody\") {\n const rate = attr(token, \"rate\");\n const pitch = attr(token, \"pitch\");\n const volume = attr(token, \"volume\");\n if (rate && !isSupportedProsodyRate(rate))\n addDiagnostic(diagnostics, source, token.start, `Unsupported <prosody rate> value \"${rate}\".`);\n if (pitch && !/^(x-low|low|medium|high|x-high|[+-]?\\d+(?:\\.\\d+)?(?:st|Hz|%)?)$/.test(pitch.trim()))\n addDiagnostic(diagnostics, source, token.start, `Unsupported <prosody pitch> value \"${pitch}\".`);\n if (volume && !/^(silent|x-soft|soft|medium|loud|x-loud|[+-]?\\d+(?:\\.\\d+)?(?:dB|%)?)$/.test(volume.trim()))\n addDiagnostic(diagnostics, source, token.start, `Unsupported <prosody volume> value \"${volume}\".`);\n }\n if (name === \"mstts:express-as\" || name === \"express-as\" || name === \"expressas\") {\n const style = attr(token, \"style\");\n if (!style?.trim())\n addDiagnostic(diagnostics, source, token.start, '<mstts:express-as> requires a non-empty \"style\" attribute.');\n const degree = attr(token, \"styledegree\") ?? attr(token, \"style-degree\");\n if (degree && (!/^\\d+(?:\\.\\d+)?$/.test(degree) || Number(degree) < 0.01 || Number(degree) > 2))\n addDiagnostic(\n diagnostics,\n source,\n token.start,\n \"<mstts:express-as styledegree> must be a number between 0.01 and 2.\",\n );\n const role = attr(token, \"role\");\n if (role && !ALLOWED_ROLES.has(role))\n addDiagnostic(diagnostics, source, token.start, `Unsupported <mstts:express-as role> value \"${role}\".`);\n const definition = voiceName ? voiceCatalog.get(voiceName.toLowerCase()) : undefined;\n const supportedStyles = definition?.styles;\n const severity = diagnosticSeverity(options.unsupportedStylePolicy ?? options.unknownVoicePolicy ?? \"warn\");\n if (\n style &&\n definition &&\n !supportedStyles?.some((candidate) => candidate.toLowerCase() === style.toLowerCase()) &&\n severity\n )\n addDiagnostic(\n diagnostics,\n source,\n token.start,\n `Unknown style \"${style}\" is not supported by voice \"${voiceName}\" according to the configured voice style map.`,\n severity,\n \"azure-unsupported-style\",\n );\n if (style && voiceName && !definition && severity)\n addDiagnostic(\n diagnostics,\n source,\n token.start,\n `Unknown style \"${style}\" cannot be verified because voice \"${voiceName}\" is not registered in the voice style map.`,\n severity,\n );\n }\n if (name === \"say-as\" || name === \"sayas\") {\n const interpretAs = attr(token, \"interpret-as\");\n if (!interpretAs || !ALLOWED_SAY_AS.has(interpretAs))\n addDiagnostic(diagnostics, source, token.start, `<say-as> requires a supported \"interpret-as\" value.`);\n }\n if (name === \"phoneme\" && (!attr(token, \"alphabet\") || !attr(token, \"ph\")))\n addDiagnostic(diagnostics, source, token.start, '<phoneme> requires both \"alphabet\" and \"ph\" attributes.');\n if (name === \"emphasis\" && attr(token, \"level\") && !ALLOWED_EMPHASIS_LEVELS.has(attr(token, \"level\") ?? \"\"))\n addDiagnostic(diagnostics, source, token.start, `Unsupported <emphasis level> value \"${attr(token, \"level\")}\".`);\n if (name === \"sub\" && !attr(token, \"alias\")?.trim())\n addDiagnostic(diagnostics, source, token.start, '<sub> requires a non-empty \"alias\" attribute.');\n if (name === \"lang\" && !attr(token, \"xml:lang\")?.trim() && !attr(token, \"lang\")?.trim())\n addDiagnostic(diagnostics, source, token.start, '<lang> requires an \"xml:lang\" attribute.');\n if (name === \"mark\" && !attr(token, \"name\")?.trim())\n addDiagnostic(diagnostics, source, token.start, '<mark> requires a non-empty \"name\" attribute.');\n if (name === \"bookmark\" && !attr(token, \"mark\")?.trim())\n addDiagnostic(diagnostics, source, token.start, '<bookmark> requires a non-empty \"mark\" attribute.');\n if (name === \"lexicon\") {\n const uri = attr(token, \"uri\");\n if (!uri) addDiagnostic(diagnostics, source, token.start, '<lexicon> requires a \"uri\" attribute.');\n else {\n try {\n const parsed = new URL(uri);\n if (parsed.protocol !== \"https:\")\n addDiagnostic(diagnostics, source, token.start, \"<lexicon uri> must use HTTPS.\");\n } catch {\n addDiagnostic(diagnostics, source, token.start, \"<lexicon uri> must be an absolute HTTPS URL.\");\n }\n }\n }\n if (name === \"mstts:silence\") {\n const type = attr(token, \"type\");\n const value = attr(token, \"value\");\n if (!type || !ALLOWED_SILENCE_TYPES.has(type))\n addDiagnostic(diagnostics, source, token.start, '<mstts:silence> requires a supported \"type\" attribute.');\n if (!value || !/^\\d+(?:\\.\\d+)?(?:ms|s)$/.test(value.trim()))\n addDiagnostic(diagnostics, source, token.start, '<mstts:silence> requires a time-valued \"value\" attribute.');\n }\n if (name === \"mstts:audioduration\") {\n const value = attr(token, \"value\");\n if (!value || !isValidAzureAudioDuration(value))\n addDiagnostic(\n diagnostics,\n source,\n token.start,\n '<mstts:audioduration> requires a positive duration such as \"10s\", \"5000ms\", or \"00:00:10\".',\n );\n if (!token.selfClosing)\n addDiagnostic(diagnostics, source, token.start, \"<mstts:audioduration> must be self-closing.\");\n }\n if (name === \"mstts:viseme\") {\n const type = attr(token, \"type\");\n if (!type || !ALLOWED_VISEME_TYPES.has(type))\n addDiagnostic(diagnostics, source, token.start, '<mstts:viseme> requires a supported \"type\" attribute.');\n }\n if (name === \"audio\") {\n validateAudioSource(token, source, diagnostics, options, \"audio\");\n }\n if (name === \"mstts:turn\") {\n if (!attr(token, \"voice\")?.trim() && !attr(token, \"speaker\")?.trim())\n addDiagnostic(\n diagnostics,\n source,\n token.start,\n '<mstts:turn> requires a non-empty \"voice\" or \"speaker\" attribute.',\n );\n if (token.parentName?.toLowerCase() !== \"mstts:dialog\")\n addDiagnostic(diagnostics, source, token.start, \"<mstts:turn> is only allowed directly inside <mstts:dialog>.\");\n }\n if (name === \"mstts:backgroundaudio\") {\n validateAudioSource(token, source, diagnostics, options, \"mstts:backgroundaudio\");\n const volume = attr(token, \"volume\");\n if (volume !== undefined && (!/^\\d+(?:\\.\\d+)?$/.test(volume.trim()) || Number(volume) > 100))\n addDiagnostic(diagnostics, source, token.start, `Unsupported <mstts:backgroundaudio volume> value \"${volume}\".`);\n for (const [attribute, value] of [\n [\"fadein\", attr(token, \"fadein\")],\n [\"fadeout\", attr(token, \"fadeout\")],\n ] as const) {\n if (value !== undefined && !isValidAzureBackgroundAudioDuration(value))\n addDiagnostic(\n diagnostics,\n source,\n token.start,\n `<mstts:backgroundaudio ${attribute}> must be between 0 and 10000 milliseconds, for example \"500ms\" or \"10s\".`,\n );\n }\n if (token.parentName?.toLowerCase() !== \"speak\" || token.childElementIndex !== 0)\n addDiagnostic(\n diagnostics,\n source,\n token.start,\n \"<mstts:backgroundaudio> must be the first element directly under <speak>.\",\n );\n if (!token.selfClosing)\n addDiagnostic(diagnostics, source, token.start, \"<mstts:backgroundaudio> must be self-closing.\");\n }\n}\n\nfunction validateAzureSsmlStatic(ssml: string, options: AzureValidationOptions = {}): SsmlDiagnostic[] {\n const diagnostics: SsmlDiagnostic[] = [];\n if (typeof ssml !== \"string\") {\n return [\n {\n line: 1,\n column: 1,\n message: \"SSML input must be a string\",\n severity: \"error\",\n source: \"ssml-static-validator\",\n },\n ];\n }\n const maxLength = options.maxLength ?? 10_000;\n if (ssml.length > maxLength)\n addDiagnostic(diagnostics, ssml, maxLength, `SSML exceeds the maximum length of ${maxLength} characters.`);\n if (options.maxXmlDepth !== undefined && (!Number.isInteger(options.maxXmlDepth) || options.maxXmlDepth <= 0)) {\n addDiagnostic(diagnostics, ssml, 0, \"maxXmlDepth must be a positive integer.\");\n }\n try {\n parseSsml(ssml);\n } catch (error) {\n const message = error instanceof Error ? error.message.replace(/ at position \\d+$/, \"\") : String(error);\n const match = / at position (\\d+)$/.exec(error instanceof Error ? error.message : \"\");\n addDiagnostic(diagnostics, ssml, match ? Number(match[1]) : 0, message);\n return diagnostics;\n }\n const tokens = tokenizeElements(ssml);\n if (options.maxXmlDepth !== undefined) {\n for (const token of tokens) {\n if (token.depth > options.maxXmlDepth) {\n addDiagnostic(\n diagnostics,\n ssml,\n token.start,\n `XML nesting depth ${token.depth} exceeds the configured maximum of ${options.maxXmlDepth}.`,\n );\n }\n }\n }\n const speak = tokens.find((token) => token.name.toLowerCase() === \"speak\");\n const voices = tokens.filter((token) => token.name.toLowerCase() === \"voice\");\n const backgroundAudioTokens = tokens.filter((token) => token.name.toLowerCase() === \"mstts:backgroundaudio\");\n for (const [index, token] of backgroundAudioTokens.entries()) {\n if (index > 0)\n addDiagnostic(\n diagnostics,\n ssml,\n token.start,\n \"An SSML document can contain at most one <mstts:backgroundaudio> element.\",\n );\n }\n if (!speak || voices.length === 0)\n addDiagnostic(\n diagnostics,\n ssml,\n speak?.start ?? 0,\n \"Azure SSML requires at least one <voice> element under <speak>.\",\n );\n const voiceName = voices[0] ? attr(voices[0], \"name\") : undefined;\n const voiceCatalog = normalizeVoiceCatalog(options);\n const normalizeLanguage = createLanguageNormalizer(options);\n const policySeverity = diagnosticSeverity(options.unknownVoicePolicy ?? \"warn\");\n const voicesToValidate = options.validateNestedVoices === false ? voices.slice(0, 1) : voices;\n for (const token of voicesToValidate) {\n const name = attr(token, \"name\")?.trim();\n const language = attr(token, \"xml:lang\")?.trim() || (speak ? attr(speak, \"xml:lang\")?.trim() : undefined);\n const definition = name ? voiceCatalog.get(name.toLowerCase()) : undefined;\n if (name && definition?.status === \"preview\")\n addDiagnostic(\n diagnostics,\n ssml,\n token.start,\n `Voice \"${name}\" is an Azure Speech preview voice and may change or require preview access.`,\n \"warning\",\n \"azure-preview-voice\",\n );\n if (name && definition?.status === \"deprecated\")\n addDiagnostic(\n diagnostics,\n ssml,\n token.start,\n `Voice \"${name}\" is deprecated by Azure Speech; migrate to a supported voice.`,\n \"info\",\n \"azure-deprecated-voice\",\n );\n if (name && !definition && policySeverity)\n addDiagnostic(\n diagnostics,\n ssml,\n token.start,\n `Unknown voice \"${name}\" is not registered in the voice catalog.`,\n policySeverity,\n \"azure-unknown-voice\",\n );\n if (name && language && definitionMatchesLanguage(definition, name, language, normalizeLanguage) === false)\n addDiagnostic(\n diagnostics,\n ssml,\n token.start,\n `Voice \"${name}\" does not match language \"${language}\"; the voice name prefix indicates a different language or region.`,\n \"warning\",\n \"azure-locale-mismatch\",\n );\n }\n for (const token of tokens) {\n const tokenName = token.name.toLowerCase();\n const tokenVoiceName =\n tokenName === \"voice\"\n ? attr(token, \"name\")?.trim()\n : tokenName === \"mstts:turn\"\n ? attr(token, \"voice\")?.trim() || token.parentVoiceName\n : options.validateNestedVoices === false\n ? voiceName\n : token.parentVoiceName;\n const tokenDiagnosticStart = diagnostics.length;\n validateElement(token, ssml, diagnostics, tokenVoiceName, options, voiceCatalog);\n const definition = tokenVoiceName ? voiceCatalog.get(tokenVoiceName.toLowerCase()) : undefined;\n validateVoiceFeatureMatrix(token, ssml, diagnostics, tokenVoiceName, definition);\n annotateTokenDiagnostics(diagnostics, tokenDiagnosticStart, token, options, tokenVoiceName);\n if (\n tokenName === \"voice\" &&\n options.model &&\n definition?.models &&\n !definition.models.some((model) => model.toLowerCase() === options.model?.toLowerCase())\n ) {\n addDiagnostic(\n diagnostics,\n ssml,\n token.start,\n `Voice \"${tokenVoiceName}\" does not support model \"${options.model}\" according to the configured feature matrix.`,\n \"error\",\n \"azure-unsupported-model-for-voice\",\n );\n }\n }\n return diagnostics;\n}\n\nfunction urlAttributes(token: ElementToken): Array<{ attribute: string; value: string }> {\n const tag = canonicalTagName(token.name);\n const attributes =\n tag === \"audio\" || tag === \"mstts:backgroundaudio\"\n ? [\"src\"]\n : tag === \"lexicon\"\n ? [\"uri\"]\n : tag === \"mstts:voiceconversion\"\n ? [\"url\"]\n : [];\n return attributes.flatMap((attribute) => {\n const value = attr(token, attribute);\n return value === undefined ? [] : [{ attribute, value }];\n });\n}\n\nfunction annotateTokenDiagnostics(\n diagnostics: SsmlDiagnostic[],\n startIndex: number,\n token: ElementToken,\n options: AzureValidationOptions,\n voiceName?: string,\n): void {\n const attributes = [...token.attributes.keys()];\n for (const diagnostic of diagnostics.slice(startIndex)) {\n const attributeName = attributes.find((attribute) =>\n new RegExp(`(?:<[^> ]+\\\\s+|\")${attribute}(?:\"|>|\\\\s)`, \"i\").test(diagnostic.message),\n );\n const nodePath = options.sourceNodePath ? [...options.sourceNodePath] : [...token.path];\n Object.assign(diagnostic, {\n range: { start: token.start, end: token.end + 1 },\n tagName: token.name,\n ...(attributeName ? { attributeName } : {}),\n ...(voiceName ? { voiceName } : {}),\n ...(options.chunkIndex !== undefined ? { chunkIndex: options.chunkIndex } : {}),\n nodePath,\n targetNodePath: [...token.path],\n });\n }\n}\n\n/**\n * Validates Azure SSML synchronously unless a URL validator is supplied. URL\n * validation is asynchronous-capable so hosts can perform DNS/private-network checks.\n */\nexport function validateAzureSsml(\n ssml: string,\n options?: Omit<AzureValidationOptions, \"urlValidator\" | \"customUrlValidator\">,\n): SsmlDiagnostic[];\nexport function validateAzureSsml(\n ssml: string,\n options: AzureValidationOptions & { urlValidator?: AzureUrlValidator; customUrlValidator?: AzureUrlValidator },\n): SsmlDiagnostic[] | Promise<SsmlDiagnostic[]>;\nexport function validateAzureSsml(\n ssml: string,\n options: AzureValidationOptions = {},\n): SsmlDiagnostic[] | Promise<SsmlDiagnostic[]> {\n const diagnostics = validateAzureSsmlStatic(ssml, options);\n const validator = options.urlValidator ?? options.customUrlValidator;\n if (!validator || typeof ssml !== \"string\") return diagnostics;\n const runnerOptions = options.urlValidation ?? {};\n const boundedValidator =\n options.urlValidatorRunner ??\n createAzureUrlValidatorRunner(validator, {\n ...runnerOptions,\n ...(options.urlValidatorConcurrency !== undefined ? { concurrency: options.urlValidatorConcurrency } : {}),\n ...(options.urlValidatorTimeoutMs !== undefined ? { timeoutMs: options.urlValidatorTimeoutMs } : {}),\n ...(options.urlValidatorSignal ? { signal: options.urlValidatorSignal } : {}),\n ...(options.urlValidatorCache ? { cache: options.urlValidatorCache } : {}),\n });\n const validationSignal = options.urlValidatorSignal ?? options.urlValidation?.signal ?? new AbortController().signal;\n\n let tokens: ElementToken[];\n try {\n tokens = tokenizeElements(ssml);\n } catch {\n return diagnostics;\n }\n const checks = tokens.flatMap((token) =>\n urlAttributes(token).map(async ({ attribute, value }) => {\n try {\n const result = await boundedValidator(\n value,\n { tag: token.name, attribute, ...(options.sourceNodePath ? { sourceNodePath: options.sourceNodePath } : {}) },\n validationSignal,\n );\n const valid = typeof result === \"boolean\" ? result : result.valid;\n if (!valid) {\n const reason = typeof result === \"boolean\" ? undefined : result.reason;\n const diagnosticStart = diagnostics.length;\n addDiagnostic(\n diagnostics,\n ssml,\n token.start,\n `<${token.name} ${attribute}> was rejected by the custom URL validator${reason ? `: ${reason}` : \".\"}`,\n );\n annotateTokenDiagnostics(diagnostics, diagnosticStart, token, options, token.parentVoiceName);\n }\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n const diagnosticStart = diagnostics.length;\n addDiagnostic(\n diagnostics,\n ssml,\n token.start,\n `<${token.name} ${attribute}> could not be validated by the custom URL validator: ${reason}`,\n );\n annotateTokenDiagnostics(diagnostics, diagnosticStart, token, options, token.parentVoiceName);\n }\n }),\n );\n return Promise.all(checks).then(() => diagnostics);\n}\n\n/** Validates multiple SSML chunks with one shared URL cache, semaphore, and in-flight pool. */\nexport async function validateAzureSsmlChunks(\n chunks: readonly string[],\n options: AzureValidationOptions = {},\n): Promise<SsmlDiagnostic[][]> {\n const validator = options.urlValidator ?? options.customUrlValidator;\n const sharedOptions = validator\n ? {\n ...options,\n urlValidatorRunner:\n options.urlValidatorRunner ??\n createAzureUrlValidatorRunner(validator, {\n ...(options.urlValidation ?? {}),\n ...(options.urlValidatorConcurrency !== undefined ? { concurrency: options.urlValidatorConcurrency } : {}),\n ...(options.urlValidatorTimeoutMs !== undefined ? { timeoutMs: options.urlValidatorTimeoutMs } : {}),\n ...(options.urlValidatorSignal ? { signal: options.urlValidatorSignal } : {}),\n ...(options.urlValidatorCache ? { cache: options.urlValidatorCache } : {}),\n }),\n }\n : options;\n return Promise.all(\n chunks.map((chunk, chunkIndex) => Promise.resolve(validateAzureSsml(chunk, { ...sharedOptions, chunkIndex }))),\n );\n}\n","/** Generated by scripts/sync-azure-voices.ts. */\nimport { AZURE_VOICE_DEFINITIONS } from \"./azureVoiceDefinitions.ts\";\n\nexport interface AzureVoiceCatalogMetadata {\n apiVersion: string;\n generatedAt: string;\n regions: readonly string[];\n voiceCount: number;\n}\n\nexport const AZURE_VOICE_CATALOG_METADATA: AzureVoiceCatalogMetadata = {\n apiVersion: \"2025-10-01\",\n generatedAt: \"2026-08-28T00:00:00.000Z\",\n regions: [],\n voiceCount: AZURE_VOICE_DEFINITIONS.length,\n};\n","import { AZURE_VOICE_CATALOG_METADATA } from \"./generated/azureVoiceCatalog.ts\";\nimport type { AzureVoiceCatalogMetadata } from \"./generated/azureVoiceCatalog.ts\";\n\n/** Returns metadata for the built-in Azure voice catalog snapshot. */\nexport function getAzureVoiceCatalogMetadata(): AzureVoiceCatalogMetadata {\n return {\n ...AZURE_VOICE_CATALOG_METADATA,\n regions: [...AZURE_VOICE_CATALOG_METADATA.regions],\n };\n}\n\n/** Alias for consumers that refer to the bundled catalog as the built-in catalog. */\nexport const getBuiltInVoiceCatalogMetadata = getAzureVoiceCatalogMetadata;\n"],"mappings":";;;;;;;;AAAO,IAAM,sBAAsB;AAC5B,IAAM,kBAAkB;AACxB,IAAM,uBAAuB;AAC7B,IAAM,wBAAwB;AAC9B,IAAM,oBAAoB;AAC1B,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AAEzB,IAAM,YAAY;EACvB,OAAO;EACP,OAAO;EACP,SAAS;EACT,OAAO;EACP,YAAY;EACZ,kBAAkB;EAClB,kBAAkB;EAClB,QAAQ;EACR,cAAc;EACd,SAAS;EACT,UAAU;EACV,OAAO;EACP,KAAK;EACL,MAAM;EACN,MAAM;EACN,UAAU;EACV,SAAS;EACT,WAAW;EACX,UAAU;EACV,MAAM;EACN,eAAe;EACf,SAAS;EACT,cAAc;EACd,QAAQ;EACR,sBAAsB;EACtB,cAAc;EACd,YAAY;EACZ,wBAAwB;EACxB,qBAAqB;EACrB,iBAAiB;EACjB,wBAAwB;AAC1B;AAEO,IAAM,aA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