ssml-builder-js 2.3.0 → 2.5.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.
@@ -848,10 +848,559 @@ function validateSsml(xmlString) {
848
848
  }
849
849
  }
850
850
 
851
+ // packages/ssml-core/src/textNodes.ts
852
+ function decodeXmlText(value) {
853
+ return value.replace(/&(?:amp|apos|gt|lt|quot);|&#(?:x[\da-f]+|\d+);/gi, (entity) => {
854
+ if (entity === "&") return "&";
855
+ if (entity === "'") return "'";
856
+ if (entity === ">") return ">";
857
+ if (entity === "&lt;") return "<";
858
+ if (entity === "&quot;") return '"';
859
+ const hexadecimal = entity.toLowerCase().startsWith("&#x");
860
+ const digits = entity.slice(hexadecimal ? 3 : 2, -1);
861
+ return String.fromCodePoint(Number.parseInt(digits, hexadecimal ? 16 : 10));
862
+ });
863
+ }
864
+ function encodeXmlText(value) {
865
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
866
+ }
867
+ function decodeXmlAttribute(value) {
868
+ return decodeXmlText(value);
869
+ }
870
+ function findTagEnd(source, start) {
871
+ let quote = "";
872
+ for (let index = start; index < source.length; index += 1) {
873
+ const character = source[index];
874
+ if (quote) {
875
+ if (character === quote) quote = "";
876
+ } else if (character === '"' || character === "'") {
877
+ quote = character;
878
+ } else if (character === ">") {
879
+ return index;
880
+ }
881
+ }
882
+ return source.length - 1;
883
+ }
884
+ function readTagName(tag) {
885
+ const match = /^<\s*([A-Za-z_][A-Za-z0-9_.:-]*)/.exec(tag);
886
+ return match?.[1];
887
+ }
888
+ function readTagAttributes(tag, name) {
889
+ const attributes = {};
890
+ const nameStart = tag.indexOf(name);
891
+ const attributeSource = tag.slice(nameStart + name.length, tag.length - 1).replace(/\/\s*$/, "");
892
+ const attributePattern = /([A-Za-z_][A-Za-z0-9_.:-]*)\s*=\s*(["'])([\s\S]*?)\2/g;
893
+ for (const match of attributeSource.matchAll(attributePattern)) {
894
+ attributes[match[1].toLowerCase()] = decodeXmlAttribute(match[3]);
895
+ }
896
+ return attributes;
897
+ }
898
+ function collectTextNodes(source) {
899
+ const nodes = [];
900
+ const elements = [];
901
+ let index = 0;
902
+ const addText = (start, end, rawText, sourceStart = start, sourceEnd = end) => {
903
+ if (!rawText) return;
904
+ const path = elements.map((element) => element.name);
905
+ const parent = elements[elements.length - 1];
906
+ nodes.push({
907
+ context: {
908
+ ancestorTags: path.slice(0, -1),
909
+ parentAttributes: { ...parent?.attributes ?? {} },
910
+ parentTag: parent?.name ?? "",
911
+ path
912
+ },
913
+ decodedText: decodeXmlText(rawText),
914
+ end,
915
+ sourceEnd,
916
+ sourceStart,
917
+ start
918
+ });
919
+ };
920
+ while (index < source.length) {
921
+ if (source[index] !== "<") {
922
+ const nextTag = source.indexOf("<", index);
923
+ const end2 = nextTag === -1 ? source.length : nextTag;
924
+ addText(index, end2, source.slice(index, end2));
925
+ index = end2;
926
+ continue;
927
+ }
928
+ if (source.startsWith("<!--", index)) {
929
+ const end2 = source.indexOf("-->", index + 4);
930
+ index = end2 === -1 ? source.length : end2 + 3;
931
+ continue;
932
+ }
933
+ if (source.startsWith("<![CDATA[", index)) {
934
+ const contentStart = index + 9;
935
+ const end2 = source.indexOf("]]>", contentStart);
936
+ const contentEnd = end2 === -1 ? source.length : end2;
937
+ addText(
938
+ contentStart,
939
+ contentEnd,
940
+ source.slice(contentStart, contentEnd),
941
+ index,
942
+ end2 === -1 ? source.length : end2 + 3
943
+ );
944
+ index = end2 === -1 ? source.length : end2 + 3;
945
+ continue;
946
+ }
947
+ if (source.startsWith("<?", index)) {
948
+ const end2 = source.indexOf("?>", index + 2);
949
+ index = end2 === -1 ? source.length : end2 + 2;
950
+ continue;
951
+ }
952
+ if (source.startsWith("</", index)) {
953
+ const end2 = findTagEnd(source, index + 2);
954
+ elements.pop();
955
+ index = end2 + 1;
956
+ continue;
957
+ }
958
+ const end = findTagEnd(source, index + 1);
959
+ const tag = source.slice(index, end + 1);
960
+ const name = readTagName(tag);
961
+ if (name && !/\/\s*>$/.test(tag)) elements.push({ attributes: readTagAttributes(tag, name), name });
962
+ index = end + 1;
963
+ }
964
+ return nodes;
965
+ }
966
+ function extractSsmlText(ssml) {
967
+ parseSsml(ssml);
968
+ return collectTextNodes(ssml).map((node) => node.decodedText);
969
+ }
970
+ async function mapSsmlTextNodes(ssml, transform, options = {}) {
971
+ parseSsml(ssml);
972
+ const nodes = collectTextNodes(ssml);
973
+ const skipTags = new Set((options.skipTags ?? ["phoneme", "say-as", "sub"]).map((tag) => tag.toLowerCase()));
974
+ const replacements = await Promise.all(
975
+ nodes.map(async (node) => {
976
+ const context = {
977
+ ancestorTags: [...node.context.ancestorTags],
978
+ parentAttributes: { ...node.context.parentAttributes },
979
+ parentTag: node.context.parentTag,
980
+ path: [...node.context.path]
981
+ };
982
+ const shouldTransform = !skipTags.has(context.parentTag.toLowerCase()) && (options.filter?.(context) ?? true);
983
+ if (!shouldTransform) return ssml.slice(node.sourceStart, node.sourceEnd);
984
+ const transformed = await transform(node.decodedText, context);
985
+ if (typeof transformed !== "string") {
986
+ throw new TypeError("SSML text node transform must return a string");
987
+ }
988
+ return transformed === node.decodedText ? ssml.slice(node.sourceStart, node.sourceEnd) : encodeXmlText(transformed);
989
+ })
990
+ );
991
+ let result = "";
992
+ let cursor = 0;
993
+ nodes.forEach((node, nodeIndex) => {
994
+ result += ssml.slice(cursor, node.sourceStart) + replacements[nodeIndex];
995
+ cursor = node.sourceEnd;
996
+ });
997
+ return result + ssml.slice(cursor);
998
+ }
999
+
1000
+ // packages/ssml-core/src/azureValidation.ts
1001
+ var EXPRESS_AS_STYLES = {
1002
+ "en-us-jennyneural": [
1003
+ "assistant",
1004
+ "chat",
1005
+ "customerservice",
1006
+ "newscast",
1007
+ "cheerful",
1008
+ "empathetic",
1009
+ "excited",
1010
+ "friendly",
1011
+ "hopeful",
1012
+ "sad",
1013
+ "shouting",
1014
+ "terrified",
1015
+ "unfriendly",
1016
+ "whispering"
1017
+ ],
1018
+ "en-us-guyneural": [
1019
+ "angry",
1020
+ "cheerful",
1021
+ "excited",
1022
+ "friendly",
1023
+ "hopeful",
1024
+ "newscast",
1025
+ "sad",
1026
+ "shouting",
1027
+ "terrified",
1028
+ "unfriendly",
1029
+ "whispering"
1030
+ ],
1031
+ "en-us-jennymultilingualneural": [
1032
+ "cheerful",
1033
+ "empathetic",
1034
+ "excited",
1035
+ "friendly",
1036
+ "hopeful",
1037
+ "sad",
1038
+ "shouting",
1039
+ "terrified",
1040
+ "unfriendly",
1041
+ "whispering"
1042
+ ],
1043
+ "en-us-andrewneural": ["empathetic", "relieved"],
1044
+ "ja-jp-mayuneural": ["calm", "cheerful", "sad"],
1045
+ "ja-jp-nanamineural": ["chat", "customerservice", "cheerful", "whispering", "sad"],
1046
+ "ja-jp-keitaneural": ["chat"],
1047
+ "ko-kr-sunhineural": ["cheerful", "sad"],
1048
+ "zh-cn-yunxineural": [
1049
+ "narration-relaxed",
1050
+ "embarrassed",
1051
+ "fearful",
1052
+ "sad",
1053
+ "disgruntled",
1054
+ "serious",
1055
+ "angry",
1056
+ "depressed",
1057
+ "chat",
1058
+ "cheerful",
1059
+ "assistant"
1060
+ ],
1061
+ "zh-cn-xiaoxiaoneural": [
1062
+ "assistant",
1063
+ "chat",
1064
+ "customerservice",
1065
+ "newscast",
1066
+ "cheerful",
1067
+ "empathetic",
1068
+ "excited",
1069
+ "friendly",
1070
+ "hopeful",
1071
+ "sad",
1072
+ "terrified",
1073
+ "whispering",
1074
+ "poetry-reading",
1075
+ "sports_commentary",
1076
+ "sports_commentary_excited",
1077
+ "story"
1078
+ ],
1079
+ "fr-fr-deniseneural": ["cheerful", "sad"],
1080
+ "fr-fr-henrineural": ["cheerful", "sad"],
1081
+ "pt-br-franciscaneural": ["calm"],
1082
+ "it-it-elsaneural": ["cheerful", "sad"],
1083
+ "de-de-katjaneural": ["cheerful", "sad"],
1084
+ "de-de-conradneural": ["cheerful", "sad"],
1085
+ "ru-ru-svetlananeural": ["cheerful", "sad", "angry", "disgruntled", "embarrassed", "fearful"]
1086
+ };
1087
+ var ALLOWED_BREAK_STRENGTHS = /* @__PURE__ */ new Set(["none", "x-weak", "weak", "medium", "strong", "x-strong"]);
1088
+ var ALLOWED_SAY_AS = /* @__PURE__ */ new Set([
1089
+ "characters",
1090
+ "spell-out",
1091
+ "cardinal",
1092
+ "ordinal",
1093
+ "number",
1094
+ "date",
1095
+ "time",
1096
+ "telephone",
1097
+ "fraction",
1098
+ "address",
1099
+ "name",
1100
+ "currency"
1101
+ ]);
1102
+ var ALLOWED_ROLES = /* @__PURE__ */ new Set([
1103
+ "Girl",
1104
+ "Boy",
1105
+ "YoungAdultFemale",
1106
+ "YoungAdultMale",
1107
+ "OlderAdultFemale",
1108
+ "OlderAdultMale",
1109
+ "SeniorFemale",
1110
+ "SeniorMale"
1111
+ ]);
1112
+ var ALLOWED_EMPHASIS_LEVELS = /* @__PURE__ */ new Set(["strong", "moderate", "reduced", "none"]);
1113
+ var ALLOWED_SILENCE_TYPES = /* @__PURE__ */ new Set([
1114
+ "Leading",
1115
+ "Tailing",
1116
+ "Sentenceboundary",
1117
+ "Comma",
1118
+ "Semicolon",
1119
+ "Enumerationcomma"
1120
+ ]);
1121
+ var ALLOWED_VISEME_TYPES = /* @__PURE__ */ new Set(["redlips_front", "FacialExpression"]);
1122
+ function decodeAttribute(value) {
1123
+ return value.replace(
1124
+ /&(?:amp|apos|gt|lt|quot);/gi,
1125
+ (entity) => ({ "&amp;": "&", "&apos;": "'", "&gt;": ">", "&lt;": "<", "&quot;": '"' })[entity.toLowerCase()] ?? entity
1126
+ );
1127
+ }
1128
+ function findTagEnd2(source, start) {
1129
+ let quote = "";
1130
+ for (let index = start; index < source.length; index += 1) {
1131
+ const character = source[index];
1132
+ if (quote) {
1133
+ if (character === quote) quote = "";
1134
+ } else if (character === '"' || character === "'") quote = character;
1135
+ else if (character === ">") return index;
1136
+ }
1137
+ return source.length - 1;
1138
+ }
1139
+ function tokenizeElements(source) {
1140
+ const tokens = [];
1141
+ const openElements = [];
1142
+ let index = 0;
1143
+ while (index < source.length) {
1144
+ const start = source.indexOf("<", index);
1145
+ if (start === -1) break;
1146
+ if (source.startsWith("<!--", start)) {
1147
+ const end2 = source.indexOf("-->", start + 4);
1148
+ index = end2 === -1 ? source.length : end2 + 3;
1149
+ continue;
1150
+ }
1151
+ if (source.startsWith("<![CDATA[", start)) {
1152
+ const end2 = source.indexOf("]]>", start + 9);
1153
+ index = end2 === -1 ? source.length : end2 + 3;
1154
+ continue;
1155
+ }
1156
+ if (source.startsWith("<?", start)) {
1157
+ const end2 = source.indexOf("?>", start + 2);
1158
+ index = end2 === -1 ? source.length : end2 + 2;
1159
+ continue;
1160
+ }
1161
+ const end = findTagEnd2(source, start + 1);
1162
+ const raw = source.slice(start, end + 1);
1163
+ if (raw.startsWith("</")) {
1164
+ openElements.pop();
1165
+ index = end + 1;
1166
+ continue;
1167
+ }
1168
+ const nameMatch = /^<\s*([A-Za-z_][A-Za-z0-9_.:-]*)/.exec(raw);
1169
+ if (!nameMatch?.[1]) {
1170
+ index = end + 1;
1171
+ continue;
1172
+ }
1173
+ const attributes = /* @__PURE__ */ new Map();
1174
+ const attributeSource = raw.slice(nameMatch[0].length, raw.length - 1).replace(/\/\s*$/, "");
1175
+ const attributePattern = /([A-Za-z_][A-Za-z0-9_.:-]*)\s*=\s*(["'])([\s\S]*?)\2/g;
1176
+ for (const match of attributeSource.matchAll(attributePattern)) {
1177
+ attributes.set(match[1].toLowerCase(), decodeAttribute(match[3]));
1178
+ }
1179
+ const selfClosing = /\/\s*>$/.test(raw);
1180
+ const parentVoiceName = [...openElements].reverse().find((element) => element.voiceName)?.voiceName;
1181
+ tokens.push({ attributes, end, name: nameMatch[1], parentVoiceName, selfClosing, start });
1182
+ if (!selfClosing) {
1183
+ openElements.push({
1184
+ name: nameMatch[1],
1185
+ voiceName: nameMatch[1].toLowerCase() === "voice" ? attributes.get("name") : parentVoiceName
1186
+ });
1187
+ }
1188
+ index = end + 1;
1189
+ }
1190
+ return tokens;
1191
+ }
1192
+ function location(source, offset) {
1193
+ const before = source.slice(0, Math.max(0, offset));
1194
+ const line = before.split("\n").length;
1195
+ return { line, column: before.length - (before.lastIndexOf("\n") + 1) + 1 };
1196
+ }
1197
+ function addDiagnostic(diagnostics, source, offset, message, severity = "error") {
1198
+ diagnostics.push({ ...location(source, offset), message, severity });
1199
+ }
1200
+ function attr(token, name) {
1201
+ return token.attributes.get(name.toLowerCase());
1202
+ }
1203
+ function normalizeVoiceStyleMap(customVoiceStyleMap) {
1204
+ const map = new Map(
1205
+ Object.entries(EXPRESS_AS_STYLES).map(([voiceName, styles]) => [voiceName.toLowerCase(), styles])
1206
+ );
1207
+ for (const [voiceName, styles] of Object.entries(customVoiceStyleMap ?? {})) {
1208
+ map.set(
1209
+ voiceName.toLowerCase(),
1210
+ styles.map((style) => style.toLowerCase())
1211
+ );
1212
+ }
1213
+ return map;
1214
+ }
1215
+ function diagnosticSeverity(policy) {
1216
+ if (policy === "ignore") return void 0;
1217
+ return policy === "error" ? "error" : "warning";
1218
+ }
1219
+ function validateElement(token, source, diagnostics, voiceName, options, voiceStyleMap) {
1220
+ const name = token.name.toLowerCase();
1221
+ if (name === "voice" && !attr(token, "name")?.trim())
1222
+ addDiagnostic(diagnostics, source, token.start, '<voice> requires a non-empty "name" attribute.');
1223
+ if (name === "break") {
1224
+ const time = attr(token, "time");
1225
+ const strength = attr(token, "strength");
1226
+ if (!time && !strength)
1227
+ addDiagnostic(diagnostics, source, token.start, '<break> requires either "time" or "strength".');
1228
+ if (time && strength)
1229
+ addDiagnostic(diagnostics, source, token.start, '<break> must not specify both "time" and "strength".');
1230
+ if (time && !/^\d+(?:\.\d+)?(?:ms|s)$/.test(time.trim()))
1231
+ addDiagnostic(diagnostics, source, token.start, '<break time> must use a numeric value followed by "ms" or "s".');
1232
+ if (strength && !ALLOWED_BREAK_STRENGTHS.has(strength))
1233
+ addDiagnostic(diagnostics, source, token.start, `Unsupported <break strength> value "${strength}".`);
1234
+ }
1235
+ if (name === "prosody") {
1236
+ const rate = attr(token, "rate");
1237
+ const pitch = attr(token, "pitch");
1238
+ const volume = attr(token, "volume");
1239
+ if (rate && !/^(x-slow|slow|medium|fast|x-fast|[+-]?\d+(?:\.\d+)?%)$/.test(rate.trim()))
1240
+ addDiagnostic(diagnostics, source, token.start, `Unsupported <prosody rate> value "${rate}".`);
1241
+ if (pitch && !/^(x-low|low|medium|high|x-high|[+-]?\d+(?:\.\d+)?(?:st|Hz|%)?)$/.test(pitch.trim()))
1242
+ addDiagnostic(diagnostics, source, token.start, `Unsupported <prosody pitch> value "${pitch}".`);
1243
+ if (volume && !/^(silent|x-soft|soft|medium|loud|x-loud|[+-]?\d+(?:\.\d+)?(?:dB|%)?)$/.test(volume.trim()))
1244
+ addDiagnostic(diagnostics, source, token.start, `Unsupported <prosody volume> value "${volume}".`);
1245
+ }
1246
+ if (name === "mstts:express-as" || name === "express-as" || name === "expressas") {
1247
+ const style = attr(token, "style");
1248
+ if (!style?.trim())
1249
+ addDiagnostic(diagnostics, source, token.start, '<mstts:express-as> requires a non-empty "style" attribute.');
1250
+ const degree = attr(token, "styledegree") ?? attr(token, "style-degree");
1251
+ if (degree && (!/^\d+(?:\.\d+)?$/.test(degree) || Number(degree) < 0.01 || Number(degree) > 2))
1252
+ addDiagnostic(
1253
+ diagnostics,
1254
+ source,
1255
+ token.start,
1256
+ "<mstts:express-as styledegree> must be a number between 0.01 and 2."
1257
+ );
1258
+ const role = attr(token, "role");
1259
+ if (role && !ALLOWED_ROLES.has(role))
1260
+ addDiagnostic(diagnostics, source, token.start, `Unsupported <mstts:express-as role> value "${role}".`);
1261
+ const supportedStyles = voiceName ? voiceStyleMap.get(voiceName.toLowerCase()) : void 0;
1262
+ const severity = diagnosticSeverity(options.unknownVoicePolicy ?? "warn");
1263
+ if (style && supportedStyles && !supportedStyles.includes(style.toLowerCase()) && severity)
1264
+ addDiagnostic(
1265
+ diagnostics,
1266
+ source,
1267
+ token.start,
1268
+ `Unknown style "${style}" is not supported by voice "${voiceName}" according to the configured voice style map.`,
1269
+ severity
1270
+ );
1271
+ if (style && voiceName && !supportedStyles && severity)
1272
+ addDiagnostic(
1273
+ diagnostics,
1274
+ source,
1275
+ token.start,
1276
+ `Unknown style "${style}" cannot be verified because voice "${voiceName}" is not registered in the voice style map.`,
1277
+ severity
1278
+ );
1279
+ }
1280
+ if (name === "say-as" || name === "sayas") {
1281
+ const interpretAs = attr(token, "interpret-as");
1282
+ if (!interpretAs || !ALLOWED_SAY_AS.has(interpretAs))
1283
+ addDiagnostic(diagnostics, source, token.start, `<say-as> requires a supported "interpret-as" value.`);
1284
+ }
1285
+ if (name === "phoneme" && (!attr(token, "alphabet") || !attr(token, "ph")))
1286
+ addDiagnostic(diagnostics, source, token.start, '<phoneme> requires both "alphabet" and "ph" attributes.');
1287
+ if (name === "emphasis" && attr(token, "level") && !ALLOWED_EMPHASIS_LEVELS.has(attr(token, "level") ?? ""))
1288
+ addDiagnostic(diagnostics, source, token.start, `Unsupported <emphasis level> value "${attr(token, "level")}".`);
1289
+ if (name === "sub" && !attr(token, "alias")?.trim())
1290
+ addDiagnostic(diagnostics, source, token.start, '<sub> requires a non-empty "alias" attribute.');
1291
+ if (name === "lang" && !attr(token, "xml:lang")?.trim() && !attr(token, "lang")?.trim())
1292
+ addDiagnostic(diagnostics, source, token.start, '<lang> requires an "xml:lang" attribute.');
1293
+ if (name === "mark" && !attr(token, "name")?.trim())
1294
+ addDiagnostic(diagnostics, source, token.start, '<mark> requires a non-empty "name" attribute.');
1295
+ if (name === "bookmark" && !attr(token, "mark")?.trim())
1296
+ addDiagnostic(diagnostics, source, token.start, '<bookmark> requires a non-empty "mark" attribute.');
1297
+ if (name === "lexicon") {
1298
+ const uri = attr(token, "uri");
1299
+ if (!uri) addDiagnostic(diagnostics, source, token.start, '<lexicon> requires a "uri" attribute.');
1300
+ else {
1301
+ try {
1302
+ const parsed = new URL(uri);
1303
+ if (parsed.protocol !== "https:")
1304
+ addDiagnostic(diagnostics, source, token.start, "<lexicon uri> must use HTTPS.");
1305
+ } catch {
1306
+ addDiagnostic(diagnostics, source, token.start, "<lexicon uri> must be an absolute HTTPS URL.");
1307
+ }
1308
+ }
1309
+ }
1310
+ if (name === "mstts:silence") {
1311
+ const type = attr(token, "type");
1312
+ const value = attr(token, "value");
1313
+ if (!type || !ALLOWED_SILENCE_TYPES.has(type))
1314
+ addDiagnostic(diagnostics, source, token.start, '<mstts:silence> requires a supported "type" attribute.');
1315
+ if (!value || !/^\d+(?:\.\d+)?(?:ms|s)$/.test(value.trim()))
1316
+ addDiagnostic(diagnostics, source, token.start, '<mstts:silence> requires a time-valued "value" attribute.');
1317
+ }
1318
+ if (name === "mstts:viseme") {
1319
+ const type = attr(token, "type");
1320
+ if (!type || !ALLOWED_VISEME_TYPES.has(type))
1321
+ addDiagnostic(diagnostics, source, token.start, '<mstts:viseme> requires a supported "type" attribute.');
1322
+ }
1323
+ if (name === "audio") {
1324
+ const src = attr(token, "src");
1325
+ if (!src) addDiagnostic(diagnostics, source, token.start, '<audio> requires a "src" attribute.');
1326
+ else {
1327
+ let parsed;
1328
+ try {
1329
+ parsed = new URL(src);
1330
+ } catch {
1331
+ addDiagnostic(diagnostics, source, token.start, "<audio src> must be an absolute HTTP(S) URL.");
1332
+ return;
1333
+ }
1334
+ if (parsed.protocol !== "https:" && !(options.allowHttpAudio && parsed.protocol === "http:"))
1335
+ addDiagnostic(diagnostics, source, token.start, "<audio src> must use HTTPS.");
1336
+ if (options.allowedAudioOrigins && !options.allowedAudioOrigins.includes(parsed.origin))
1337
+ addDiagnostic(diagnostics, source, token.start, `<audio src> origin "${parsed.origin}" is not allowed.`);
1338
+ else if (!options.allowExternalAudio)
1339
+ addDiagnostic(
1340
+ diagnostics,
1341
+ source,
1342
+ token.start,
1343
+ `<audio src> external origin "${parsed.origin}" is blocked by default; set allowExternalAudio to true or provide allowedAudioOrigins.`,
1344
+ "error"
1345
+ );
1346
+ }
1347
+ }
1348
+ }
1349
+ function validateAzureSsml(ssml, options = {}) {
1350
+ const diagnostics = [];
1351
+ if (typeof ssml !== "string") {
1352
+ return [{ line: 1, column: 1, message: "SSML input must be a string", severity: "error" }];
1353
+ }
1354
+ const maxLength = options.maxLength ?? 1e4;
1355
+ if (ssml.length > maxLength)
1356
+ addDiagnostic(diagnostics, ssml, maxLength, `SSML exceeds the maximum length of ${maxLength} characters.`);
1357
+ try {
1358
+ parseSsml(ssml);
1359
+ } catch (error) {
1360
+ const message = error instanceof Error ? error.message.replace(/ at position \d+$/, "") : String(error);
1361
+ const match = / at position (\d+)$/.exec(error instanceof Error ? error.message : "");
1362
+ addDiagnostic(diagnostics, ssml, match ? Number(match[1]) : 0, message);
1363
+ return diagnostics;
1364
+ }
1365
+ const tokens = tokenizeElements(ssml);
1366
+ const speak = tokens.find((token) => token.name.toLowerCase() === "speak");
1367
+ const voices = tokens.filter((token) => token.name.toLowerCase() === "voice");
1368
+ if (!speak || voices.length === 0)
1369
+ addDiagnostic(
1370
+ diagnostics,
1371
+ ssml,
1372
+ speak?.start ?? 0,
1373
+ "Azure SSML requires at least one <voice> element under <speak>."
1374
+ );
1375
+ const voiceName = voices[0] ? attr(voices[0], "name") : void 0;
1376
+ const voiceStyleMap = normalizeVoiceStyleMap(options.customVoiceStyleMap);
1377
+ const policySeverity = diagnosticSeverity(options.unknownVoicePolicy ?? "warn");
1378
+ const voicesToValidate = options.validateNestedVoices === false ? voices.slice(0, 1) : voices;
1379
+ for (const token of voicesToValidate) {
1380
+ const name = attr(token, "name")?.trim();
1381
+ if (name && !voiceStyleMap.has(name.toLowerCase()) && policySeverity)
1382
+ addDiagnostic(
1383
+ diagnostics,
1384
+ ssml,
1385
+ token.start,
1386
+ `Unknown voice "${name}" is not registered in the voice style map.`,
1387
+ policySeverity
1388
+ );
1389
+ }
1390
+ for (const token of tokens) {
1391
+ const tokenVoiceName = options.validateNestedVoices === false ? voiceName : token.parentVoiceName;
1392
+ validateElement(token, ssml, diagnostics, tokenVoiceName, options, voiceStyleMap);
1393
+ }
1394
+ return diagnostics;
1395
+ }
1396
+
851
1397
  export {
852
1398
  buildSsml,
853
1399
  parseSsml,
854
1400
  buildPartialSsml,
855
- validateSsml
1401
+ validateSsml,
1402
+ extractSsmlText,
1403
+ mapSsmlTextNodes,
1404
+ validateAzureSsml
856
1405
  };
857
- //# sourceMappingURL=chunk-PSN6XAFF.mjs.map
1406
+ //# sourceMappingURL=chunk-4RHHW33A.mjs.map