ssml-builder-js 2.2.0 → 2.4.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.
@@ -56,6 +56,7 @@ var SSML_ATTRS = {
56
56
  STYLE: "style",
57
57
  STYLE_DEGREE: "styledegree",
58
58
  STYLE_DEGREE_CAMEL: "styleDegree",
59
+ STYLE_DEGREE_HYPHEN: "style-degree",
59
60
  ROLE: "role",
60
61
  INTERPRET_AS: "interpret-as",
61
62
  FORMAT: "format",
@@ -603,7 +604,12 @@ function convertElement(node) {
603
604
  case SSML_TAGS.MSTTS_EXPRESS_AS: {
604
605
  const element = { type: node.name };
605
606
  const style = readAttribute(attributes, SSML_ATTRS.STYLE);
606
- const styleDegree = readAttribute(attributes, SSML_ATTRS.STYLE_DEGREE, SSML_ATTRS.STYLE_DEGREE_CAMEL);
607
+ const styleDegree = readAttribute(
608
+ attributes,
609
+ SSML_ATTRS.STYLE_DEGREE,
610
+ SSML_ATTRS.STYLE_DEGREE_CAMEL,
611
+ SSML_ATTRS.STYLE_DEGREE_HYPHEN
612
+ );
607
613
  const role = readAttribute(attributes, SSML_ATTRS.ROLE);
608
614
  if (style !== void 0) element.style = style;
609
615
  if (styleDegree !== void 0) element.styleDegree = styleDegree;
@@ -842,10 +848,463 @@ function validateSsml(xmlString) {
842
848
  }
843
849
  }
844
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 findTagEnd(source, start) {
868
+ let quote = "";
869
+ for (let index = start; index < source.length; index += 1) {
870
+ const character = source[index];
871
+ if (quote) {
872
+ if (character === quote) quote = "";
873
+ } else if (character === '"' || character === "'") {
874
+ quote = character;
875
+ } else if (character === ">") {
876
+ return index;
877
+ }
878
+ }
879
+ return source.length - 1;
880
+ }
881
+ function readTagName(tag) {
882
+ const match = /^<\s*([A-Za-z_][A-Za-z0-9_.:-]*)/.exec(tag);
883
+ return match?.[1];
884
+ }
885
+ function collectTextNodes(source) {
886
+ const nodes = [];
887
+ const path = [];
888
+ let index = 0;
889
+ const addText = (start, end, rawText, sourceStart = start, sourceEnd = end) => {
890
+ if (!rawText) return;
891
+ nodes.push({
892
+ context: { parentTag: path[path.length - 1] ?? "", path: [...path] },
893
+ decodedText: decodeXmlText(rawText),
894
+ end,
895
+ sourceEnd,
896
+ sourceStart,
897
+ start
898
+ });
899
+ };
900
+ while (index < source.length) {
901
+ if (source[index] !== "<") {
902
+ const nextTag = source.indexOf("<", index);
903
+ const end2 = nextTag === -1 ? source.length : nextTag;
904
+ addText(index, end2, source.slice(index, end2));
905
+ index = end2;
906
+ continue;
907
+ }
908
+ if (source.startsWith("<!--", index)) {
909
+ const end2 = source.indexOf("-->", index + 4);
910
+ index = end2 === -1 ? source.length : end2 + 3;
911
+ continue;
912
+ }
913
+ if (source.startsWith("<![CDATA[", index)) {
914
+ const contentStart = index + 9;
915
+ const end2 = source.indexOf("]]>", contentStart);
916
+ const contentEnd = end2 === -1 ? source.length : end2;
917
+ addText(
918
+ contentStart,
919
+ contentEnd,
920
+ source.slice(contentStart, contentEnd),
921
+ index,
922
+ end2 === -1 ? source.length : end2 + 3
923
+ );
924
+ index = end2 === -1 ? source.length : end2 + 3;
925
+ continue;
926
+ }
927
+ if (source.startsWith("<?", index)) {
928
+ const end2 = source.indexOf("?>", index + 2);
929
+ index = end2 === -1 ? source.length : end2 + 2;
930
+ continue;
931
+ }
932
+ if (source.startsWith("</", index)) {
933
+ const end2 = findTagEnd(source, index + 2);
934
+ path.pop();
935
+ index = end2 + 1;
936
+ continue;
937
+ }
938
+ const end = findTagEnd(source, index + 1);
939
+ const tag = source.slice(index, end + 1);
940
+ const name = readTagName(tag);
941
+ if (name && !/\/\s*>$/.test(tag)) path.push(name);
942
+ index = end + 1;
943
+ }
944
+ return nodes;
945
+ }
946
+ function extractSsmlText(ssml) {
947
+ parseSsml(ssml);
948
+ return collectTextNodes(ssml).map((node) => node.decodedText);
949
+ }
950
+ async function mapSsmlTextNodes(ssml, transform) {
951
+ parseSsml(ssml);
952
+ const nodes = collectTextNodes(ssml);
953
+ const replacements = await Promise.all(
954
+ nodes.map(async (node) => {
955
+ const transformed = await transform(node.decodedText, {
956
+ parentTag: node.context.parentTag,
957
+ path: [...node.context.path]
958
+ });
959
+ if (typeof transformed !== "string") {
960
+ throw new TypeError("SSML text node transform must return a string");
961
+ }
962
+ return transformed === node.decodedText ? ssml.slice(node.sourceStart, node.sourceEnd) : encodeXmlText(transformed);
963
+ })
964
+ );
965
+ let result = "";
966
+ let cursor = 0;
967
+ nodes.forEach((node, nodeIndex) => {
968
+ result += ssml.slice(cursor, node.sourceStart) + replacements[nodeIndex];
969
+ cursor = node.sourceEnd;
970
+ });
971
+ return result + ssml.slice(cursor);
972
+ }
973
+
974
+ // packages/ssml-core/src/azureValidation.ts
975
+ var EXPRESS_AS_STYLES = {
976
+ "en-us-jennyneural": [
977
+ "assistant",
978
+ "chat",
979
+ "customerservice",
980
+ "newscast",
981
+ "cheerful",
982
+ "empathetic",
983
+ "excited",
984
+ "friendly",
985
+ "hopeful",
986
+ "sad",
987
+ "shouting",
988
+ "terrified",
989
+ "unfriendly",
990
+ "whispering"
991
+ ],
992
+ "en-us-guyneural": [
993
+ "angry",
994
+ "cheerful",
995
+ "excited",
996
+ "friendly",
997
+ "hopeful",
998
+ "newscast",
999
+ "sad",
1000
+ "shouting",
1001
+ "terrified",
1002
+ "unfriendly",
1003
+ "whispering"
1004
+ ],
1005
+ "en-us-jennymultilingualneural": [
1006
+ "cheerful",
1007
+ "empathetic",
1008
+ "excited",
1009
+ "friendly",
1010
+ "hopeful",
1011
+ "sad",
1012
+ "shouting",
1013
+ "terrified",
1014
+ "unfriendly",
1015
+ "whispering"
1016
+ ],
1017
+ "en-us-andrewneural": ["empathetic", "relieved"],
1018
+ "ja-jp-mayuneural": ["calm", "cheerful", "sad"],
1019
+ "ja-jp-nanamineural": ["chat", "customerservice", "cheerful", "whispering", "sad"],
1020
+ "ja-jp-keitaneural": ["chat"],
1021
+ "ko-kr-sunhineural": ["cheerful", "sad"],
1022
+ "zh-cn-yunxineural": [
1023
+ "narration-relaxed",
1024
+ "embarrassed",
1025
+ "fearful",
1026
+ "sad",
1027
+ "disgruntled",
1028
+ "serious",
1029
+ "angry",
1030
+ "depressed",
1031
+ "chat",
1032
+ "cheerful",
1033
+ "assistant"
1034
+ ],
1035
+ "zh-cn-xiaoxiaoneural": [
1036
+ "assistant",
1037
+ "chat",
1038
+ "customerservice",
1039
+ "newscast",
1040
+ "cheerful",
1041
+ "empathetic",
1042
+ "excited",
1043
+ "friendly",
1044
+ "hopeful",
1045
+ "sad",
1046
+ "terrified",
1047
+ "whispering",
1048
+ "poetry-reading",
1049
+ "sports_commentary",
1050
+ "sports_commentary_excited",
1051
+ "story"
1052
+ ],
1053
+ "fr-fr-deniseneural": ["cheerful", "sad"],
1054
+ "fr-fr-henrineural": ["cheerful", "sad"],
1055
+ "pt-br-franciscaneural": ["calm"],
1056
+ "it-it-elsaneural": ["cheerful", "sad"],
1057
+ "de-de-katjaneural": ["cheerful", "sad"],
1058
+ "de-de-conradneural": ["cheerful", "sad"],
1059
+ "ru-ru-svetlananeural": ["cheerful", "sad", "angry", "disgruntled", "embarrassed", "fearful"]
1060
+ };
1061
+ var ALLOWED_BREAK_STRENGTHS = /* @__PURE__ */ new Set(["none", "x-weak", "weak", "medium", "strong", "x-strong"]);
1062
+ var ALLOWED_SAY_AS = /* @__PURE__ */ new Set([
1063
+ "characters",
1064
+ "spell-out",
1065
+ "cardinal",
1066
+ "ordinal",
1067
+ "number",
1068
+ "date",
1069
+ "time",
1070
+ "telephone",
1071
+ "fraction",
1072
+ "address",
1073
+ "name",
1074
+ "currency"
1075
+ ]);
1076
+ var ALLOWED_ROLES = /* @__PURE__ */ new Set([
1077
+ "Girl",
1078
+ "Boy",
1079
+ "YoungAdultFemale",
1080
+ "YoungAdultMale",
1081
+ "OlderAdultFemale",
1082
+ "OlderAdultMale",
1083
+ "SeniorFemale",
1084
+ "SeniorMale"
1085
+ ]);
1086
+ var ALLOWED_EMPHASIS_LEVELS = /* @__PURE__ */ new Set(["strong", "moderate", "reduced", "none"]);
1087
+ var ALLOWED_SILENCE_TYPES = /* @__PURE__ */ new Set([
1088
+ "Leading",
1089
+ "Tailing",
1090
+ "Sentenceboundary",
1091
+ "Comma",
1092
+ "Semicolon",
1093
+ "Enumerationcomma"
1094
+ ]);
1095
+ var ALLOWED_VISEME_TYPES = /* @__PURE__ */ new Set(["redlips_front", "FacialExpression"]);
1096
+ function decodeAttribute(value) {
1097
+ return value.replace(
1098
+ /&(?:amp|apos|gt|lt|quot);/gi,
1099
+ (entity) => ({ "&amp;": "&", "&apos;": "'", "&gt;": ">", "&lt;": "<", "&quot;": '"' })[entity.toLowerCase()] ?? entity
1100
+ );
1101
+ }
1102
+ function findTagEnd2(source, start) {
1103
+ let quote = "";
1104
+ for (let index = start; index < source.length; index += 1) {
1105
+ const character = source[index];
1106
+ if (quote) {
1107
+ if (character === quote) quote = "";
1108
+ } else if (character === '"' || character === "'") quote = character;
1109
+ else if (character === ">") return index;
1110
+ }
1111
+ return source.length - 1;
1112
+ }
1113
+ function tokenizeElements(source) {
1114
+ const tokens = [];
1115
+ let index = 0;
1116
+ while (index < source.length) {
1117
+ const start = source.indexOf("<", index);
1118
+ if (start === -1) break;
1119
+ if (source.startsWith("<!--", start)) {
1120
+ const end2 = source.indexOf("-->", start + 4);
1121
+ index = end2 === -1 ? source.length : end2 + 3;
1122
+ continue;
1123
+ }
1124
+ if (source.startsWith("<![CDATA[", start)) {
1125
+ const end2 = source.indexOf("]]>", start + 9);
1126
+ index = end2 === -1 ? source.length : end2 + 3;
1127
+ continue;
1128
+ }
1129
+ if (source.startsWith("<?", start)) {
1130
+ const end2 = source.indexOf("?>", start + 2);
1131
+ index = end2 === -1 ? source.length : end2 + 2;
1132
+ continue;
1133
+ }
1134
+ const end = findTagEnd2(source, start + 1);
1135
+ const raw = source.slice(start, end + 1);
1136
+ const nameMatch = /^<\s*([A-Za-z_][A-Za-z0-9_.:-]*)/.exec(raw);
1137
+ if (!nameMatch?.[1] || raw.startsWith("</")) {
1138
+ index = end + 1;
1139
+ continue;
1140
+ }
1141
+ const attributes = /* @__PURE__ */ new Map();
1142
+ const attributeSource = raw.slice(nameMatch[0].length, raw.length - 1).replace(/\/\s*$/, "");
1143
+ const attributePattern = /([A-Za-z_][A-Za-z0-9_.:-]*)\s*=\s*(["'])([\s\S]*?)\2/g;
1144
+ for (const match of attributeSource.matchAll(attributePattern)) {
1145
+ attributes.set(match[1].toLowerCase(), decodeAttribute(match[3]));
1146
+ }
1147
+ tokens.push({ attributes, end, name: nameMatch[1], selfClosing: /\/\s*>$/.test(raw), start });
1148
+ index = end + 1;
1149
+ }
1150
+ return tokens;
1151
+ }
1152
+ function location(source, offset) {
1153
+ const before = source.slice(0, Math.max(0, offset));
1154
+ const line = before.split("\n").length;
1155
+ return { line, column: before.length - (before.lastIndexOf("\n") + 1) + 1 };
1156
+ }
1157
+ function addDiagnostic(diagnostics, source, offset, message, severity = "error") {
1158
+ diagnostics.push({ ...location(source, offset), message, severity });
1159
+ }
1160
+ function attr(token, name) {
1161
+ return token.attributes.get(name.toLowerCase());
1162
+ }
1163
+ function validateElement(token, source, diagnostics, voiceName, options) {
1164
+ const name = token.name.toLowerCase();
1165
+ if (name === "voice" && !attr(token, "name")?.trim())
1166
+ addDiagnostic(diagnostics, source, token.start, '<voice> requires a non-empty "name" attribute.');
1167
+ if (name === "break") {
1168
+ const time = attr(token, "time");
1169
+ const strength = attr(token, "strength");
1170
+ if (!time && !strength)
1171
+ addDiagnostic(diagnostics, source, token.start, '<break> requires either "time" or "strength".');
1172
+ if (time && strength)
1173
+ addDiagnostic(diagnostics, source, token.start, '<break> must not specify both "time" and "strength".');
1174
+ if (time && !/^\d+(?:\.\d+)?(?:ms|s)$/.test(time.trim()))
1175
+ addDiagnostic(diagnostics, source, token.start, '<break time> must use a numeric value followed by "ms" or "s".');
1176
+ if (strength && !ALLOWED_BREAK_STRENGTHS.has(strength))
1177
+ addDiagnostic(diagnostics, source, token.start, `Unsupported <break strength> value "${strength}".`);
1178
+ }
1179
+ if (name === "prosody") {
1180
+ const rate = attr(token, "rate");
1181
+ const pitch = attr(token, "pitch");
1182
+ const volume = attr(token, "volume");
1183
+ if (rate && !/^(x-slow|slow|medium|fast|x-fast|[+-]?\d+(?:\.\d+)?%)$/.test(rate.trim()))
1184
+ addDiagnostic(diagnostics, source, token.start, `Unsupported <prosody rate> value "${rate}".`);
1185
+ if (pitch && !/^(x-low|low|medium|high|x-high|[+-]?\d+(?:\.\d+)?(?:st|Hz|%)?)$/.test(pitch.trim()))
1186
+ addDiagnostic(diagnostics, source, token.start, `Unsupported <prosody pitch> value "${pitch}".`);
1187
+ if (volume && !/^(silent|x-soft|soft|medium|loud|x-loud|[+-]?\d+(?:\.\d+)?(?:dB|%)?)$/.test(volume.trim()))
1188
+ addDiagnostic(diagnostics, source, token.start, `Unsupported <prosody volume> value "${volume}".`);
1189
+ }
1190
+ if (name === "mstts:express-as" || name === "express-as" || name === "expressas") {
1191
+ const style = attr(token, "style");
1192
+ if (!style?.trim())
1193
+ addDiagnostic(diagnostics, source, token.start, '<mstts:express-as> requires a non-empty "style" attribute.');
1194
+ const degree = attr(token, "styledegree") ?? attr(token, "style-degree");
1195
+ if (degree && (!/^\d+(?:\.\d+)?$/.test(degree) || Number(degree) < 0.01 || Number(degree) > 2))
1196
+ addDiagnostic(
1197
+ diagnostics,
1198
+ source,
1199
+ token.start,
1200
+ "<mstts:express-as styledegree> must be a number between 0.01 and 2."
1201
+ );
1202
+ const role = attr(token, "role");
1203
+ if (role && !ALLOWED_ROLES.has(role))
1204
+ addDiagnostic(diagnostics, source, token.start, `Unsupported <mstts:express-as role> value "${role}".`);
1205
+ const supportedStyles = voiceName ? EXPRESS_AS_STYLES[voiceName.toLowerCase()] : void 0;
1206
+ if (style && supportedStyles && !supportedStyles.includes(style.toLowerCase()))
1207
+ addDiagnostic(diagnostics, source, token.start, `Style "${style}" is not supported by voice "${voiceName}".`);
1208
+ }
1209
+ if (name === "say-as" || name === "sayas") {
1210
+ const interpretAs = attr(token, "interpret-as");
1211
+ if (!interpretAs || !ALLOWED_SAY_AS.has(interpretAs))
1212
+ addDiagnostic(diagnostics, source, token.start, `<say-as> requires a supported "interpret-as" value.`);
1213
+ }
1214
+ if (name === "phoneme" && (!attr(token, "alphabet") || !attr(token, "ph")))
1215
+ addDiagnostic(diagnostics, source, token.start, '<phoneme> requires both "alphabet" and "ph" attributes.');
1216
+ if (name === "emphasis" && attr(token, "level") && !ALLOWED_EMPHASIS_LEVELS.has(attr(token, "level") ?? ""))
1217
+ addDiagnostic(diagnostics, source, token.start, `Unsupported <emphasis level> value "${attr(token, "level")}".`);
1218
+ if (name === "sub" && !attr(token, "alias")?.trim())
1219
+ addDiagnostic(diagnostics, source, token.start, '<sub> requires a non-empty "alias" attribute.');
1220
+ if (name === "lang" && !attr(token, "xml:lang")?.trim() && !attr(token, "lang")?.trim())
1221
+ addDiagnostic(diagnostics, source, token.start, '<lang> requires an "xml:lang" attribute.');
1222
+ if (name === "mark" && !attr(token, "name")?.trim())
1223
+ addDiagnostic(diagnostics, source, token.start, '<mark> requires a non-empty "name" attribute.');
1224
+ if (name === "bookmark" && !attr(token, "mark")?.trim())
1225
+ addDiagnostic(diagnostics, source, token.start, '<bookmark> requires a non-empty "mark" attribute.');
1226
+ if (name === "lexicon") {
1227
+ const uri = attr(token, "uri");
1228
+ if (!uri) addDiagnostic(diagnostics, source, token.start, '<lexicon> requires a "uri" attribute.');
1229
+ else {
1230
+ try {
1231
+ const parsed = new URL(uri);
1232
+ if (parsed.protocol !== "https:")
1233
+ addDiagnostic(diagnostics, source, token.start, "<lexicon uri> must use HTTPS.");
1234
+ } catch {
1235
+ addDiagnostic(diagnostics, source, token.start, "<lexicon uri> must be an absolute HTTPS URL.");
1236
+ }
1237
+ }
1238
+ }
1239
+ if (name === "mstts:silence") {
1240
+ const type = attr(token, "type");
1241
+ const value = attr(token, "value");
1242
+ if (!type || !ALLOWED_SILENCE_TYPES.has(type))
1243
+ addDiagnostic(diagnostics, source, token.start, '<mstts:silence> requires a supported "type" attribute.');
1244
+ if (!value || !/^\d+(?:\.\d+)?(?:ms|s)$/.test(value.trim()))
1245
+ addDiagnostic(diagnostics, source, token.start, '<mstts:silence> requires a time-valued "value" attribute.');
1246
+ }
1247
+ if (name === "mstts:viseme") {
1248
+ const type = attr(token, "type");
1249
+ if (!type || !ALLOWED_VISEME_TYPES.has(type))
1250
+ addDiagnostic(diagnostics, source, token.start, '<mstts:viseme> requires a supported "type" attribute.');
1251
+ }
1252
+ if (name === "audio") {
1253
+ const src = attr(token, "src");
1254
+ if (!src) addDiagnostic(diagnostics, source, token.start, '<audio> requires a "src" attribute.');
1255
+ else {
1256
+ let parsed;
1257
+ try {
1258
+ parsed = new URL(src);
1259
+ } catch {
1260
+ addDiagnostic(diagnostics, source, token.start, "<audio src> must be an absolute HTTP(S) URL.");
1261
+ return;
1262
+ }
1263
+ if (parsed.protocol !== "https:" && !(options.allowHttpAudio && parsed.protocol === "http:"))
1264
+ addDiagnostic(diagnostics, source, token.start, "<audio src> must use HTTPS.");
1265
+ if (options.allowedAudioOrigins && !options.allowedAudioOrigins.includes(parsed.origin))
1266
+ addDiagnostic(diagnostics, source, token.start, `<audio src> origin "${parsed.origin}" is not allowed.`);
1267
+ }
1268
+ }
1269
+ }
1270
+ function validateAzureSsml(ssml, options = {}) {
1271
+ const diagnostics = [];
1272
+ if (typeof ssml !== "string") {
1273
+ return [{ line: 1, column: 1, message: "SSML input must be a string", severity: "error" }];
1274
+ }
1275
+ const maxLength = options.maxLength ?? 1e4;
1276
+ if (ssml.length > maxLength)
1277
+ addDiagnostic(diagnostics, ssml, maxLength, `SSML exceeds the maximum length of ${maxLength} characters.`);
1278
+ try {
1279
+ parseSsml(ssml);
1280
+ } catch (error) {
1281
+ const message = error instanceof Error ? error.message.replace(/ at position \d+$/, "") : String(error);
1282
+ const match = / at position (\d+)$/.exec(error instanceof Error ? error.message : "");
1283
+ addDiagnostic(diagnostics, ssml, match ? Number(match[1]) : 0, message);
1284
+ return diagnostics;
1285
+ }
1286
+ const tokens = tokenizeElements(ssml);
1287
+ const speak = tokens.find((token) => token.name.toLowerCase() === "speak");
1288
+ const voices = tokens.filter((token) => token.name.toLowerCase() === "voice");
1289
+ if (!speak || voices.length === 0)
1290
+ addDiagnostic(
1291
+ diagnostics,
1292
+ ssml,
1293
+ speak?.start ?? 0,
1294
+ "Azure SSML requires at least one <voice> element under <speak>."
1295
+ );
1296
+ const voiceName = voices[0] ? attr(voices[0], "name") : void 0;
1297
+ for (const token of tokens) validateElement(token, ssml, diagnostics, voiceName, options);
1298
+ return diagnostics;
1299
+ }
1300
+
845
1301
  export {
846
1302
  buildSsml,
847
1303
  parseSsml,
848
1304
  buildPartialSsml,
849
- validateSsml
1305
+ validateSsml,
1306
+ extractSsmlText,
1307
+ mapSsmlTextNodes,
1308
+ validateAzureSsml
850
1309
  };
851
- //# sourceMappingURL=chunk-I3GP7OJU.mjs.map
1310
+ //# sourceMappingURL=chunk-RUIEMCWP.mjs.map