@pie-element/venn-classification 0.1.1-next.1 → 0.1.1-next.10

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.
Files changed (36) hide show
  1. package/author.js +2 -0
  2. package/dist/author/index.d.ts +2 -10
  3. package/dist/author/index.js +23824 -18172
  4. package/dist/author/index.js.map +1 -1
  5. package/dist/browser/VennClassification-CijQL7Lf.js +3620 -0
  6. package/dist/browser/VennClassification-CijQL7Lf.js.map +1 -0
  7. package/dist/browser/author/index.js +5428 -4285
  8. package/dist/browser/author/index.js.map +1 -1
  9. package/dist/browser/controller/index.js +2 -2
  10. package/dist/browser/controller-bkBJ6-j1.js +1779 -0
  11. package/dist/browser/controller-bkBJ6-j1.js.map +1 -0
  12. package/dist/browser/delivery/index.js +86 -27
  13. package/dist/browser/delivery/index.js.map +1 -1
  14. package/dist/controller/defaults.d.ts +5 -0
  15. package/dist/controller/index.d.ts +21 -7
  16. package/dist/controller/index.js +2400 -50
  17. package/dist/controller/index.js.map +1 -1
  18. package/dist/controller/region.d.ts +2 -2
  19. package/dist/delivery/dnd.d.ts +9 -0
  20. package/dist/delivery/index.d.ts +2 -14
  21. package/dist/delivery/index.js +6672 -3644
  22. package/dist/delivery/index.js.map +1 -1
  23. package/dist/delivery/layout.d.ts +104 -34
  24. package/dist/delivery/tile-accessible-name.d.ts +13 -1
  25. package/dist/i18n.d.ts +9 -0
  26. package/dist/index.iife.js +17 -17
  27. package/dist/index.js +2 -6697
  28. package/dist/runtime-support.js +5 -5
  29. package/dist/runtime-support.js.map +1 -1
  30. package/dist/types.d.ts +7 -0
  31. package/package.json +10 -19
  32. package/dist/browser/VennClassification-C6roHfLf.js +0 -3412
  33. package/dist/browser/VennClassification-C6roHfLf.js.map +0 -1
  34. package/dist/browser/controller-Dt0dg5dA.js +0 -249
  35. package/dist/browser/controller-Dt0dg5dA.js.map +0 -1
  36. package/dist/index.js.map +0 -1
@@ -1,13 +1,12 @@
1
1
  var defaults_default = {
2
2
  model: {
3
- id: "1",
4
- element: "venn-classification",
5
3
  prompt: "<p>Sort each tile into the correct region of the Venn diagram.</p>",
6
4
  promptEnabled: true,
7
5
  circles: [{ label: "Set A" }, { label: "Set B" }],
8
6
  tiles: [],
9
7
  regionLabels: {},
10
- scoringPolicy: "partialPerTile"
8
+ scoringPolicy: "partialPerTile",
9
+ teacherInstructionsEnabled: true
11
10
  },
12
11
  configuration: {
13
12
  prompt: {
@@ -17,12 +16,2361 @@ var defaults_default = {
17
16
  scoringPolicy: {
18
17
  label: "Scoring policy",
19
18
  settings: true
19
+ },
20
+ teacherInstructions: {
21
+ label: "Teacher Instructions",
22
+ settings: true
23
+ },
24
+ settingsPanelDisabled: false
25
+ }
26
+ };
27
+ //#endregion
28
+ //#region ../../shared/translator/dist/en.js
29
+ var e$1 = {
30
+ translation: {
31
+ categorize: {
32
+ limitMaxChoicesPerCategory: "You've reached the limit of {{maxChoicesPerCategory}} responses per area. To add another response, one must first be removed.",
33
+ maxChoicesPerCategoryRestriction: "To change this value to {{maxChoicesPerCategory}}, each category must have {{maxChoicesPerCategory}} or fewer answer choice[s]."
34
+ },
35
+ ebsr: { part: "Part {{index}}" },
36
+ numberLine: {
37
+ addElementLimit_one: "You can only add {{count}} element",
38
+ addElementLimit_other: "You can only add {{count}} elements",
39
+ clearAll: "Clear all"
40
+ },
41
+ imageClozeAssociation: {
42
+ reachedLimit_one: "You’ve reached the limit of {{count}} response per area. To add another response, one must first be removed.",
43
+ reachedLimit_other: "Full"
44
+ },
45
+ drawingResponse: {
46
+ fillColor: "Fill color",
47
+ outlineColor: "Outline color",
48
+ noFill: "No fill",
49
+ lightblue: "Light blue",
50
+ lightyellow: "Light yellow",
51
+ red: "Red",
52
+ orange: "Orange",
53
+ yellow: "Yellow",
54
+ violet: "Violet",
55
+ blue: "Blue",
56
+ green: "Green",
57
+ white: "White",
58
+ black: "Black",
59
+ onDoubleClick: "Double click to edit this text. Press Enter to submit."
60
+ },
61
+ charting: {
62
+ addCategory: "Add category",
63
+ actions: "Actions",
64
+ add: "Add",
65
+ delete: "Delete",
66
+ newLabel: "New label",
67
+ reachedLimit_other: "There can't be more than {{count}} categories.",
68
+ keyLegend: {
69
+ incorrectAnswer: "Student incorrect answer",
70
+ correctAnswer: "Student correct answer",
71
+ correctKeyAnswer: "Answer key correct"
72
+ }
73
+ },
74
+ graphing: {
75
+ point: "Point",
76
+ circle: "Circle",
77
+ line: "Line",
78
+ parabola: "Parabola",
79
+ absolute: "Absolute Value",
80
+ exponential: "Exponential",
81
+ polygon: "Polygon",
82
+ ray: "Ray",
83
+ segment: "Segment",
84
+ sine: "Sine",
85
+ vector: "Vector",
86
+ label: "Label",
87
+ redo: "Redo",
88
+ reset: "Reset"
89
+ },
90
+ mathInline: { primaryCorrectWithAlternates: "Note: The answer shown above is the primary correct answer specified by the author for this item, but other answers may also be recognized as correct." },
91
+ mcPopulatedBlank: {
92
+ answerChoices: "Answer choices",
93
+ blankLabel: "blank",
94
+ emptyBlank: "(blank)",
95
+ blankPreSelectionHint: "The answer you choose will appear on the blank line above.",
96
+ correctAnswerSelected: "Correct answer selected",
97
+ incorrectAnswerSelected: "Incorrect answer selected",
98
+ selectedAnswerImage: "Selected answer image",
99
+ choiceImage: "Choice {{id}}",
100
+ clickToEnableAutoplay: "Click to enable audio autoplay",
101
+ audioResourceUnavailable: "Audio is enabled but no playable audio URL is configured.",
102
+ listen: "Listen",
103
+ listenSilentAlt: "Repeat instructions",
104
+ listenPlayingAlt: "Instructions are playing",
105
+ printAudio: "Audio:",
106
+ printTranscript: "Transcript:"
107
+ },
108
+ multipleChoice: {
109
+ minSelections: "Select at least {{minSelections}}.",
110
+ maxSelections_one: "Only {{maxSelections}} answer is allowed.",
111
+ maxSelections_other: "Only {{maxSelections}} answers are allowed.",
112
+ minmaxSelections_equal: "Select {{minSelections}}.",
113
+ minmaxSelections_range: "Select between {{minSelections}} and {{maxSelections}}."
114
+ },
115
+ selectText: {
116
+ correctAnswerSelected: "Correct",
117
+ correctAnswerNotSelected: "Correct Answer Not Selected",
118
+ incorrectSelection: "Incorrect Selection",
119
+ key: "Key"
120
+ },
121
+ simpleCloze: {
122
+ correctAnswerShown: "Correct answer",
123
+ correct: "Correct",
124
+ incorrect: "Incorrect",
125
+ unanswered: "No answer",
126
+ placeholder: "Enter your answer...",
127
+ answerInput: "Your answer",
128
+ printCorrectAnswer: "Correct answer:",
129
+ printAnswerBlank: "Answer blank"
130
+ },
131
+ vennClassification: {
132
+ tray: "Tiles to classify",
133
+ unknownTarget: "unknown",
134
+ cancelled: "Cancelled",
135
+ returnedToTray: "{{name}} returned to tray",
136
+ placedIn: "{{name}} placed in {{target}}",
137
+ pickedUp: "Picked up {{name}}",
138
+ pickedUpWithKeyboard: "Picked up {{name}}, drop target: {{target}}. Use arrow keys to choose a drop target, Enter to drop, Escape to cancel.",
139
+ dropTarget: "Drop target: {{target}}",
140
+ unsupportedCircles_one: "This diagram cannot be shown: it has {{count}} circle, and only {{supported}} are supported.",
141
+ unsupportedCircles_other: "This diagram cannot be shown: it has {{count}} circles, and only {{supported}} are supported.",
142
+ setNumber: "Set {{number}}",
143
+ regionOnly: "{{set}} only",
144
+ regionNeither: "Neither {{first}} nor {{second}}",
145
+ regionNoneOf: "None of {{sets}}",
146
+ regionAndSeparator: " and ",
147
+ tileFallbackName: "Tile",
148
+ tileNotPlaced: "not placed",
149
+ tileInRegion: "in {{region}}",
150
+ tileCorrect: "correct",
151
+ tileIncorrect: "incorrect"
152
+ }
153
+ },
154
+ common: {
155
+ undo: "Undo",
156
+ clearAll: "Clear all",
157
+ correct: "Correct",
158
+ incorrect: "Incorrect",
159
+ showCorrectAnswer: "Show correct answer",
160
+ hideCorrectAnswer: "Hide correct answer",
161
+ showTeacherInstructions: "Show Teacher Instructions",
162
+ hideTeacherInstructions: "Hide Teacher Instructions",
163
+ commonCorrectAnswerWithAlternates: "Note: The answer shown above is the most common correct answer for this item. One or more additional correct answers are also defined, and will also be recognized as correct.",
164
+ warning: "Warning",
165
+ showNote: "Show Note",
166
+ hideNote: "Hide Note",
167
+ cancel: "Cancel"
168
+ }
169
+ };
170
+ //#endregion
171
+ //#region ../../shared/translator/dist/es.js
172
+ var e = {
173
+ translation: {
174
+ categorize: {
175
+ limitMaxChoicesPerCategory: "Has alcanzado el límite de {{maxChoicesPerCategory}} respuestas por área. Para agregar otra respuesta, primero se debe eliminar una respuesta.",
176
+ maxChoicesPerCategoryRestriction: "Para cambiar este valor a {{maxChoicesPerCategory}}, cada categoría debe tener {{maxChoicesPerCategory}} o menos opciones de respuesta"
177
+ },
178
+ ebsr: { part: "Parte {{index}}" },
179
+ numberLine: {
180
+ addElementLimit_one: "Solo puedes agregar {{count}} elemento",
181
+ addElementLimit_other: "Solo puedes agregar {{count}} elementos",
182
+ clearAll: "Borrar todo"
183
+ },
184
+ imageClozeAssociation: {
185
+ reachedLimit_one: "Has alcanzado el límite de {{count}} respuesta por área. Para agregar otra respuesta, primero se debe eliminar una respuesta.",
186
+ reachedLimit_other: "Lleno"
187
+ },
188
+ drawingResponse: {
189
+ fillColor: "Color de relleno",
190
+ outlineColor: "Color del contorno",
191
+ noFill: "Sin relleno",
192
+ lightblue: "Azul claro",
193
+ lightyellow: "Amarillo claro",
194
+ red: "Rojo",
195
+ orange: "Naranja",
196
+ yellow: "Amarillo",
197
+ violet: "Violeta",
198
+ blue: "Azul",
199
+ green: "Verde",
200
+ white: "Blanco",
201
+ black: "Negro",
202
+ onDoubleClick: "Haz doble clic para revisar este texto. Presiona el botón de ingreso para enviar"
203
+ },
204
+ charting: {
205
+ addCategory: "Añadir categoría",
206
+ actions: "Acciones",
207
+ add: "Añadir",
208
+ delete: "Eliminar",
209
+ newLabel: "Nueva etiqueta",
210
+ reachedLimit_other: "No puede haber más de {{count}} categorías.",
211
+ keyLegend: {
212
+ incorrectAnswer: "Respuesta incorrecta del estudiante",
213
+ correctAnswer: "Respuesta correcta del estudiante",
214
+ correctKeyAnswer: "Clave de respuesta correcta"
215
+ }
216
+ },
217
+ graphing: {
218
+ point: "Punto",
219
+ circle: "Circulo",
220
+ line: "Línea",
221
+ parabola: "Parábola",
222
+ absolute: "Valor absoluto",
223
+ exponential: "Exponencial",
224
+ polygon: "Polígono",
225
+ ray: "Semirrecta",
226
+ segment: "Segmento ",
227
+ sine: "Seno",
228
+ vector: "Vector",
229
+ label: "Etiqueta",
230
+ redo: "Rehacer",
231
+ reset: "Reiniciar"
232
+ },
233
+ mathInline: { primaryCorrectWithAlternates: "Nota: La respuesta que se muestra arriba es la respuesta correcta principal especificada por el autor para esta pregunta, pero también se pueden reconocer otras respuestas como correctas." },
234
+ mcPopulatedBlank: {
235
+ answerChoices: "Opciones de respuesta",
236
+ blankLabel: "espacio en blanco",
237
+ emptyBlank: "(en blanco)",
238
+ blankPreSelectionHint: "La respuesta que elijas aparecerá en la línea en blanco de arriba.",
239
+ correctAnswerSelected: "Respuesta correcta seleccionada",
240
+ incorrectAnswerSelected: "Respuesta incorrecta seleccionada",
241
+ selectedAnswerImage: "Imagen de la respuesta seleccionada",
242
+ choiceImage: "Opción {{id}}",
243
+ clickToEnableAutoplay: "Haz clic para activar la reproducción automática del audio",
244
+ audioResourceUnavailable: "El audio está activado, pero no hay una URL de audio reproducible configurada.",
245
+ listen: "Escuchar",
246
+ listenSilentAlt: "Escuchar. Repetir las instrucciones.",
247
+ listenPlayingAlt: "Escuchar. Estas son las instrucciones.",
248
+ printAudio: "Audio:",
249
+ printTranscript: "Transcripción:"
250
+ },
251
+ multipleChoice: {
252
+ minSelections: "Seleccione al menos {{minSelections}}.",
253
+ maxSelections_one: "Sólo se permite {{maxSelections}} respuesta.",
254
+ maxSelections_other: "Sólo se permiten {{maxSelections}} respuestas.",
255
+ minmaxSelections_equal: "Seleccione {{minSelections}}.",
256
+ minmaxSelections_range: "Seleccione entre {{minSelections}} y {{maxSelections}}."
257
+ },
258
+ selectText: {
259
+ correctAnswerSelected: "Respuesta Correcta",
260
+ correctAnswerNotSelected: "Respuesta Correcta No Seleccionada",
261
+ incorrectSelection: "Selección Incorrecta",
262
+ key: "Clave"
263
+ },
264
+ simpleCloze: {
265
+ correctAnswerShown: "Respuesta correcta",
266
+ correct: "Correcto",
267
+ incorrect: "Incorrecto",
268
+ unanswered: "Sin respuesta",
269
+ placeholder: "Escribe tu respuesta...",
270
+ answerInput: "Tu respuesta",
271
+ printCorrectAnswer: "Respuesta correcta:",
272
+ printAnswerBlank: "Espacio para la respuesta"
273
+ },
274
+ vennClassification: {
275
+ tray: "Fichas para clasificar",
276
+ unknownTarget: "desconocido",
277
+ cancelled: "Cancelado",
278
+ returnedToTray: "Se devolvió {{name}} a la bandeja",
279
+ placedIn: "Se colocó {{name}} en {{target}}",
280
+ pickedUp: "Se tomó {{name}}",
281
+ pickedUpWithKeyboard: "Se tomó {{name}}, destino: {{target}}. Usa las flechas para elegir un destino, Enter para soltar y Escape para cancelar.",
282
+ dropTarget: "Destino: {{target}}",
283
+ unsupportedCircles_one: "No se puede mostrar este diagrama: tiene {{count}} círculo, y solo se admiten {{supported}}.",
284
+ unsupportedCircles_other: "No se puede mostrar este diagrama: tiene {{count}} círculos, y solo se admiten {{supported}}.",
285
+ setNumber: "Conjunto {{number}}",
286
+ regionOnly: "Solo {{set}}",
287
+ regionNeither: "Ni {{first}} ni {{second}}",
288
+ regionNoneOf: "Ninguno de {{sets}}",
289
+ regionAndSeparator: " y ",
290
+ tileFallbackName: "Ficha",
291
+ tileNotPlaced: "sin colocar",
292
+ tileInRegion: "en {{region}}",
293
+ tileCorrect: "correcta",
294
+ tileIncorrect: "incorrecta"
295
+ }
296
+ },
297
+ common: {
298
+ undo: "Deshacer",
299
+ clearAll: "Borrar todo",
300
+ correct: "Correcto",
301
+ incorrect: "Incorrecto",
302
+ showCorrectAnswer: "Mostrar respuesta correcta",
303
+ hideCorrectAnswer: "Ocultar respuesta correcta",
304
+ showTeacherInstructions: "Mostrar instrucciones para el maestro",
305
+ hideTeacherInstructions: "Ocultar instrucciones para el maestro",
306
+ commonCorrectAnswerWithAlternates: "Nota: La respuesta que se muestra arriba es la respuesta correcta más común para esta pregunta. También se definen una o más respuestas correctas adicionales, y también se reconocerán como correctas.",
307
+ warning: "Advertencia",
308
+ showNote: "Mostrar Nota",
309
+ hideNote: "Ocultar Nota",
310
+ cancel: "Cancelar"
311
+ }
312
+ };
313
+ //#endregion
314
+ //#region ../../../node_modules/.bun/i18next@25.10.10+1fb4c65d43e298b9/node_modules/i18next/dist/esm/i18next.js
315
+ var isString = (obj) => typeof obj === "string";
316
+ var defer = () => {
317
+ let res;
318
+ let rej;
319
+ const promise = new Promise((resolve, reject) => {
320
+ res = resolve;
321
+ rej = reject;
322
+ });
323
+ promise.resolve = res;
324
+ promise.reject = rej;
325
+ return promise;
326
+ };
327
+ var makeString = (object) => {
328
+ if (object == null) return "";
329
+ return "" + object;
330
+ };
331
+ var copy = (a, s, t) => {
332
+ a.forEach((m) => {
333
+ if (s[m]) t[m] = s[m];
334
+ });
335
+ };
336
+ var lastOfPathSeparatorRegExp = /###/g;
337
+ var cleanKey = (key) => key && key.indexOf("###") > -1 ? key.replace(lastOfPathSeparatorRegExp, ".") : key;
338
+ var canNotTraverseDeeper = (object) => !object || isString(object);
339
+ var getLastOfPath = (object, path, Empty) => {
340
+ const stack = !isString(path) ? path : path.split(".");
341
+ let stackIndex = 0;
342
+ while (stackIndex < stack.length - 1) {
343
+ if (canNotTraverseDeeper(object)) return {};
344
+ const key = cleanKey(stack[stackIndex]);
345
+ if (!object[key] && Empty) object[key] = new Empty();
346
+ if (Object.prototype.hasOwnProperty.call(object, key)) object = object[key];
347
+ else object = {};
348
+ ++stackIndex;
349
+ }
350
+ if (canNotTraverseDeeper(object)) return {};
351
+ return {
352
+ obj: object,
353
+ k: cleanKey(stack[stackIndex])
354
+ };
355
+ };
356
+ var setPath = (object, path, newValue) => {
357
+ const { obj, k } = getLastOfPath(object, path, Object);
358
+ if (obj !== void 0 || path.length === 1) {
359
+ obj[k] = newValue;
360
+ return;
361
+ }
362
+ let e = path[path.length - 1];
363
+ let p = path.slice(0, path.length - 1);
364
+ let last = getLastOfPath(object, p, Object);
365
+ while (last.obj === void 0 && p.length) {
366
+ e = `${p[p.length - 1]}.${e}`;
367
+ p = p.slice(0, p.length - 1);
368
+ last = getLastOfPath(object, p, Object);
369
+ if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== "undefined") last.obj = void 0;
370
+ }
371
+ last.obj[`${last.k}.${e}`] = newValue;
372
+ };
373
+ var pushPath = (object, path, newValue, concat) => {
374
+ const { obj, k } = getLastOfPath(object, path, Object);
375
+ obj[k] = obj[k] || [];
376
+ obj[k].push(newValue);
377
+ };
378
+ var getPath = (object, path) => {
379
+ const { obj, k } = getLastOfPath(object, path);
380
+ if (!obj) return void 0;
381
+ if (!Object.prototype.hasOwnProperty.call(obj, k)) return void 0;
382
+ return obj[k];
383
+ };
384
+ var getPathWithDefaults = (data, defaultData, key) => {
385
+ const value = getPath(data, key);
386
+ if (value !== void 0) return value;
387
+ return getPath(defaultData, key);
388
+ };
389
+ var deepExtend = (target, source, overwrite) => {
390
+ for (const prop in source) if (prop !== "__proto__" && prop !== "constructor") if (prop in target) if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
391
+ if (overwrite) target[prop] = source[prop];
392
+ } else deepExtend(target[prop], source[prop], overwrite);
393
+ else target[prop] = source[prop];
394
+ return target;
395
+ };
396
+ var regexEscape = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
397
+ var _entityMap = {
398
+ "&": "&amp;",
399
+ "<": "&lt;",
400
+ ">": "&gt;",
401
+ "\"": "&quot;",
402
+ "'": "&#39;",
403
+ "/": "&#x2F;"
404
+ };
405
+ var escape = (data) => {
406
+ if (isString(data)) return data.replace(/[&<>"'\/]/g, (s) => _entityMap[s]);
407
+ return data;
408
+ };
409
+ var RegExpCache = class {
410
+ constructor(capacity) {
411
+ this.capacity = capacity;
412
+ this.regExpMap = /* @__PURE__ */ new Map();
413
+ this.regExpQueue = [];
414
+ }
415
+ getRegExp(pattern) {
416
+ const regExpFromCache = this.regExpMap.get(pattern);
417
+ if (regExpFromCache !== void 0) return regExpFromCache;
418
+ const regExpNew = new RegExp(pattern);
419
+ if (this.regExpQueue.length === this.capacity) this.regExpMap.delete(this.regExpQueue.shift());
420
+ this.regExpMap.set(pattern, regExpNew);
421
+ this.regExpQueue.push(pattern);
422
+ return regExpNew;
423
+ }
424
+ };
425
+ var chars = [
426
+ " ",
427
+ ",",
428
+ "?",
429
+ "!",
430
+ ";"
431
+ ];
432
+ var looksLikeObjectPathRegExpCache = new RegExpCache(20);
433
+ var looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
434
+ nsSeparator = nsSeparator || "";
435
+ keySeparator = keySeparator || "";
436
+ const possibleChars = chars.filter((c) => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
437
+ if (possibleChars.length === 0) return true;
438
+ const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`);
439
+ let matched = !r.test(key);
440
+ if (!matched) {
441
+ const ki = key.indexOf(keySeparator);
442
+ if (ki > 0 && !r.test(key.substring(0, ki))) matched = true;
443
+ }
444
+ return matched;
445
+ };
446
+ var deepFind = (obj, path, keySeparator = ".") => {
447
+ if (!obj) return void 0;
448
+ if (obj[path]) {
449
+ if (!Object.prototype.hasOwnProperty.call(obj, path)) return void 0;
450
+ return obj[path];
451
+ }
452
+ const tokens = path.split(keySeparator);
453
+ let current = obj;
454
+ for (let i = 0; i < tokens.length;) {
455
+ if (!current || typeof current !== "object") return;
456
+ let next;
457
+ let nextPath = "";
458
+ for (let j = i; j < tokens.length; ++j) {
459
+ if (j !== i) nextPath += keySeparator;
460
+ nextPath += tokens[j];
461
+ next = current[nextPath];
462
+ if (next !== void 0) {
463
+ if ([
464
+ "string",
465
+ "number",
466
+ "boolean"
467
+ ].indexOf(typeof next) > -1 && j < tokens.length - 1) continue;
468
+ i += j - i + 1;
469
+ break;
470
+ }
471
+ }
472
+ current = next;
473
+ }
474
+ return current;
475
+ };
476
+ var getCleanedCode = (code) => code?.replace(/_/g, "-");
477
+ var consoleLogger = {
478
+ type: "logger",
479
+ log(args) {
480
+ this.output("log", args);
481
+ },
482
+ warn(args) {
483
+ this.output("warn", args);
484
+ },
485
+ error(args) {
486
+ this.output("error", args);
487
+ },
488
+ output(type, args) {
489
+ console?.[type]?.apply?.(console, args);
490
+ }
491
+ };
492
+ var baseLogger = new class Logger {
493
+ constructor(concreteLogger, options = {}) {
494
+ this.init(concreteLogger, options);
495
+ }
496
+ init(concreteLogger, options = {}) {
497
+ this.prefix = options.prefix || "i18next:";
498
+ this.logger = concreteLogger || consoleLogger;
499
+ this.options = options;
500
+ this.debug = options.debug;
501
+ }
502
+ log(...args) {
503
+ return this.forward(args, "log", "", true);
504
+ }
505
+ warn(...args) {
506
+ return this.forward(args, "warn", "", true);
507
+ }
508
+ error(...args) {
509
+ return this.forward(args, "error", "");
510
+ }
511
+ deprecate(...args) {
512
+ return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
513
+ }
514
+ forward(args, lvl, prefix, debugOnly) {
515
+ if (debugOnly && !this.debug) return null;
516
+ if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
517
+ return this.logger[lvl](args);
518
+ }
519
+ create(moduleName) {
520
+ return new Logger(this.logger, {
521
+ prefix: `${this.prefix}:${moduleName}:`,
522
+ ...this.options
523
+ });
524
+ }
525
+ clone(options) {
526
+ options = options || this.options;
527
+ options.prefix = options.prefix || this.prefix;
528
+ return new Logger(this.logger, options);
529
+ }
530
+ }();
531
+ var EventEmitter = class {
532
+ constructor() {
533
+ this.observers = {};
534
+ }
535
+ on(events, listener) {
536
+ events.split(" ").forEach((event) => {
537
+ if (!this.observers[event]) this.observers[event] = /* @__PURE__ */ new Map();
538
+ const numListeners = this.observers[event].get(listener) || 0;
539
+ this.observers[event].set(listener, numListeners + 1);
540
+ });
541
+ return this;
542
+ }
543
+ off(event, listener) {
544
+ if (!this.observers[event]) return;
545
+ if (!listener) {
546
+ delete this.observers[event];
547
+ return;
548
+ }
549
+ this.observers[event].delete(listener);
550
+ }
551
+ emit(event, ...args) {
552
+ if (this.observers[event]) Array.from(this.observers[event].entries()).forEach(([observer, numTimesAdded]) => {
553
+ for (let i = 0; i < numTimesAdded; i++) observer(...args);
554
+ });
555
+ if (this.observers["*"]) Array.from(this.observers["*"].entries()).forEach(([observer, numTimesAdded]) => {
556
+ for (let i = 0; i < numTimesAdded; i++) observer.apply(observer, [event, ...args]);
557
+ });
558
+ }
559
+ };
560
+ var ResourceStore = class extends EventEmitter {
561
+ constructor(data, options = {
562
+ ns: ["translation"],
563
+ defaultNS: "translation"
564
+ }) {
565
+ super();
566
+ this.data = data || {};
567
+ this.options = options;
568
+ if (this.options.keySeparator === void 0) this.options.keySeparator = ".";
569
+ if (this.options.ignoreJSONStructure === void 0) this.options.ignoreJSONStructure = true;
570
+ }
571
+ addNamespaces(ns) {
572
+ if (this.options.ns.indexOf(ns) < 0) this.options.ns.push(ns);
573
+ }
574
+ removeNamespaces(ns) {
575
+ const index = this.options.ns.indexOf(ns);
576
+ if (index > -1) this.options.ns.splice(index, 1);
577
+ }
578
+ getResource(lng, ns, key, options = {}) {
579
+ const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
580
+ const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
581
+ let path;
582
+ if (lng.indexOf(".") > -1) path = lng.split(".");
583
+ else {
584
+ path = [lng, ns];
585
+ if (key) if (Array.isArray(key)) path.push(...key);
586
+ else if (isString(key) && keySeparator) path.push(...key.split(keySeparator));
587
+ else path.push(key);
588
+ }
589
+ const result = getPath(this.data, path);
590
+ if (!result && !ns && !key && lng.indexOf(".") > -1) {
591
+ lng = path[0];
592
+ ns = path[1];
593
+ key = path.slice(2).join(".");
594
+ }
595
+ if (result || !ignoreJSONStructure || !isString(key)) return result;
596
+ return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
597
+ }
598
+ addResource(lng, ns, key, value, options = { silent: false }) {
599
+ const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
600
+ let path = [lng, ns];
601
+ if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
602
+ if (lng.indexOf(".") > -1) {
603
+ path = lng.split(".");
604
+ value = ns;
605
+ ns = path[1];
606
+ }
607
+ this.addNamespaces(ns);
608
+ setPath(this.data, path, value);
609
+ if (!options.silent) this.emit("added", lng, ns, key, value);
610
+ }
611
+ addResources(lng, ns, resources, options = { silent: false }) {
612
+ for (const m in resources) if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], { silent: true });
613
+ if (!options.silent) this.emit("added", lng, ns, resources);
614
+ }
615
+ addResourceBundle(lng, ns, resources, deep, overwrite, options = {
616
+ silent: false,
617
+ skipCopy: false
618
+ }) {
619
+ let path = [lng, ns];
620
+ if (lng.indexOf(".") > -1) {
621
+ path = lng.split(".");
622
+ deep = resources;
623
+ resources = ns;
624
+ ns = path[1];
625
+ }
626
+ this.addNamespaces(ns);
627
+ let pack = getPath(this.data, path) || {};
628
+ if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
629
+ if (deep) deepExtend(pack, resources, overwrite);
630
+ else pack = {
631
+ ...pack,
632
+ ...resources
633
+ };
634
+ setPath(this.data, path, pack);
635
+ if (!options.silent) this.emit("added", lng, ns, resources);
636
+ }
637
+ removeResourceBundle(lng, ns) {
638
+ if (this.hasResourceBundle(lng, ns)) delete this.data[lng][ns];
639
+ this.removeNamespaces(ns);
640
+ this.emit("removed", lng, ns);
641
+ }
642
+ hasResourceBundle(lng, ns) {
643
+ return this.getResource(lng, ns) !== void 0;
644
+ }
645
+ getResourceBundle(lng, ns) {
646
+ if (!ns) ns = this.options.defaultNS;
647
+ return this.getResource(lng, ns);
648
+ }
649
+ getDataByLanguage(lng) {
650
+ return this.data[lng];
651
+ }
652
+ hasLanguageSomeTranslations(lng) {
653
+ const data = this.getDataByLanguage(lng);
654
+ return !!(data && Object.keys(data) || []).find((v) => data[v] && Object.keys(data[v]).length > 0);
655
+ }
656
+ toJSON() {
657
+ return this.data;
658
+ }
659
+ };
660
+ var postProcessor = {
661
+ processors: {},
662
+ addPostProcessor(module) {
663
+ this.processors[module.name] = module;
664
+ },
665
+ handle(processors, value, key, options, translator) {
666
+ processors.forEach((processor) => {
667
+ value = this.processors[processor]?.process(value, key, options, translator) ?? value;
668
+ });
669
+ return value;
670
+ }
671
+ };
672
+ var PATH_KEY = Symbol("i18next/PATH_KEY");
673
+ function createProxy() {
674
+ const state = [];
675
+ const handler = Object.create(null);
676
+ let proxy;
677
+ handler.get = (target, key) => {
678
+ proxy?.revoke?.();
679
+ if (key === PATH_KEY) return state;
680
+ state.push(key);
681
+ proxy = Proxy.revocable(target, handler);
682
+ return proxy.proxy;
683
+ };
684
+ return Proxy.revocable(Object.create(null), handler).proxy;
685
+ }
686
+ function keysFromSelector(selector, opts) {
687
+ const { [PATH_KEY]: path } = selector(createProxy());
688
+ const keySeparator = opts?.keySeparator ?? ".";
689
+ const nsSeparator = opts?.nsSeparator ?? ":";
690
+ if (path.length > 1 && nsSeparator) {
691
+ const ns = opts?.ns;
692
+ const nsArray = Array.isArray(ns) ? ns : null;
693
+ if (nsArray && nsArray.length > 1 && nsArray.slice(1).includes(path[0])) return `${path[0]}${nsSeparator}${path.slice(1).join(keySeparator)}`;
694
+ }
695
+ return path.join(keySeparator);
696
+ }
697
+ var checkedLoadedFor = {};
698
+ var shouldHandleAsObject = (res) => !isString(res) && typeof res !== "boolean" && typeof res !== "number";
699
+ var Translator = class Translator extends EventEmitter {
700
+ constructor(services, options = {}) {
701
+ super();
702
+ copy([
703
+ "resourceStore",
704
+ "languageUtils",
705
+ "pluralResolver",
706
+ "interpolator",
707
+ "backendConnector",
708
+ "i18nFormat",
709
+ "utils"
710
+ ], services, this);
711
+ this.options = options;
712
+ if (this.options.keySeparator === void 0) this.options.keySeparator = ".";
713
+ this.logger = baseLogger.create("translator");
714
+ }
715
+ changeLanguage(lng) {
716
+ if (lng) this.language = lng;
717
+ }
718
+ exists(key, o = { interpolation: {} }) {
719
+ const opt = { ...o };
720
+ if (key == null) return false;
721
+ const resolved = this.resolve(key, opt);
722
+ if (resolved?.res === void 0) return false;
723
+ const isObject = shouldHandleAsObject(resolved.res);
724
+ if (opt.returnObjects === false && isObject) return false;
725
+ return true;
726
+ }
727
+ extractFromKey(key, opt) {
728
+ let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator;
729
+ if (nsSeparator === void 0) nsSeparator = ":";
730
+ const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator;
731
+ let namespaces = opt.ns || this.options.defaultNS || [];
732
+ const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
733
+ const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
734
+ if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
735
+ const m = key.match(this.interpolator.nestingRegexp);
736
+ if (m && m.length > 0) return {
737
+ key,
738
+ namespaces: isString(namespaces) ? [namespaces] : namespaces
739
+ };
740
+ const parts = key.split(nsSeparator);
741
+ if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
742
+ key = parts.join(keySeparator);
743
+ }
744
+ return {
745
+ key,
746
+ namespaces: isString(namespaces) ? [namespaces] : namespaces
747
+ };
748
+ }
749
+ translate(keys, o, lastKey) {
750
+ let opt = typeof o === "object" ? { ...o } : o;
751
+ if (typeof opt !== "object" && this.options.overloadTranslationOptionHandler) opt = this.options.overloadTranslationOptionHandler(arguments);
752
+ if (typeof opt === "object") opt = { ...opt };
753
+ if (!opt) opt = {};
754
+ if (keys == null) return "";
755
+ if (typeof keys === "function") keys = keysFromSelector(keys, {
756
+ ...this.options,
757
+ ...opt
758
+ });
759
+ if (!Array.isArray(keys)) keys = [String(keys)];
760
+ keys = keys.map((k) => typeof k === "function" ? keysFromSelector(k, {
761
+ ...this.options,
762
+ ...opt
763
+ }) : String(k));
764
+ const returnDetails = opt.returnDetails !== void 0 ? opt.returnDetails : this.options.returnDetails;
765
+ const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator;
766
+ const { key, namespaces } = this.extractFromKey(keys[keys.length - 1], opt);
767
+ const namespace = namespaces[namespaces.length - 1];
768
+ let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator;
769
+ if (nsSeparator === void 0) nsSeparator = ":";
770
+ const lng = opt.lng || this.language;
771
+ const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
772
+ if (lng?.toLowerCase() === "cimode") {
773
+ if (appendNamespaceToCIMode) {
774
+ if (returnDetails) return {
775
+ res: `${namespace}${nsSeparator}${key}`,
776
+ usedKey: key,
777
+ exactUsedKey: key,
778
+ usedLng: lng,
779
+ usedNS: namespace,
780
+ usedParams: this.getUsedParamsDetails(opt)
781
+ };
782
+ return `${namespace}${nsSeparator}${key}`;
783
+ }
784
+ if (returnDetails) return {
785
+ res: key,
786
+ usedKey: key,
787
+ exactUsedKey: key,
788
+ usedLng: lng,
789
+ usedNS: namespace,
790
+ usedParams: this.getUsedParamsDetails(opt)
791
+ };
792
+ return key;
793
+ }
794
+ const resolved = this.resolve(keys, opt);
795
+ let res = resolved?.res;
796
+ const resUsedKey = resolved?.usedKey || key;
797
+ const resExactUsedKey = resolved?.exactUsedKey || key;
798
+ const noObject = [
799
+ "[object Number]",
800
+ "[object Function]",
801
+ "[object RegExp]"
802
+ ];
803
+ const joinArrays = opt.joinArrays !== void 0 ? opt.joinArrays : this.options.joinArrays;
804
+ const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
805
+ const needsPluralHandling = opt.count !== void 0 && !isString(opt.count);
806
+ const hasDefaultValue = Translator.hasDefaultValue(opt);
807
+ const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : "";
808
+ const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, { ordinal: false }) : "";
809
+ const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
810
+ const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
811
+ let resForObjHndl = res;
812
+ if (handleAsObjectInI18nFormat && !res && hasDefaultValue) resForObjHndl = defaultValue;
813
+ const handleAsObject = shouldHandleAsObject(resForObjHndl);
814
+ const resType = Object.prototype.toString.apply(resForObjHndl);
815
+ if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
816
+ if (!opt.returnObjects && !this.options.returnObjects) {
817
+ if (!this.options.returnedObjectHandler) this.logger.warn("accessing an object - but returnObjects options is not enabled!");
818
+ const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
819
+ ...opt,
820
+ ns: namespaces
821
+ }) : `key '${key} (${this.language})' returned an object instead of string.`;
822
+ if (returnDetails) {
823
+ resolved.res = r;
824
+ resolved.usedParams = this.getUsedParamsDetails(opt);
825
+ return resolved;
826
+ }
827
+ return r;
828
+ }
829
+ if (keySeparator) {
830
+ const resTypeIsArray = Array.isArray(resForObjHndl);
831
+ const copy = resTypeIsArray ? [] : {};
832
+ const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
833
+ for (const m in resForObjHndl) if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
834
+ const deepKey = `${newKeyToUse}${keySeparator}${m}`;
835
+ if (hasDefaultValue && !res) copy[m] = this.translate(deepKey, {
836
+ ...opt,
837
+ defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : void 0,
838
+ joinArrays: false,
839
+ ns: namespaces
840
+ });
841
+ else copy[m] = this.translate(deepKey, {
842
+ ...opt,
843
+ joinArrays: false,
844
+ ns: namespaces
845
+ });
846
+ if (copy[m] === deepKey) copy[m] = resForObjHndl[m];
847
+ }
848
+ res = copy;
849
+ }
850
+ } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
851
+ res = res.join(joinArrays);
852
+ if (res) res = this.extendTranslation(res, keys, opt, lastKey);
853
+ } else {
854
+ let usedDefault = false;
855
+ let usedKey = false;
856
+ if (!this.isValidLookup(res) && hasDefaultValue) {
857
+ usedDefault = true;
858
+ res = defaultValue;
859
+ }
860
+ if (!this.isValidLookup(res)) {
861
+ usedKey = true;
862
+ res = key;
863
+ }
864
+ const resForMissing = (opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey) && usedKey ? void 0 : res;
865
+ const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
866
+ if (usedKey || usedDefault || updateMissing) {
867
+ this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res);
868
+ if (keySeparator) {
869
+ const fk = this.resolve(key, {
870
+ ...opt,
871
+ keySeparator: false
872
+ });
873
+ if (fk && fk.res) this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.");
874
+ }
875
+ let lngs = [];
876
+ const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
877
+ if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) for (let i = 0; i < fallbackLngs.length; i++) lngs.push(fallbackLngs[i]);
878
+ else if (this.options.saveMissingTo === "all") lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
879
+ else lngs.push(opt.lng || this.language);
880
+ const send = (l, k, specificDefaultValue) => {
881
+ const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
882
+ if (this.options.missingKeyHandler) this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
883
+ else if (this.backendConnector?.saveMissing) this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
884
+ this.emit("missingKey", l, namespace, k, res);
885
+ };
886
+ if (this.options.saveMissing) if (this.options.saveMissingPlurals && needsPluralHandling) lngs.forEach((language) => {
887
+ const suffixes = this.pluralResolver.getSuffixes(language, opt);
888
+ if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) suffixes.push(`${this.options.pluralSeparator}zero`);
889
+ suffixes.forEach((suffix) => {
890
+ send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
891
+ });
892
+ });
893
+ else send(lngs, key, defaultValue);
894
+ }
895
+ res = this.extendTranslation(res, keys, opt, resolved, lastKey);
896
+ if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = `${namespace}${nsSeparator}${key}`;
897
+ if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : void 0, opt);
898
+ }
899
+ if (returnDetails) {
900
+ resolved.res = res;
901
+ resolved.usedParams = this.getUsedParamsDetails(opt);
902
+ return resolved;
903
+ }
904
+ return res;
905
+ }
906
+ extendTranslation(res, key, opt, resolved, lastKey) {
907
+ if (this.i18nFormat?.parse) res = this.i18nFormat.parse(res, {
908
+ ...this.options.interpolation.defaultVariables,
909
+ ...opt
910
+ }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, { resolved });
911
+ else if (!opt.skipInterpolation) {
912
+ if (opt.interpolation) this.interpolator.init({
913
+ ...opt,
914
+ interpolation: {
915
+ ...this.options.interpolation,
916
+ ...opt.interpolation
917
+ }
918
+ });
919
+ const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== void 0 ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
920
+ let nestBef;
921
+ if (skipOnVariables) {
922
+ const nb = res.match(this.interpolator.nestingRegexp);
923
+ nestBef = nb && nb.length;
924
+ }
925
+ let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
926
+ if (this.options.interpolation.defaultVariables) data = {
927
+ ...this.options.interpolation.defaultVariables,
928
+ ...data
929
+ };
930
+ res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
931
+ if (skipOnVariables) {
932
+ const na = res.match(this.interpolator.nestingRegexp);
933
+ const nestAft = na && na.length;
934
+ if (nestBef < nestAft) opt.nest = false;
935
+ }
936
+ if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
937
+ if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
938
+ if (lastKey?.[0] === args[0] && !opt.context) {
939
+ this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
940
+ return null;
941
+ }
942
+ return this.translate(...args, key);
943
+ }, opt);
944
+ if (opt.interpolation) this.interpolator.reset();
945
+ }
946
+ const postProcess = opt.postProcess || this.options.postProcess;
947
+ const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
948
+ if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
949
+ i18nResolved: {
950
+ ...resolved,
951
+ usedParams: this.getUsedParamsDetails(opt)
952
+ },
953
+ ...opt
954
+ } : opt, this);
955
+ return res;
956
+ }
957
+ resolve(keys, opt = {}) {
958
+ let found;
959
+ let usedKey;
960
+ let exactUsedKey;
961
+ let usedLng;
962
+ let usedNS;
963
+ if (isString(keys)) keys = [keys];
964
+ if (Array.isArray(keys)) keys = keys.map((k) => typeof k === "function" ? keysFromSelector(k, {
965
+ ...this.options,
966
+ ...opt
967
+ }) : k);
968
+ keys.forEach((k) => {
969
+ if (this.isValidLookup(found)) return;
970
+ const extracted = this.extractFromKey(k, opt);
971
+ const key = extracted.key;
972
+ usedKey = key;
973
+ let namespaces = extracted.namespaces;
974
+ if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
975
+ const needsPluralHandling = opt.count !== void 0 && !isString(opt.count);
976
+ const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
977
+ const needsContextHandling = opt.context !== void 0 && (isString(opt.context) || typeof opt.context === "number") && opt.context !== "";
978
+ const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
979
+ namespaces.forEach((ns) => {
980
+ if (this.isValidLookup(found)) return;
981
+ usedNS = ns;
982
+ if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
983
+ checkedLoadedFor[`${codes[0]}-${ns}`] = true;
984
+ this.logger.warn(`key "${usedKey}" for languages "${codes.join(", ")}" won't get resolved as namespace "${usedNS}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
985
+ }
986
+ codes.forEach((code) => {
987
+ if (this.isValidLookup(found)) return;
988
+ usedLng = code;
989
+ const finalKeys = [key];
990
+ if (this.i18nFormat?.addLookupKeys) this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
991
+ else {
992
+ let pluralSuffix;
993
+ if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
994
+ const zeroSuffix = `${this.options.pluralSeparator}zero`;
995
+ const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
996
+ if (needsPluralHandling) {
997
+ if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
998
+ finalKeys.push(key + pluralSuffix);
999
+ if (needsZeroSuffixLookup) finalKeys.push(key + zeroSuffix);
1000
+ }
1001
+ if (needsContextHandling) {
1002
+ const contextKey = `${key}${this.options.contextSeparator || "_"}${opt.context}`;
1003
+ finalKeys.push(contextKey);
1004
+ if (needsPluralHandling) {
1005
+ if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
1006
+ finalKeys.push(contextKey + pluralSuffix);
1007
+ if (needsZeroSuffixLookup) finalKeys.push(contextKey + zeroSuffix);
1008
+ }
1009
+ }
1010
+ }
1011
+ let possibleKey;
1012
+ while (possibleKey = finalKeys.pop()) if (!this.isValidLookup(found)) {
1013
+ exactUsedKey = possibleKey;
1014
+ found = this.getResource(code, ns, possibleKey, opt);
1015
+ }
1016
+ });
1017
+ });
1018
+ });
1019
+ return {
1020
+ res: found,
1021
+ usedKey,
1022
+ exactUsedKey,
1023
+ usedLng,
1024
+ usedNS
1025
+ };
1026
+ }
1027
+ isValidLookup(res) {
1028
+ return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
1029
+ }
1030
+ getResource(code, ns, key, options = {}) {
1031
+ if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
1032
+ return this.resourceStore.getResource(code, ns, key, options);
1033
+ }
1034
+ getUsedParamsDetails(options = {}) {
1035
+ const optionsKeys = [
1036
+ "defaultValue",
1037
+ "ordinal",
1038
+ "context",
1039
+ "replace",
1040
+ "lng",
1041
+ "lngs",
1042
+ "fallbackLng",
1043
+ "ns",
1044
+ "keySeparator",
1045
+ "nsSeparator",
1046
+ "returnObjects",
1047
+ "returnDetails",
1048
+ "joinArrays",
1049
+ "postProcess",
1050
+ "interpolation"
1051
+ ];
1052
+ const useOptionsReplaceForData = options.replace && !isString(options.replace);
1053
+ let data = useOptionsReplaceForData ? options.replace : options;
1054
+ if (useOptionsReplaceForData && typeof options.count !== "undefined") data.count = options.count;
1055
+ if (this.options.interpolation.defaultVariables) data = {
1056
+ ...this.options.interpolation.defaultVariables,
1057
+ ...data
1058
+ };
1059
+ if (!useOptionsReplaceForData) {
1060
+ data = { ...data };
1061
+ for (const key of optionsKeys) delete data[key];
1062
+ }
1063
+ return data;
1064
+ }
1065
+ static hasDefaultValue(options) {
1066
+ const prefix = "defaultValue";
1067
+ for (const option in options) if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, 12) && void 0 !== options[option]) return true;
1068
+ return false;
1069
+ }
1070
+ };
1071
+ var LanguageUtil = class {
1072
+ constructor(options) {
1073
+ this.options = options;
1074
+ this.supportedLngs = this.options.supportedLngs || false;
1075
+ this.logger = baseLogger.create("languageUtils");
1076
+ }
1077
+ getScriptPartFromCode(code) {
1078
+ code = getCleanedCode(code);
1079
+ if (!code || code.indexOf("-") < 0) return null;
1080
+ const p = code.split("-");
1081
+ if (p.length === 2) return null;
1082
+ p.pop();
1083
+ if (p[p.length - 1].toLowerCase() === "x") return null;
1084
+ return this.formatLanguageCode(p.join("-"));
1085
+ }
1086
+ getLanguagePartFromCode(code) {
1087
+ code = getCleanedCode(code);
1088
+ if (!code || code.indexOf("-") < 0) return code;
1089
+ const p = code.split("-");
1090
+ return this.formatLanguageCode(p[0]);
1091
+ }
1092
+ formatLanguageCode(code) {
1093
+ if (isString(code) && code.indexOf("-") > -1) {
1094
+ let formattedCode;
1095
+ try {
1096
+ formattedCode = Intl.getCanonicalLocales(code)[0];
1097
+ } catch (e) {}
1098
+ if (formattedCode && this.options.lowerCaseLng) formattedCode = formattedCode.toLowerCase();
1099
+ if (formattedCode) return formattedCode;
1100
+ if (this.options.lowerCaseLng) return code.toLowerCase();
1101
+ return code;
1102
+ }
1103
+ return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
1104
+ }
1105
+ isSupportedCode(code) {
1106
+ if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) code = this.getLanguagePartFromCode(code);
1107
+ return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
1108
+ }
1109
+ getBestMatchFromCodes(codes) {
1110
+ if (!codes) return null;
1111
+ let found;
1112
+ codes.forEach((code) => {
1113
+ if (found) return;
1114
+ const cleanedLng = this.formatLanguageCode(code);
1115
+ if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
1116
+ });
1117
+ if (!found && this.options.supportedLngs) codes.forEach((code) => {
1118
+ if (found) return;
1119
+ const lngScOnly = this.getScriptPartFromCode(code);
1120
+ if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
1121
+ const lngOnly = this.getLanguagePartFromCode(code);
1122
+ if (this.isSupportedCode(lngOnly)) return found = lngOnly;
1123
+ found = this.options.supportedLngs.find((supportedLng) => {
1124
+ if (supportedLng === lngOnly) return supportedLng;
1125
+ if (supportedLng.indexOf("-") < 0 && lngOnly.indexOf("-") < 0) return;
1126
+ if (supportedLng.indexOf("-") > 0 && lngOnly.indexOf("-") < 0 && supportedLng.substring(0, supportedLng.indexOf("-")) === lngOnly) return supportedLng;
1127
+ if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
1128
+ });
1129
+ });
1130
+ if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
1131
+ return found;
1132
+ }
1133
+ getFallbackCodes(fallbacks, code) {
1134
+ if (!fallbacks) return [];
1135
+ if (typeof fallbacks === "function") fallbacks = fallbacks(code);
1136
+ if (isString(fallbacks)) fallbacks = [fallbacks];
1137
+ if (Array.isArray(fallbacks)) return fallbacks;
1138
+ if (!code) return fallbacks.default || [];
1139
+ let found = fallbacks[code];
1140
+ if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
1141
+ if (!found) found = fallbacks[this.formatLanguageCode(code)];
1142
+ if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
1143
+ if (!found) found = fallbacks.default;
1144
+ return found || [];
1145
+ }
1146
+ toResolveHierarchy(code, fallbackCode) {
1147
+ const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
1148
+ const codes = [];
1149
+ const addCode = (c) => {
1150
+ if (!c) return;
1151
+ if (this.isSupportedCode(c)) codes.push(c);
1152
+ else this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
1153
+ };
1154
+ if (isString(code) && (code.indexOf("-") > -1 || code.indexOf("_") > -1)) {
1155
+ if (this.options.load !== "languageOnly") addCode(this.formatLanguageCode(code));
1156
+ if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") addCode(this.getScriptPartFromCode(code));
1157
+ if (this.options.load !== "currentOnly") addCode(this.getLanguagePartFromCode(code));
1158
+ } else if (isString(code)) addCode(this.formatLanguageCode(code));
1159
+ fallbackCodes.forEach((fc) => {
1160
+ if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
1161
+ });
1162
+ return codes;
1163
+ }
1164
+ };
1165
+ var suffixesOrder = {
1166
+ zero: 0,
1167
+ one: 1,
1168
+ two: 2,
1169
+ few: 3,
1170
+ many: 4,
1171
+ other: 5
1172
+ };
1173
+ var dummyRule = {
1174
+ select: (count) => count === 1 ? "one" : "other",
1175
+ resolvedOptions: () => ({ pluralCategories: ["one", "other"] })
1176
+ };
1177
+ var PluralResolver = class {
1178
+ constructor(languageUtils, options = {}) {
1179
+ this.languageUtils = languageUtils;
1180
+ this.options = options;
1181
+ this.logger = baseLogger.create("pluralResolver");
1182
+ this.pluralRulesCache = {};
1183
+ }
1184
+ clearCache() {
1185
+ this.pluralRulesCache = {};
1186
+ }
1187
+ getRule(code, options = {}) {
1188
+ const cleanedCode = getCleanedCode(code === "dev" ? "en" : code);
1189
+ const type = options.ordinal ? "ordinal" : "cardinal";
1190
+ const cacheKey = JSON.stringify({
1191
+ cleanedCode,
1192
+ type
1193
+ });
1194
+ if (cacheKey in this.pluralRulesCache) return this.pluralRulesCache[cacheKey];
1195
+ let rule;
1196
+ try {
1197
+ rule = new Intl.PluralRules(cleanedCode, { type });
1198
+ } catch (err) {
1199
+ if (typeof Intl === "undefined") {
1200
+ this.logger.error("No Intl support, please use an Intl polyfill!");
1201
+ return dummyRule;
1202
+ }
1203
+ if (!code.match(/-|_/)) return dummyRule;
1204
+ const lngPart = this.languageUtils.getLanguagePartFromCode(code);
1205
+ rule = this.getRule(lngPart, options);
1206
+ }
1207
+ this.pluralRulesCache[cacheKey] = rule;
1208
+ return rule;
1209
+ }
1210
+ needsPlural(code, options = {}) {
1211
+ let rule = this.getRule(code, options);
1212
+ if (!rule) rule = this.getRule("dev", options);
1213
+ return rule?.resolvedOptions().pluralCategories.length > 1;
1214
+ }
1215
+ getPluralFormsOfKey(code, key, options = {}) {
1216
+ return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`);
1217
+ }
1218
+ getSuffixes(code, options = {}) {
1219
+ let rule = this.getRule(code, options);
1220
+ if (!rule) rule = this.getRule("dev", options);
1221
+ if (!rule) return [];
1222
+ return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
1223
+ }
1224
+ getSuffix(code, count, options = {}) {
1225
+ const rule = this.getRule(code, options);
1226
+ if (rule) return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
1227
+ this.logger.warn(`no plural rule found for: ${code}`);
1228
+ return this.getSuffix("dev", count, options);
1229
+ }
1230
+ };
1231
+ var deepFindWithDefaults = (data, defaultData, key, keySeparator = ".", ignoreJSONStructure = true) => {
1232
+ let path = getPathWithDefaults(data, defaultData, key);
1233
+ if (!path && ignoreJSONStructure && isString(key)) {
1234
+ path = deepFind(data, key, keySeparator);
1235
+ if (path === void 0) path = deepFind(defaultData, key, keySeparator);
1236
+ }
1237
+ return path;
1238
+ };
1239
+ var regexSafe = (val) => val.replace(/\$/g, "$$$$");
1240
+ var Interpolator = class {
1241
+ constructor(options = {}) {
1242
+ this.logger = baseLogger.create("interpolator");
1243
+ this.options = options;
1244
+ this.format = options?.interpolation?.format || ((value) => value);
1245
+ this.init(options);
1246
+ }
1247
+ init(options = {}) {
1248
+ if (!options.interpolation) options.interpolation = { escapeValue: true };
1249
+ const { escape: escape$1, escapeValue, useRawValueToEscape, prefix, prefixEscaped, suffix, suffixEscaped, formatSeparator, unescapeSuffix, unescapePrefix, nestingPrefix, nestingPrefixEscaped, nestingSuffix, nestingSuffixEscaped, nestingOptionsSeparator, maxReplaces, alwaysFormat } = options.interpolation;
1250
+ this.escape = escape$1 !== void 0 ? escape$1 : escape;
1251
+ this.escapeValue = escapeValue !== void 0 ? escapeValue : true;
1252
+ this.useRawValueToEscape = useRawValueToEscape !== void 0 ? useRawValueToEscape : false;
1253
+ this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{";
1254
+ this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}";
1255
+ this.formatSeparator = formatSeparator || ",";
1256
+ this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix || "-";
1257
+ this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix || "";
1258
+ this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t(");
1259
+ this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")");
1260
+ this.nestingOptionsSeparator = nestingOptionsSeparator || ",";
1261
+ this.maxReplaces = maxReplaces || 1e3;
1262
+ this.alwaysFormat = alwaysFormat !== void 0 ? alwaysFormat : false;
1263
+ this.resetRegExp();
1264
+ }
1265
+ reset() {
1266
+ if (this.options) this.init(this.options);
1267
+ }
1268
+ resetRegExp() {
1269
+ const getOrResetRegExp = (existingRegExp, pattern) => {
1270
+ if (existingRegExp?.source === pattern) {
1271
+ existingRegExp.lastIndex = 0;
1272
+ return existingRegExp;
1273
+ }
1274
+ return new RegExp(pattern, "g");
1275
+ };
1276
+ this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
1277
+ this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
1278
+ this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
1279
+ }
1280
+ interpolate(str, data, lng, options) {
1281
+ let match;
1282
+ let value;
1283
+ let replaces;
1284
+ const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1285
+ const handleFormat = (key) => {
1286
+ if (key.indexOf(this.formatSeparator) < 0) {
1287
+ const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1288
+ return this.alwaysFormat ? this.format(path, void 0, lng, {
1289
+ ...options,
1290
+ ...data,
1291
+ interpolationkey: key
1292
+ }) : path;
1293
+ }
1294
+ const p = key.split(this.formatSeparator);
1295
+ const k = p.shift().trim();
1296
+ const f = p.join(this.formatSeparator).trim();
1297
+ return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1298
+ ...options,
1299
+ ...data,
1300
+ interpolationkey: k
1301
+ });
1302
+ };
1303
+ this.resetRegExp();
1304
+ const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
1305
+ const skipOnVariables = options?.interpolation?.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1306
+ [{
1307
+ regex: this.regexpUnescape,
1308
+ safeValue: (val) => regexSafe(val)
1309
+ }, {
1310
+ regex: this.regexp,
1311
+ safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1312
+ }].forEach((todo) => {
1313
+ replaces = 0;
1314
+ while (match = todo.regex.exec(str)) {
1315
+ const matchedVar = match[1].trim();
1316
+ value = handleFormat(matchedVar);
1317
+ if (value === void 0) if (typeof missingInterpolationHandler === "function") {
1318
+ const temp = missingInterpolationHandler(str, match, options);
1319
+ value = isString(temp) ? temp : "";
1320
+ } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) value = "";
1321
+ else if (skipOnVariables) {
1322
+ value = match[0];
1323
+ continue;
1324
+ } else {
1325
+ this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1326
+ value = "";
1327
+ }
1328
+ else if (!isString(value) && !this.useRawValueToEscape) value = makeString(value);
1329
+ const safeValue = todo.safeValue(value);
1330
+ str = str.replace(match[0], safeValue);
1331
+ if (skipOnVariables) {
1332
+ todo.regex.lastIndex += value.length;
1333
+ todo.regex.lastIndex -= match[0].length;
1334
+ } else todo.regex.lastIndex = 0;
1335
+ replaces++;
1336
+ if (replaces >= this.maxReplaces) break;
1337
+ }
1338
+ });
1339
+ return str;
1340
+ }
1341
+ nest(str, fc, options = {}) {
1342
+ let match;
1343
+ let value;
1344
+ let clonedOptions;
1345
+ const handleHasOptions = (key, inheritedOptions) => {
1346
+ const sep = this.nestingOptionsSeparator;
1347
+ if (key.indexOf(sep) < 0) return key;
1348
+ const c = key.split(new RegExp(`${regexEscape(sep)}[ ]*{`));
1349
+ let optionsString = `{${c[1]}`;
1350
+ key = c[0];
1351
+ optionsString = this.interpolate(optionsString, clonedOptions);
1352
+ const matchedSingleQuotes = optionsString.match(/'/g);
1353
+ const matchedDoubleQuotes = optionsString.match(/"/g);
1354
+ if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || (matchedDoubleQuotes?.length ?? 0) % 2 !== 0) optionsString = optionsString.replace(/'/g, "\"");
1355
+ try {
1356
+ clonedOptions = JSON.parse(optionsString);
1357
+ if (inheritedOptions) clonedOptions = {
1358
+ ...inheritedOptions,
1359
+ ...clonedOptions
1360
+ };
1361
+ } catch (e) {
1362
+ this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1363
+ return `${key}${sep}${optionsString}`;
1364
+ }
1365
+ if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
1366
+ return key;
1367
+ };
1368
+ while (match = this.nestingRegexp.exec(str)) {
1369
+ let formatters = [];
1370
+ clonedOptions = { ...options };
1371
+ clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
1372
+ clonedOptions.applyPostProcessor = false;
1373
+ delete clonedOptions.defaultValue;
1374
+ const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf("}") + 1 : match[1].indexOf(this.formatSeparator);
1375
+ if (keyEndIndex !== -1) {
1376
+ formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map((elem) => elem.trim()).filter(Boolean);
1377
+ match[1] = match[1].slice(0, keyEndIndex);
1378
+ }
1379
+ value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1380
+ if (value && match[0] === str && !isString(value)) return value;
1381
+ if (!isString(value)) value = makeString(value);
1382
+ if (!value) {
1383
+ this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1384
+ value = "";
1385
+ }
1386
+ if (formatters.length) value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1387
+ ...options,
1388
+ interpolationkey: match[1].trim()
1389
+ }), value.trim());
1390
+ str = str.replace(match[0], value);
1391
+ this.regexp.lastIndex = 0;
1392
+ }
1393
+ return str;
1394
+ }
1395
+ };
1396
+ var parseFormatStr = (formatStr) => {
1397
+ let formatName = formatStr.toLowerCase().trim();
1398
+ const formatOptions = {};
1399
+ if (formatStr.indexOf("(") > -1) {
1400
+ const p = formatStr.split("(");
1401
+ formatName = p[0].toLowerCase().trim();
1402
+ const optStr = p[1].substring(0, p[1].length - 1);
1403
+ if (formatName === "currency" && optStr.indexOf(":") < 0) {
1404
+ if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1405
+ } else if (formatName === "relativetime" && optStr.indexOf(":") < 0) {
1406
+ if (!formatOptions.range) formatOptions.range = optStr.trim();
1407
+ } else optStr.split(";").forEach((opt) => {
1408
+ if (opt) {
1409
+ const [key, ...rest] = opt.split(":");
1410
+ const val = rest.join(":").trim().replace(/^'+|'+$/g, "");
1411
+ const trimmedKey = key.trim();
1412
+ if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
1413
+ if (val === "false") formatOptions[trimmedKey] = false;
1414
+ if (val === "true") formatOptions[trimmedKey] = true;
1415
+ if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
1416
+ }
1417
+ });
1418
+ }
1419
+ return {
1420
+ formatName,
1421
+ formatOptions
1422
+ };
1423
+ };
1424
+ var createCachedFormatter = (fn) => {
1425
+ const cache = {};
1426
+ return (v, l, o) => {
1427
+ let optForCache = o;
1428
+ if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) optForCache = {
1429
+ ...optForCache,
1430
+ [o.interpolationkey]: void 0
1431
+ };
1432
+ const key = l + JSON.stringify(optForCache);
1433
+ let frm = cache[key];
1434
+ if (!frm) {
1435
+ frm = fn(getCleanedCode(l), o);
1436
+ cache[key] = frm;
1437
+ }
1438
+ return frm(v);
1439
+ };
1440
+ };
1441
+ var createNonCachedFormatter = (fn) => (v, l, o) => fn(getCleanedCode(l), o)(v);
1442
+ var Formatter = class {
1443
+ constructor(options = {}) {
1444
+ this.logger = baseLogger.create("formatter");
1445
+ this.options = options;
1446
+ this.init(options);
1447
+ }
1448
+ init(services, options = { interpolation: {} }) {
1449
+ this.formatSeparator = options.interpolation.formatSeparator || ",";
1450
+ const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
1451
+ this.formats = {
1452
+ number: cf((lng, opt) => {
1453
+ const formatter = new Intl.NumberFormat(lng, { ...opt });
1454
+ return (val) => formatter.format(val);
1455
+ }),
1456
+ currency: cf((lng, opt) => {
1457
+ const formatter = new Intl.NumberFormat(lng, {
1458
+ ...opt,
1459
+ style: "currency"
1460
+ });
1461
+ return (val) => formatter.format(val);
1462
+ }),
1463
+ datetime: cf((lng, opt) => {
1464
+ const formatter = new Intl.DateTimeFormat(lng, { ...opt });
1465
+ return (val) => formatter.format(val);
1466
+ }),
1467
+ relativetime: cf((lng, opt) => {
1468
+ const formatter = new Intl.RelativeTimeFormat(lng, { ...opt });
1469
+ return (val) => formatter.format(val, opt.range || "day");
1470
+ }),
1471
+ list: cf((lng, opt) => {
1472
+ const formatter = new Intl.ListFormat(lng, { ...opt });
1473
+ return (val) => formatter.format(val);
1474
+ })
1475
+ };
1476
+ }
1477
+ add(name, fc) {
1478
+ this.formats[name.toLowerCase().trim()] = fc;
1479
+ }
1480
+ addCached(name, fc) {
1481
+ this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1482
+ }
1483
+ format(value, format, lng, options = {}) {
1484
+ const formats = format.split(this.formatSeparator);
1485
+ if (formats.length > 1 && formats[0].indexOf("(") > 1 && formats[0].indexOf(")") < 0 && formats.find((f) => f.indexOf(")") > -1)) {
1486
+ const lastIndex = formats.findIndex((f) => f.indexOf(")") > -1);
1487
+ formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
20
1488
  }
1489
+ return formats.reduce((mem, f) => {
1490
+ const { formatName, formatOptions } = parseFormatStr(f);
1491
+ if (this.formats[formatName]) {
1492
+ let formatted = mem;
1493
+ try {
1494
+ const valOptions = options?.formatParams?.[options.interpolationkey] || {};
1495
+ const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1496
+ formatted = this.formats[formatName](mem, l, {
1497
+ ...formatOptions,
1498
+ ...options,
1499
+ ...valOptions
1500
+ });
1501
+ } catch (error) {
1502
+ this.logger.warn(error);
1503
+ }
1504
+ return formatted;
1505
+ } else this.logger.warn(`there was no format function for ${formatName}`);
1506
+ return mem;
1507
+ }, value);
1508
+ }
1509
+ };
1510
+ var removePending = (q, name) => {
1511
+ if (q.pending[name] !== void 0) {
1512
+ delete q.pending[name];
1513
+ q.pendingCount--;
21
1514
  }
22
1515
  };
1516
+ var Connector = class extends EventEmitter {
1517
+ constructor(backend, store, services, options = {}) {
1518
+ super();
1519
+ this.backend = backend;
1520
+ this.store = store;
1521
+ this.services = services;
1522
+ this.languageUtils = services.languageUtils;
1523
+ this.options = options;
1524
+ this.logger = baseLogger.create("backendConnector");
1525
+ this.waitingReads = [];
1526
+ this.maxParallelReads = options.maxParallelReads || 10;
1527
+ this.readingCalls = 0;
1528
+ this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1529
+ this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1530
+ this.state = {};
1531
+ this.queue = [];
1532
+ this.backend?.init?.(services, options.backend, options);
1533
+ }
1534
+ queueLoad(languages, namespaces, options, callback) {
1535
+ const toLoad = {};
1536
+ const pending = {};
1537
+ const toLoadLanguages = {};
1538
+ const toLoadNamespaces = {};
1539
+ languages.forEach((lng) => {
1540
+ let hasAllNamespaces = true;
1541
+ namespaces.forEach((ns) => {
1542
+ const name = `${lng}|${ns}`;
1543
+ if (!options.reload && this.store.hasResourceBundle(lng, ns)) this.state[name] = 2;
1544
+ else if (this.state[name] < 0);
1545
+ else if (this.state[name] === 1) {
1546
+ if (pending[name] === void 0) pending[name] = true;
1547
+ } else {
1548
+ this.state[name] = 1;
1549
+ hasAllNamespaces = false;
1550
+ if (pending[name] === void 0) pending[name] = true;
1551
+ if (toLoad[name] === void 0) toLoad[name] = true;
1552
+ if (toLoadNamespaces[ns] === void 0) toLoadNamespaces[ns] = true;
1553
+ }
1554
+ });
1555
+ if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1556
+ });
1557
+ if (Object.keys(toLoad).length || Object.keys(pending).length) this.queue.push({
1558
+ pending,
1559
+ pendingCount: Object.keys(pending).length,
1560
+ loaded: {},
1561
+ errors: [],
1562
+ callback
1563
+ });
1564
+ return {
1565
+ toLoad: Object.keys(toLoad),
1566
+ pending: Object.keys(pending),
1567
+ toLoadLanguages: Object.keys(toLoadLanguages),
1568
+ toLoadNamespaces: Object.keys(toLoadNamespaces)
1569
+ };
1570
+ }
1571
+ loaded(name, err, data) {
1572
+ const s = name.split("|");
1573
+ const lng = s[0];
1574
+ const ns = s[1];
1575
+ if (err) this.emit("failedLoading", lng, ns, err);
1576
+ if (!err && data) this.store.addResourceBundle(lng, ns, data, void 0, void 0, { skipCopy: true });
1577
+ this.state[name] = err ? -1 : 2;
1578
+ if (err && data) this.state[name] = 0;
1579
+ const loaded = {};
1580
+ this.queue.forEach((q) => {
1581
+ pushPath(q.loaded, [lng], ns);
1582
+ removePending(q, name);
1583
+ if (err) q.errors.push(err);
1584
+ if (q.pendingCount === 0 && !q.done) {
1585
+ Object.keys(q.loaded).forEach((l) => {
1586
+ if (!loaded[l]) loaded[l] = {};
1587
+ const loadedKeys = q.loaded[l];
1588
+ if (loadedKeys.length) loadedKeys.forEach((n) => {
1589
+ if (loaded[l][n] === void 0) loaded[l][n] = true;
1590
+ });
1591
+ });
1592
+ q.done = true;
1593
+ if (q.errors.length) q.callback(q.errors);
1594
+ else q.callback();
1595
+ }
1596
+ });
1597
+ this.emit("loaded", loaded);
1598
+ this.queue = this.queue.filter((q) => !q.done);
1599
+ }
1600
+ read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
1601
+ if (!lng.length) return callback(null, {});
1602
+ if (this.readingCalls >= this.maxParallelReads) {
1603
+ this.waitingReads.push({
1604
+ lng,
1605
+ ns,
1606
+ fcName,
1607
+ tried,
1608
+ wait,
1609
+ callback
1610
+ });
1611
+ return;
1612
+ }
1613
+ this.readingCalls++;
1614
+ const resolver = (err, data) => {
1615
+ this.readingCalls--;
1616
+ if (this.waitingReads.length > 0) {
1617
+ const next = this.waitingReads.shift();
1618
+ this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1619
+ }
1620
+ if (err && data && tried < this.maxRetries) {
1621
+ setTimeout(() => {
1622
+ this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1623
+ }, wait);
1624
+ return;
1625
+ }
1626
+ callback(err, data);
1627
+ };
1628
+ const fc = this.backend[fcName].bind(this.backend);
1629
+ if (fc.length === 2) {
1630
+ try {
1631
+ const r = fc(lng, ns);
1632
+ if (r && typeof r.then === "function") r.then((data) => resolver(null, data)).catch(resolver);
1633
+ else resolver(null, r);
1634
+ } catch (err) {
1635
+ resolver(err);
1636
+ }
1637
+ return;
1638
+ }
1639
+ return fc(lng, ns, resolver);
1640
+ }
1641
+ prepareLoading(languages, namespaces, options = {}, callback) {
1642
+ if (!this.backend) {
1643
+ this.logger.warn("No backend was added via i18next.use. Will not load resources.");
1644
+ return callback && callback();
1645
+ }
1646
+ if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
1647
+ if (isString(namespaces)) namespaces = [namespaces];
1648
+ const toLoad = this.queueLoad(languages, namespaces, options, callback);
1649
+ if (!toLoad.toLoad.length) {
1650
+ if (!toLoad.pending.length) callback();
1651
+ return null;
1652
+ }
1653
+ toLoad.toLoad.forEach((name) => {
1654
+ this.loadOne(name);
1655
+ });
1656
+ }
1657
+ load(languages, namespaces, callback) {
1658
+ this.prepareLoading(languages, namespaces, {}, callback);
1659
+ }
1660
+ reload(languages, namespaces, callback) {
1661
+ this.prepareLoading(languages, namespaces, { reload: true }, callback);
1662
+ }
1663
+ loadOne(name, prefix = "") {
1664
+ const s = name.split("|");
1665
+ const lng = s[0];
1666
+ const ns = s[1];
1667
+ this.read(lng, ns, "read", void 0, void 0, (err, data) => {
1668
+ if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1669
+ if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1670
+ this.loaded(name, err, data);
1671
+ });
1672
+ }
1673
+ saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {
1674
+ if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
1675
+ this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
1676
+ return;
1677
+ }
1678
+ if (key === void 0 || key === null || key === "") return;
1679
+ if (this.backend?.create) {
1680
+ const opts = {
1681
+ ...options,
1682
+ isUpdate
1683
+ };
1684
+ const fc = this.backend.create.bind(this.backend);
1685
+ if (fc.length < 6) try {
1686
+ let r;
1687
+ if (fc.length === 5) r = fc(languages, namespace, key, fallbackValue, opts);
1688
+ else r = fc(languages, namespace, key, fallbackValue);
1689
+ if (r && typeof r.then === "function") r.then((data) => clb(null, data)).catch(clb);
1690
+ else clb(null, r);
1691
+ } catch (err) {
1692
+ clb(err);
1693
+ }
1694
+ else fc(languages, namespace, key, fallbackValue, clb, opts);
1695
+ }
1696
+ if (!languages || !languages[0]) return;
1697
+ this.store.addResource(languages[0], namespace, key, fallbackValue);
1698
+ }
1699
+ };
1700
+ var get = () => ({
1701
+ debug: false,
1702
+ initAsync: true,
1703
+ ns: ["translation"],
1704
+ defaultNS: ["translation"],
1705
+ fallbackLng: ["dev"],
1706
+ fallbackNS: false,
1707
+ supportedLngs: false,
1708
+ nonExplicitSupportedLngs: false,
1709
+ load: "all",
1710
+ preload: false,
1711
+ simplifyPluralSuffix: true,
1712
+ keySeparator: ".",
1713
+ nsSeparator: ":",
1714
+ pluralSeparator: "_",
1715
+ contextSeparator: "_",
1716
+ partialBundledLanguages: false,
1717
+ saveMissing: false,
1718
+ updateMissing: false,
1719
+ saveMissingTo: "fallback",
1720
+ saveMissingPlurals: true,
1721
+ missingKeyHandler: false,
1722
+ missingInterpolationHandler: false,
1723
+ postProcess: false,
1724
+ postProcessPassResolved: false,
1725
+ returnNull: false,
1726
+ returnEmptyString: true,
1727
+ returnObjects: false,
1728
+ joinArrays: false,
1729
+ returnedObjectHandler: false,
1730
+ parseMissingKeyHandler: false,
1731
+ appendNamespaceToMissingKey: false,
1732
+ appendNamespaceToCIMode: false,
1733
+ overloadTranslationOptionHandler: (args) => {
1734
+ let ret = {};
1735
+ if (typeof args[1] === "object") ret = args[1];
1736
+ if (isString(args[1])) ret.defaultValue = args[1];
1737
+ if (isString(args[2])) ret.tDescription = args[2];
1738
+ if (typeof args[2] === "object" || typeof args[3] === "object") {
1739
+ const options = args[3] || args[2];
1740
+ Object.keys(options).forEach((key) => {
1741
+ ret[key] = options[key];
1742
+ });
1743
+ }
1744
+ return ret;
1745
+ },
1746
+ interpolation: {
1747
+ escapeValue: true,
1748
+ format: (value) => value,
1749
+ prefix: "{{",
1750
+ suffix: "}}",
1751
+ formatSeparator: ",",
1752
+ unescapePrefix: "-",
1753
+ nestingPrefix: "$t(",
1754
+ nestingSuffix: ")",
1755
+ nestingOptionsSeparator: ",",
1756
+ maxReplaces: 1e3,
1757
+ skipOnVariables: true
1758
+ },
1759
+ cacheInBuiltFormats: true
1760
+ });
1761
+ var transformOptions = (options) => {
1762
+ if (isString(options.ns)) options.ns = [options.ns];
1763
+ if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
1764
+ if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
1765
+ if (options.supportedLngs?.indexOf?.("cimode") < 0) options.supportedLngs = options.supportedLngs.concat(["cimode"]);
1766
+ if (typeof options.initImmediate === "boolean") options.initAsync = options.initImmediate;
1767
+ return options;
1768
+ };
1769
+ var noop = () => {};
1770
+ var bindMemberFunctions = (inst) => {
1771
+ Object.getOwnPropertyNames(Object.getPrototypeOf(inst)).forEach((mem) => {
1772
+ if (typeof inst[mem] === "function") inst[mem] = inst[mem].bind(inst);
1773
+ });
1774
+ };
1775
+ var SUPPORT_NOTICE_KEY = "__i18next_supportNoticeShown";
1776
+ var getSupportNoticeShown = () => {
1777
+ if (typeof globalThis !== "undefined" && !!globalThis[SUPPORT_NOTICE_KEY]) return true;
1778
+ if (typeof process !== "undefined" && process.env && process.env.I18NEXT_NO_SUPPORT_NOTICE) return true;
1779
+ if (typeof process !== "undefined" && process.env && process.env.NODE_ENV === "production") return true;
1780
+ return false;
1781
+ };
1782
+ var setSupportNoticeShown = () => {
1783
+ if (typeof globalThis !== "undefined") globalThis[SUPPORT_NOTICE_KEY] = true;
1784
+ };
1785
+ var usesLocize = (inst) => {
1786
+ if (inst?.modules?.backend?.name?.indexOf("Locize") > 0) return true;
1787
+ if (inst?.modules?.backend?.constructor?.name?.indexOf("Locize") > 0) return true;
1788
+ if (inst?.options?.backend?.backends) {
1789
+ if (inst.options.backend.backends.some((b) => b?.name?.indexOf("Locize") > 0 || b?.constructor?.name?.indexOf("Locize") > 0)) return true;
1790
+ }
1791
+ if (inst?.options?.backend?.projectId) return true;
1792
+ if (inst?.options?.backend?.backendOptions) {
1793
+ if (inst.options.backend.backendOptions.some((b) => b?.projectId)) return true;
1794
+ }
1795
+ return false;
1796
+ };
1797
+ var instance = class I18n extends EventEmitter {
1798
+ constructor(options = {}, callback) {
1799
+ super();
1800
+ this.options = transformOptions(options);
1801
+ this.services = {};
1802
+ this.logger = baseLogger;
1803
+ this.modules = { external: [] };
1804
+ bindMemberFunctions(this);
1805
+ if (callback && !this.isInitialized && !options.isClone) {
1806
+ if (!this.options.initAsync) {
1807
+ this.init(options, callback);
1808
+ return this;
1809
+ }
1810
+ setTimeout(() => {
1811
+ this.init(options, callback);
1812
+ }, 0);
1813
+ }
1814
+ }
1815
+ init(options = {}, callback) {
1816
+ this.isInitializing = true;
1817
+ if (typeof options === "function") {
1818
+ callback = options;
1819
+ options = {};
1820
+ }
1821
+ if (options.defaultNS == null && options.ns) {
1822
+ if (isString(options.ns)) options.defaultNS = options.ns;
1823
+ else if (options.ns.indexOf("translation") < 0) options.defaultNS = options.ns[0];
1824
+ }
1825
+ const defOpts = get();
1826
+ this.options = {
1827
+ ...defOpts,
1828
+ ...this.options,
1829
+ ...transformOptions(options)
1830
+ };
1831
+ this.options.interpolation = {
1832
+ ...defOpts.interpolation,
1833
+ ...this.options.interpolation
1834
+ };
1835
+ if (options.keySeparator !== void 0) this.options.userDefinedKeySeparator = options.keySeparator;
1836
+ if (options.nsSeparator !== void 0) this.options.userDefinedNsSeparator = options.nsSeparator;
1837
+ if (typeof this.options.overloadTranslationOptionHandler !== "function") this.options.overloadTranslationOptionHandler = defOpts.overloadTranslationOptionHandler;
1838
+ if (this.options.showSupportNotice !== false && !usesLocize(this) && !getSupportNoticeShown()) {
1839
+ if (typeof console !== "undefined" && typeof console.info !== "undefined") console.info("🌐 i18next is made possible by our own product, Locize — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙");
1840
+ setSupportNoticeShown();
1841
+ }
1842
+ const createClassOnDemand = (ClassOrObject) => {
1843
+ if (!ClassOrObject) return null;
1844
+ if (typeof ClassOrObject === "function") return new ClassOrObject();
1845
+ return ClassOrObject;
1846
+ };
1847
+ if (!this.options.isClone) {
1848
+ if (this.modules.logger) baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1849
+ else baseLogger.init(null, this.options);
1850
+ let formatter;
1851
+ if (this.modules.formatter) formatter = this.modules.formatter;
1852
+ else formatter = Formatter;
1853
+ const lu = new LanguageUtil(this.options);
1854
+ this.store = new ResourceStore(this.options.resources, this.options);
1855
+ const s = this.services;
1856
+ s.logger = baseLogger;
1857
+ s.resourceStore = this.store;
1858
+ s.languageUtils = lu;
1859
+ s.pluralResolver = new PluralResolver(lu, {
1860
+ prepend: this.options.pluralSeparator,
1861
+ simplifyPluralSuffix: this.options.simplifyPluralSuffix
1862
+ });
1863
+ if (this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format) this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);
1864
+ if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
1865
+ s.formatter = createClassOnDemand(formatter);
1866
+ if (s.formatter.init) s.formatter.init(s, this.options);
1867
+ this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1868
+ }
1869
+ s.interpolator = new Interpolator(this.options);
1870
+ s.utils = { hasLoadedNamespace: this.hasLoadedNamespace.bind(this) };
1871
+ s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1872
+ s.backendConnector.on("*", (event, ...args) => {
1873
+ this.emit(event, ...args);
1874
+ });
1875
+ if (this.modules.languageDetector) {
1876
+ s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1877
+ if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1878
+ }
1879
+ if (this.modules.i18nFormat) {
1880
+ s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1881
+ if (s.i18nFormat.init) s.i18nFormat.init(this);
1882
+ }
1883
+ this.translator = new Translator(this.services, this.options);
1884
+ this.translator.on("*", (event, ...args) => {
1885
+ this.emit(event, ...args);
1886
+ });
1887
+ this.modules.external.forEach((m) => {
1888
+ if (m.init) m.init(this);
1889
+ });
1890
+ }
1891
+ this.format = this.options.interpolation.format;
1892
+ if (!callback) callback = noop;
1893
+ if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
1894
+ const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1895
+ if (codes.length > 0 && codes[0] !== "dev") this.options.lng = codes[0];
1896
+ }
1897
+ if (!this.services.languageDetector && !this.options.lng) this.logger.warn("init: no languageDetector is used and no lng is defined");
1898
+ [
1899
+ "getResource",
1900
+ "hasResourceBundle",
1901
+ "getResourceBundle",
1902
+ "getDataByLanguage"
1903
+ ].forEach((fcName) => {
1904
+ this[fcName] = (...args) => this.store[fcName](...args);
1905
+ });
1906
+ [
1907
+ "addResource",
1908
+ "addResources",
1909
+ "addResourceBundle",
1910
+ "removeResourceBundle"
1911
+ ].forEach((fcName) => {
1912
+ this[fcName] = (...args) => {
1913
+ this.store[fcName](...args);
1914
+ return this;
1915
+ };
1916
+ });
1917
+ const deferred = defer();
1918
+ const load = () => {
1919
+ const finish = (err, t) => {
1920
+ this.isInitializing = false;
1921
+ if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn("init: i18next is already initialized. You should call init just once!");
1922
+ this.isInitialized = true;
1923
+ if (!this.options.isClone) this.logger.log("initialized", this.options);
1924
+ this.emit("initialized", this.options);
1925
+ deferred.resolve(t);
1926
+ callback(err, t);
1927
+ };
1928
+ if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
1929
+ this.changeLanguage(this.options.lng, finish);
1930
+ };
1931
+ if (this.options.resources || !this.options.initAsync) load();
1932
+ else setTimeout(load, 0);
1933
+ return deferred;
1934
+ }
1935
+ loadResources(language, callback = noop) {
1936
+ let usedCallback = callback;
1937
+ const usedLng = isString(language) ? language : this.language;
1938
+ if (typeof language === "function") usedCallback = language;
1939
+ if (!this.options.resources || this.options.partialBundledLanguages) {
1940
+ if (usedLng?.toLowerCase() === "cimode" && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
1941
+ const toLoad = [];
1942
+ const append = (lng) => {
1943
+ if (!lng) return;
1944
+ if (lng === "cimode") return;
1945
+ this.services.languageUtils.toResolveHierarchy(lng).forEach((l) => {
1946
+ if (l === "cimode") return;
1947
+ if (toLoad.indexOf(l) < 0) toLoad.push(l);
1948
+ });
1949
+ };
1950
+ if (!usedLng) this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach((l) => append(l));
1951
+ else append(usedLng);
1952
+ this.options.preload?.forEach?.((l) => append(l));
1953
+ this.services.backendConnector.load(toLoad, this.options.ns, (e) => {
1954
+ if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
1955
+ usedCallback(e);
1956
+ });
1957
+ } else usedCallback(null);
1958
+ }
1959
+ reloadResources(lngs, ns, callback) {
1960
+ const deferred = defer();
1961
+ if (typeof lngs === "function") {
1962
+ callback = lngs;
1963
+ lngs = void 0;
1964
+ }
1965
+ if (typeof ns === "function") {
1966
+ callback = ns;
1967
+ ns = void 0;
1968
+ }
1969
+ if (!lngs) lngs = this.languages;
1970
+ if (!ns) ns = this.options.ns;
1971
+ if (!callback) callback = noop;
1972
+ this.services.backendConnector.reload(lngs, ns, (err) => {
1973
+ deferred.resolve();
1974
+ callback(err);
1975
+ });
1976
+ return deferred;
1977
+ }
1978
+ use(module) {
1979
+ if (!module) throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
1980
+ if (!module.type) throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
1981
+ if (module.type === "backend") this.modules.backend = module;
1982
+ if (module.type === "logger" || module.log && module.warn && module.error) this.modules.logger = module;
1983
+ if (module.type === "languageDetector") this.modules.languageDetector = module;
1984
+ if (module.type === "i18nFormat") this.modules.i18nFormat = module;
1985
+ if (module.type === "postProcessor") postProcessor.addPostProcessor(module);
1986
+ if (module.type === "formatter") this.modules.formatter = module;
1987
+ if (module.type === "3rdParty") this.modules.external.push(module);
1988
+ return this;
1989
+ }
1990
+ setResolvedLanguage(l) {
1991
+ if (!l || !this.languages) return;
1992
+ if (["cimode", "dev"].indexOf(l) > -1) return;
1993
+ for (let li = 0; li < this.languages.length; li++) {
1994
+ const lngInLngs = this.languages[li];
1995
+ if (["cimode", "dev"].indexOf(lngInLngs) > -1) continue;
1996
+ if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
1997
+ this.resolvedLanguage = lngInLngs;
1998
+ break;
1999
+ }
2000
+ }
2001
+ if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {
2002
+ this.resolvedLanguage = l;
2003
+ this.languages.unshift(l);
2004
+ }
2005
+ }
2006
+ changeLanguage(lng, callback) {
2007
+ this.isLanguageChangingTo = lng;
2008
+ const deferred = defer();
2009
+ this.emit("languageChanging", lng);
2010
+ const setLngProps = (l) => {
2011
+ this.language = l;
2012
+ this.languages = this.services.languageUtils.toResolveHierarchy(l);
2013
+ this.resolvedLanguage = void 0;
2014
+ this.setResolvedLanguage(l);
2015
+ };
2016
+ const done = (err, l) => {
2017
+ if (l) {
2018
+ if (this.isLanguageChangingTo === lng) {
2019
+ setLngProps(l);
2020
+ this.translator.changeLanguage(l);
2021
+ this.isLanguageChangingTo = void 0;
2022
+ this.emit("languageChanged", l);
2023
+ this.logger.log("languageChanged", l);
2024
+ }
2025
+ } else this.isLanguageChangingTo = void 0;
2026
+ deferred.resolve((...args) => this.t(...args));
2027
+ if (callback) callback(err, (...args) => this.t(...args));
2028
+ };
2029
+ const setLng = (lngs) => {
2030
+ if (!lng && !lngs && this.services.languageDetector) lngs = [];
2031
+ const fl = isString(lngs) ? lngs : lngs && lngs[0];
2032
+ const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
2033
+ if (l) {
2034
+ if (!this.language) setLngProps(l);
2035
+ if (!this.translator.language) this.translator.changeLanguage(l);
2036
+ this.services.languageDetector?.cacheUserLanguage?.(l);
2037
+ }
2038
+ this.loadResources(l, (err) => {
2039
+ done(err, l);
2040
+ });
2041
+ };
2042
+ if (!lng && this.services.languageDetector && !this.services.languageDetector.async) setLng(this.services.languageDetector.detect());
2043
+ else if (!lng && this.services.languageDetector && this.services.languageDetector.async) if (this.services.languageDetector.detect.length === 0) this.services.languageDetector.detect().then(setLng);
2044
+ else this.services.languageDetector.detect(setLng);
2045
+ else setLng(lng);
2046
+ return deferred;
2047
+ }
2048
+ getFixedT(lng, ns, keyPrefix) {
2049
+ const fixedT = (key, opts, ...rest) => {
2050
+ let o;
2051
+ if (typeof opts !== "object") o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2052
+ else o = { ...opts };
2053
+ o.lng = o.lng || fixedT.lng;
2054
+ o.lngs = o.lngs || fixedT.lngs;
2055
+ o.ns = o.ns || fixedT.ns;
2056
+ if (o.keyPrefix !== "") o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
2057
+ const selectorOpts = {
2058
+ ...this.options,
2059
+ ...o
2060
+ };
2061
+ if (typeof o.keyPrefix === "function") o.keyPrefix = keysFromSelector(o.keyPrefix, selectorOpts);
2062
+ const keySeparator = this.options.keySeparator || ".";
2063
+ let resultKey;
2064
+ if (o.keyPrefix && Array.isArray(key)) resultKey = key.map((k) => {
2065
+ if (typeof k === "function") k = keysFromSelector(k, selectorOpts);
2066
+ return `${o.keyPrefix}${keySeparator}${k}`;
2067
+ });
2068
+ else {
2069
+ if (typeof key === "function") key = keysFromSelector(key, selectorOpts);
2070
+ resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
2071
+ }
2072
+ return this.t(resultKey, o);
2073
+ };
2074
+ if (isString(lng)) fixedT.lng = lng;
2075
+ else fixedT.lngs = lng;
2076
+ fixedT.ns = ns;
2077
+ fixedT.keyPrefix = keyPrefix;
2078
+ return fixedT;
2079
+ }
2080
+ t(...args) {
2081
+ return this.translator?.translate(...args);
2082
+ }
2083
+ exists(...args) {
2084
+ return this.translator?.exists(...args);
2085
+ }
2086
+ setDefaultNamespace(ns) {
2087
+ this.options.defaultNS = ns;
2088
+ }
2089
+ hasLoadedNamespace(ns, options = {}) {
2090
+ if (!this.isInitialized) {
2091
+ this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
2092
+ return false;
2093
+ }
2094
+ if (!this.languages || !this.languages.length) {
2095
+ this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
2096
+ return false;
2097
+ }
2098
+ const lng = options.lng || this.resolvedLanguage || this.languages[0];
2099
+ const fallbackLng = this.options ? this.options.fallbackLng : false;
2100
+ const lastLng = this.languages[this.languages.length - 1];
2101
+ if (lng.toLowerCase() === "cimode") return true;
2102
+ const loadNotPending = (l, n) => {
2103
+ const loadState = this.services.backendConnector.state[`${l}|${n}`];
2104
+ return loadState === -1 || loadState === 0 || loadState === 2;
2105
+ };
2106
+ if (options.precheck) {
2107
+ const preResult = options.precheck(this, loadNotPending);
2108
+ if (preResult !== void 0) return preResult;
2109
+ }
2110
+ if (this.hasResourceBundle(lng, ns)) return true;
2111
+ if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2112
+ if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2113
+ return false;
2114
+ }
2115
+ loadNamespaces(ns, callback) {
2116
+ const deferred = defer();
2117
+ if (!this.options.ns) {
2118
+ if (callback) callback();
2119
+ return Promise.resolve();
2120
+ }
2121
+ if (isString(ns)) ns = [ns];
2122
+ ns.forEach((n) => {
2123
+ if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2124
+ });
2125
+ this.loadResources((err) => {
2126
+ deferred.resolve();
2127
+ if (callback) callback(err);
2128
+ });
2129
+ return deferred;
2130
+ }
2131
+ loadLanguages(lngs, callback) {
2132
+ const deferred = defer();
2133
+ if (isString(lngs)) lngs = [lngs];
2134
+ const preloaded = this.options.preload || [];
2135
+ const newLngs = lngs.filter((lng) => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
2136
+ if (!newLngs.length) {
2137
+ if (callback) callback();
2138
+ return Promise.resolve();
2139
+ }
2140
+ this.options.preload = preloaded.concat(newLngs);
2141
+ this.loadResources((err) => {
2142
+ deferred.resolve();
2143
+ if (callback) callback(err);
2144
+ });
2145
+ return deferred;
2146
+ }
2147
+ dir(lng) {
2148
+ if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
2149
+ if (!lng) return "rtl";
2150
+ try {
2151
+ const l = new Intl.Locale(lng);
2152
+ if (l && l.getTextInfo) {
2153
+ const ti = l.getTextInfo();
2154
+ if (ti && ti.direction) return ti.direction;
2155
+ }
2156
+ } catch (e) {}
2157
+ const rtlLngs = [
2158
+ "ar",
2159
+ "shu",
2160
+ "sqr",
2161
+ "ssh",
2162
+ "xaa",
2163
+ "yhd",
2164
+ "yud",
2165
+ "aao",
2166
+ "abh",
2167
+ "abv",
2168
+ "acm",
2169
+ "acq",
2170
+ "acw",
2171
+ "acx",
2172
+ "acy",
2173
+ "adf",
2174
+ "ads",
2175
+ "aeb",
2176
+ "aec",
2177
+ "afb",
2178
+ "ajp",
2179
+ "apc",
2180
+ "apd",
2181
+ "arb",
2182
+ "arq",
2183
+ "ars",
2184
+ "ary",
2185
+ "arz",
2186
+ "auz",
2187
+ "avl",
2188
+ "ayh",
2189
+ "ayl",
2190
+ "ayn",
2191
+ "ayp",
2192
+ "bbz",
2193
+ "pga",
2194
+ "he",
2195
+ "iw",
2196
+ "ps",
2197
+ "pbt",
2198
+ "pbu",
2199
+ "pst",
2200
+ "prp",
2201
+ "prd",
2202
+ "ug",
2203
+ "ur",
2204
+ "ydd",
2205
+ "yds",
2206
+ "yih",
2207
+ "ji",
2208
+ "yi",
2209
+ "hbo",
2210
+ "men",
2211
+ "xmn",
2212
+ "fa",
2213
+ "jpr",
2214
+ "peo",
2215
+ "pes",
2216
+ "prs",
2217
+ "dv",
2218
+ "sam",
2219
+ "ckb"
2220
+ ];
2221
+ const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
2222
+ if (lng.toLowerCase().indexOf("-latn") > 1) return "ltr";
2223
+ return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
2224
+ }
2225
+ static createInstance(options = {}, callback) {
2226
+ const instance = new I18n(options, callback);
2227
+ instance.createInstance = I18n.createInstance;
2228
+ return instance;
2229
+ }
2230
+ cloneInstance(options = {}, callback = noop) {
2231
+ const forkResourceStore = options.forkResourceStore;
2232
+ if (forkResourceStore) delete options.forkResourceStore;
2233
+ const mergedOptions = {
2234
+ ...this.options,
2235
+ ...options,
2236
+ isClone: true
2237
+ };
2238
+ const clone = new I18n(mergedOptions);
2239
+ if (options.debug !== void 0 || options.prefix !== void 0) clone.logger = clone.logger.clone(options);
2240
+ [
2241
+ "store",
2242
+ "services",
2243
+ "language"
2244
+ ].forEach((m) => {
2245
+ clone[m] = this[m];
2246
+ });
2247
+ clone.services = { ...this.services };
2248
+ clone.services.utils = { hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone) };
2249
+ if (forkResourceStore) {
2250
+ clone.store = new ResourceStore(Object.keys(this.store.data).reduce((prev, l) => {
2251
+ prev[l] = { ...this.store.data[l] };
2252
+ prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
2253
+ acc[n] = { ...prev[l][n] };
2254
+ return acc;
2255
+ }, prev[l]);
2256
+ return prev;
2257
+ }, {}), mergedOptions);
2258
+ clone.services.resourceStore = clone.store;
2259
+ }
2260
+ if (options.interpolation) {
2261
+ const mergedInterpolation = {
2262
+ ...get().interpolation,
2263
+ ...this.options.interpolation,
2264
+ ...options.interpolation
2265
+ };
2266
+ const mergedForInterpolator = {
2267
+ ...mergedOptions,
2268
+ interpolation: mergedInterpolation
2269
+ };
2270
+ clone.services.interpolator = new Interpolator(mergedForInterpolator);
2271
+ }
2272
+ clone.translator = new Translator(clone.services, mergedOptions);
2273
+ clone.translator.on("*", (event, ...args) => {
2274
+ clone.emit(event, ...args);
2275
+ });
2276
+ clone.init(mergedOptions, callback);
2277
+ clone.translator.options = mergedOptions;
2278
+ clone.translator.backendConnector.services.utils = { hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone) };
2279
+ return clone;
2280
+ }
2281
+ toJSON() {
2282
+ return {
2283
+ options: this.options,
2284
+ store: this.store,
2285
+ language: this.language,
2286
+ languages: this.languages,
2287
+ resolvedLanguage: this.resolvedLanguage
2288
+ };
2289
+ }
2290
+ }.createInstance();
2291
+ instance.createInstance;
2292
+ instance.dir;
2293
+ instance.init;
2294
+ instance.loadResources;
2295
+ instance.reloadResources;
2296
+ instance.use;
2297
+ instance.changeLanguage;
2298
+ instance.getFixedT;
2299
+ instance.t;
2300
+ instance.exists;
2301
+ instance.setDefaultNamespace;
2302
+ instance.hasLoadedNamespace;
2303
+ instance.loadNamespaces;
2304
+ instance.loadLanguages;
2305
+ //#endregion
2306
+ //#region ../../shared/translator/dist/index.js
2307
+ instance.init({
2308
+ fallbackLng: "en",
2309
+ lng: "en",
2310
+ showSupportNotice: !1,
2311
+ resources: {
2312
+ en: e$1,
2313
+ es: e
2314
+ }
2315
+ });
2316
+ //#endregion
2317
+ //#region src/i18n.ts
2318
+ var { translator } = {
2319
+ translator: {
2320
+ ...instance,
2321
+ t: (e, t) => {
2322
+ let { lng: r } = t;
2323
+ switch (r) {
2324
+ case "en_US":
2325
+ case "en-US":
2326
+ t.lng = "en";
2327
+ break;
2328
+ case "es_ES":
2329
+ case "es-ES":
2330
+ case "es_MX":
2331
+ case "es-MX":
2332
+ t.lng = "es";
2333
+ break;
2334
+ default: break;
2335
+ }
2336
+ return instance.t(e, {
2337
+ lng: r,
2338
+ ...t
2339
+ });
2340
+ }
2341
+ },
2342
+ languageOptions: [{
2343
+ value: "en_US",
2344
+ label: "English (US)"
2345
+ }, {
2346
+ value: "es_ES",
2347
+ label: "Spanish"
2348
+ }]
2349
+ };
2350
+ /**
2351
+ * A learner-facing string in `language`, the model's `language`. i18next falls
2352
+ * back to English for a language or key it does not hold. Values are not
2353
+ * HTML-escaped: they are circle and tile names, and Svelte escapes what it
2354
+ * renders.
2355
+ */
2356
+ function t(key, language, values = {}) {
2357
+ return translator.t(`translation:vennClassification:${key}`, {
2358
+ lng: language,
2359
+ ...values,
2360
+ interpolation: { escapeValue: false }
2361
+ });
2362
+ }
23
2363
  //#endregion
24
2364
  //#region src/controller/region.ts
25
2365
  /**
2366
+ * Region helpers for the venn-classification controller.
2367
+ *
2368
+ * A region is a sorted-ascending array of circle indexes. These helpers deal
2369
+ * with keying, labelling, and equality in a layout-agnostic way so that both
2370
+ * the controller (for scoring / validation) and delivery (for rendering)
2371
+ * can share them.
2372
+ */
2373
+ /**
26
2374
  * Returns the canonical region key: sorted-ascending indexes joined by commas.
27
2375
  * Outside / "neither" region is the empty string.
28
2376
  */
@@ -74,16 +2422,19 @@ function enumerateRegions(circleCount) {
74
2422
  * [0,1] -> "<X> and <Y>"
75
2423
  * [0,1,2] -> "<X> and <Y> and <Z>"
76
2424
  */
77
- function composeRegionLabel(circles, region) {
2425
+ function composeRegionLabel(circles, region, language) {
78
2426
  const norm = normalizeRegion(region);
79
- const labels = norm.map((i) => circles[i]?.label ?? `Set ${i + 1}`);
80
- const circleCount = circles.length;
2427
+ const setLabel = (i) => circles[i]?.label ?? t("setNumber", language, { number: i + 1 });
2428
+ const labels = norm.map(setLabel);
81
2429
  if (norm.length === 0) {
82
- if (circleCount === 2) return `Neither ${circles[0]?.label ?? "Set 1"} nor ${circles[1]?.label ?? "Set 2"}`;
83
- return `None of ${circles.map((c, i) => c?.label ?? `Set ${i + 1}`).join(", ")}`;
2430
+ if (circles.length === 2) return t("regionNeither", language, {
2431
+ first: setLabel(0),
2432
+ second: setLabel(1)
2433
+ });
2434
+ return t("regionNoneOf", language, { sets: circles.map((_, i) => setLabel(i)).join(", ") });
84
2435
  }
85
- if (norm.length === 1) return `${labels[0]} only`;
86
- return labels.join(" and ");
2436
+ if (norm.length === 1) return t("regionOnly", language, { set: labels[0] });
2437
+ return labels.join(t("regionAndSeparator", language));
87
2438
  }
88
2439
  /**
89
2440
  * Resolve the label for a region, preferring an author-supplied override from
@@ -94,7 +2445,7 @@ function getRegionLabel(model, region) {
94
2445
  const key = regionKey(region);
95
2446
  const override = model.regionLabels?.[key];
96
2447
  if (typeof override === "string" && override.trim().length > 0) return override;
97
- return composeRegionLabel(model.circles ?? [], region);
2448
+ return composeRegionLabel(model.circles ?? [], region, model.language);
98
2449
  }
99
2450
  //#endregion
100
2451
  //#region src/controller/index.ts
@@ -103,8 +2454,7 @@ function getRegionLabel(model, region) {
103
2454
  * The data model is N-generic; widening to 3-set delivery is a one-line change
104
2455
  * plus the 3-set layout/picker once that work ships.
105
2456
  */
106
- var SUPPORTED_CIRCLE_COUNTS = new Set([2]);
107
- var isEmptyObject = (value) => !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
2457
+ var SUPPORTED_CIRCLE_COUNTS = /* @__PURE__ */ new Set([2]);
108
2458
  function tilePlainLabel(label) {
109
2459
  return String(label ?? "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
110
2460
  }
@@ -167,32 +2517,29 @@ function getCorrectnessMap(model, session) {
167
2517
  for (const tile of model.tiles ?? []) out[tile.id] = getTileCorrectness(tile, placements[tile.id] ?? null);
168
2518
  return out;
169
2519
  }
2520
+ /**
2521
+ * The scoring policy in force: the model's `scoringPolicy`, overridden to
2522
+ * all-or-nothing by `env.partialScoring === false` - the rule the React
2523
+ * elements apply through `partialScoring.enabled(model, env)`.
2524
+ */
2525
+ function effectiveScoringPolicy(model, env) {
2526
+ if (model.scoringPolicy === "allOrNothing" || env?.partialScoring === false) return "allOrNothing";
2527
+ return "partialPerTile";
2528
+ }
2529
+ var EMPTY_OUTCOME = {
2530
+ score: 0,
2531
+ empty: true,
2532
+ traceLog: ["Student did not place any tiles. Score is 0."]
2533
+ };
2534
+ /**
2535
+ * Score a session. Scores in every mode, as multiple-choice does: a player
2536
+ * calls this with the env it scores under, not only `evaluate`.
2537
+ */
170
2538
  function outcome(question, session, env = {}) {
171
2539
  return new Promise((resolve) => {
172
- if (!session || isEmptyObject(session) || !session.placements || Object.keys(session.placements).length === 0) {
173
- resolve({
174
- score: 0,
175
- empty: true
176
- });
177
- return;
178
- }
179
- if (env.mode !== "evaluate") {
180
- resolve({
181
- score: void 0,
182
- completed: void 0
183
- });
184
- return;
185
- }
186
2540
  const model = createDefaultModel(question || void 0);
187
- const tiles = model.tiles || [];
188
- if (tiles.length === 0) {
189
- resolve({
190
- score: 0,
191
- empty: true
192
- });
193
- return;
194
- }
195
- const placements = session.placements || {};
2541
+ const tiles = model.tiles;
2542
+ const placements = session?.placements ?? {};
196
2543
  let correct = 0;
197
2544
  let answered = 0;
198
2545
  for (const tile of tiles) {
@@ -203,16 +2550,22 @@ function outcome(question, session, env = {}) {
203
2550
  }
204
2551
  if (answered === 0) {
205
2552
  resolve({
206
- score: 0,
207
- empty: true
2553
+ ...EMPTY_OUTCOME,
2554
+ traceLog: [...EMPTY_OUTCOME.traceLog]
208
2555
  });
209
2556
  return;
210
2557
  }
211
- if ((model.scoringPolicy === "allOrNothing" ? "allOrNothing" : "partialPerTile") === "allOrNothing") {
212
- resolve({ score: correct === tiles.length ? 1 : 0 });
213
- return;
214
- }
215
- resolve({ score: correct / tiles.length });
2558
+ const policy = effectiveScoringPolicy(model, env);
2559
+ const score = policy === "allOrNothing" ? correct === tiles.length ? 1 : 0 : Number.parseFloat((correct / tiles.length).toFixed(2));
2560
+ resolve({
2561
+ score,
2562
+ empty: false,
2563
+ traceLog: [
2564
+ `Student placed ${answered} of ${tiles.length} tile(s); ${correct} in the correct region.`,
2565
+ `Score calculated using ${policy === "allOrNothing" ? "all-or-nothing" : "partial"} scoring.`,
2566
+ `Final score: ${score}.`
2567
+ ]
2568
+ });
216
2569
  });
217
2570
  }
218
2571
  /**
@@ -242,6 +2595,7 @@ function model(question, session, env = {}) {
242
2595
  }),
243
2596
  regionLabels: { ...normalizedQuestion.regionLabels || {} },
244
2597
  scoringPolicy: normalizedQuestion.scoringPolicy ?? "partialPerTile",
2598
+ language: normalizedQuestion.language,
245
2599
  disabled: safeEnv.mode !== "gather",
246
2600
  mode: safeEnv.mode,
247
2601
  env: safeEnv
@@ -252,10 +2606,8 @@ function model(question, session, env = {}) {
252
2606
  out.correctRegionsById = correctRegionsById;
253
2607
  out.correctness = getCorrectnessMap(normalizedQuestion, session);
254
2608
  }
255
- if (safeEnv.role === "instructor" && (safeEnv.mode === "view" || safeEnv.mode === "evaluate")) {
256
- const anyQ = normalizedQuestion;
257
- out.teacherInstructions = anyQ.teacherInstructionsEnabled ? anyQ.teacherInstructions ?? null : null;
258
- } else out.teacherInstructions = null;
2609
+ if (safeEnv.role === "instructor" && (safeEnv.mode === "view" || safeEnv.mode === "evaluate")) out.teacherInstructions = normalizedQuestion.teacherInstructionsEnabled ? normalizedQuestion.teacherInstructions ?? null : null;
2610
+ else out.teacherInstructions = null;
259
2611
  resolve(out);
260
2612
  });
261
2613
  }
@@ -270,7 +2622,6 @@ function createCorrectResponseSession(question, env = {}) {
270
2622
  for (const tile of model.tiles) placements[tile.id] = normalizeRegion(tile.correctRegion);
271
2623
  resolve({
272
2624
  id: "1",
273
- element: "venn-classification",
274
2625
  placements,
275
2626
  completed: true
276
2627
  });
@@ -350,12 +2701,11 @@ function buildPreviewSession(model) {
350
2701
  for (const tile of m.tiles) placements[tile.id] = normalizeRegion(tile.correctRegion);
351
2702
  return {
352
2703
  id: "preview",
353
- element: "venn-classification",
354
2704
  placements,
355
2705
  completed: true
356
2706
  };
357
2707
  }
358
2708
  //#endregion
359
- export { SUPPORTED_CIRCLE_COUNTS, buildPreviewSession, composeRegionLabel, createCorrectResponseSession, createDefaultModel, enumerateRegions, getCorrectnessMap, getRegionLabel, getTileCorrectness, isComplete, model, normalizeRegion, normalizeSession, outcome, regionKey, regionsEqual, validate };
2709
+ export { SUPPORTED_CIRCLE_COUNTS, buildPreviewSession, composeRegionLabel, createCorrectResponseSession, createDefaultModel, effectiveScoringPolicy, enumerateRegions, getCorrectnessMap, getRegionLabel, getTileCorrectness, isComplete, model, normalizeRegion, normalizeSession, outcome, regionKey, regionsEqual, validate };
360
2710
 
361
2711
  //# sourceMappingURL=index.js.map