kaleidl 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,621 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Engine = exports.Resolver = exports.Formatters = exports.BUILTIN_SEQUENCE_SPECS = exports.SequenceExhaustedError = exports.FLUENT_MAX_DEPTH = exports.LABEL_VOCABULARY = exports.ResolutionError = void 0;
4
+ exports.ref = ref;
5
+ exports.refs = refs;
6
+ exports.messageTable = messageTable;
7
+ exports.resolveMessage = resolveMessage;
8
+ exports.render = render;
9
+ exports.loadProfile = loadProfile;
10
+ /**
11
+ * kaleidl — MN 112 labeling engine (TypeScript port of the Ruby kaleidl
12
+ * reference). Conformance contract: metanorma/ladl-testsuite.
13
+ *
14
+ * Faithful port of Ladl::Runtime::Engine: the element's label resolves
15
+ * through the association chain (declared context first, then ancestors
16
+ * nearest-first; contexts that bind no labeller for the type are
17
+ * skipped — they scope but do not label), counters are scoped by the
18
+ * declaring carrier element and restart per hierarchical scope, %pn
19
+ * chains through the labeller parent tree with an element-type
20
+ * fallback, and templates render %n, %pn, %parent, %self with {key}
21
+ * vocabulary tokens resolved through the host labels dictionary and
22
+ * the English default vocabulary.
23
+ */
24
+ const yaml = require("js-yaml");
25
+ class ResolutionError extends Error {
26
+ }
27
+ exports.ResolutionError = ResolutionError;
28
+ exports.LABEL_VOCABULARY = {
29
+ clause: "Clause",
30
+ subclause: "Clause",
31
+ annex: "Annex",
32
+ appendix: "Appendix",
33
+ section: "Section",
34
+ figure: "Figure",
35
+ table: "Table",
36
+ formula: "Formula",
37
+ inequality: "Inequality",
38
+ note: "NOTE",
39
+ note_xref: "NOTE",
40
+ note_to_entry: "Note { $n } to entry",
41
+ note_to_entry_xref: "{ $parent }, Note { $n } to entry",
42
+ example: "EXAMPLE",
43
+ example_xref: "EXAMPLE",
44
+ termexample: "EXAMPLE",
45
+ list: "List",
46
+ introduction: "Introduction",
47
+ norm_annex: "normative",
48
+ inform_annex: "informative",
49
+ };
50
+ function ref(instance, key) {
51
+ const value = instance.properties?.[key];
52
+ if (value == null)
53
+ return "";
54
+ return typeof value === "object" ? (value.ref ?? "") : String(value);
55
+ }
56
+ function refs(instance, key) {
57
+ const value = instance.properties?.[key];
58
+ if (value == null)
59
+ return [];
60
+ const list = Array.isArray(value) ? value : [value];
61
+ return list.map((v) => (typeof v === "object" ? v.ref : String(v)));
62
+ }
63
+ const PLACEHOLDER = /%pn|%parent|%self|%n|\{([A-Za-z][A-Za-z0-9_]*)\}/g;
64
+ // Label catalog values are Fluent message patterns (metanorma/
65
+ // fluent-min semantics): `{ $var }` placeables bind from the labeller
66
+ // bindings, `{ message }` references resolve within the catalog
67
+ // (default vocabulary + host labels), depth is bounded, and a missing
68
+ // variable renders as its own literal `{ name }`.
69
+ exports.FLUENT_MAX_DEPTH = 5;
70
+ function messageTable(bindings) {
71
+ return { ...exports.LABEL_VOCABULARY, ...(bindings.labels ?? {}) };
72
+ }
73
+ function resolveMessage(value, bindings, depth = 0) {
74
+ if (depth > exports.FLUENT_MAX_DEPTH)
75
+ throw new ResolutionError("catalog message nesting too deep");
76
+ let out = "";
77
+ let i = 0;
78
+ while (i < value.length) {
79
+ const ch = value[i];
80
+ if (ch === "\\" && i + 1 < value.length && "{}\\".includes(value[i + 1])) {
81
+ out += value[i + 1];
82
+ i += 2;
83
+ continue;
84
+ }
85
+ if (ch === "{") {
86
+ const end = value.indexOf("}", i);
87
+ if (end < 0) {
88
+ out += ch;
89
+ i += 1;
90
+ continue;
91
+ }
92
+ const inner = value.slice(i + 1, end).trim();
93
+ if (inner.startsWith("$")) {
94
+ const name = inner.slice(1).trim();
95
+ const v = bindings[name];
96
+ out += v == null ? `{${name}}` : String(v);
97
+ }
98
+ else {
99
+ const ref = messageTable(bindings)[inner];
100
+ if (ref == null) {
101
+ throw new ResolutionError(`catalog message references unknown message ${JSON.stringify(inner)}`);
102
+ }
103
+ out += resolveMessage(ref, bindings, depth + 1);
104
+ }
105
+ i = end + 1;
106
+ continue;
107
+ }
108
+ out += ch;
109
+ i += 1;
110
+ }
111
+ return out;
112
+ }
113
+ function render(pattern, bindings) {
114
+ return pattern.replace(PLACEHOLDER, (token, key) => {
115
+ if (token === "%n" || token === "%pn" ||
116
+ token === "%parent" || token === "%self") {
117
+ const value = bindings[token.slice(1)];
118
+ if (value == null) {
119
+ if (token === "%parent" || token === "%self")
120
+ return "";
121
+ throw new ResolutionError(`template ${JSON.stringify(bindings.pattern)} uses ${token} ` +
122
+ "but the labeller has no parent labeller bound for this element");
123
+ }
124
+ return String(value);
125
+ }
126
+ const labels = bindings.labels ?? {};
127
+ const value = key in labels ? String(labels[key])
128
+ : key in exports.LABEL_VOCABULARY ? exports.LABEL_VOCABULARY[key] : undefined;
129
+ if (value === undefined) {
130
+ throw new ResolutionError(`template ${JSON.stringify(bindings.pattern)} uses {${key}} ` +
131
+ "but the key is in neither the labels dictionary nor the " +
132
+ "default vocabulary");
133
+ }
134
+ return resolveMessage(value, bindings);
135
+ });
136
+ }
137
+ function loadProfile(text) {
138
+ const data = yaml.load(text);
139
+ const entries = data?.instances;
140
+ if (!Array.isArray(entries)) {
141
+ throw new Error("profile must be a mapping with an instances list");
142
+ }
143
+ const instances = {};
144
+ for (const entry of entries) {
145
+ if (!entry.name || !entry.type) {
146
+ throw new Error(`instance needs name and type: ${JSON.stringify(entry)}`);
147
+ }
148
+ instances[entry.name] = {
149
+ name: entry.name,
150
+ type: entry.type,
151
+ properties: entry.properties ?? {},
152
+ };
153
+ }
154
+ return { instances };
155
+ }
156
+ class SequenceExhaustedError extends Error {
157
+ }
158
+ exports.SequenceExhaustedError = SequenceExhaustedError;
159
+ const CYRILLIC_UPPER = [
160
+ "А", "Б", "В", "Г", "Д", "Е", "Ж", "З", "И", "Й", "К", "Л", "М", "Н",
161
+ "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ы",
162
+ "Ь", "Э", "Ю", "Я",
163
+ ];
164
+ const CYRILLIC_LOWER = CYRILLIC_UPPER.map((c) => c.toLowerCase());
165
+ const GREEK_UPPER = [
166
+ "Α", "Β", "Γ", "Δ", "Ε", "Ζ", "Η", "Θ", "Ι", "Κ", "Λ", "Μ", "Ν", "Ξ",
167
+ "Ο", "Π", "Ρ", "Σ", "Τ", "Υ", "Φ", "Χ", "Ψ", "Ω",
168
+ ];
169
+ const GREEK_LOWER = GREEK_UPPER.map((c) => c.toLowerCase());
170
+ const HEBREW = [
171
+ "א", "ב", "ג", "ד", "ה", "ו", "ז", "ח", "ט", "י", "כ", "ל", "מ", "נ",
172
+ "ס", "ע", "פ", "צ", "ק", "ר", "ש", "ת",
173
+ ];
174
+ function numericSpec(fmt) {
175
+ return { type: "NumericSequence", properties: { initial_value: 1, increment: 1, format: fmt } };
176
+ }
177
+ // The default sequences required of a LADL-compliant runtime (MN 112
178
+ // "NumericSequence").
179
+ exports.BUILTIN_SEQUENCE_SPECS = {
180
+ DecimalNumericSequence: numericSpec("decimal"),
181
+ ArabicNumericSequence: numericSpec("arabic_indic"),
182
+ ArabicIndicNumericSequence: {
183
+ type: "NumericSequence",
184
+ properties: { initial_value: 1, increment: 1, format: "arabic_indic", char_direction: "rtl" },
185
+ },
186
+ RomanUpperNumericSequence: numericSpec("roman_upper"),
187
+ RomanLowerNumericSequence: numericSpec("roman_lower"),
188
+ AlphaUpperNumericSequence: numericSpec("alpha_upper"),
189
+ AlphaLowerNumericSequence: numericSpec("alpha_lower"),
190
+ ChineseNumericSequence: numericSpec("chinese"),
191
+ JapaneseNumericSequence: numericSpec("japanese"),
192
+ KoreanNumericSequence: numericSpec("korean"),
193
+ CyrillicUpperCharacterSequence: {
194
+ type: "CharacterSequence",
195
+ properties: { characters: [...CYRILLIC_UPPER], expansion_rule: "prepend_prefix" },
196
+ },
197
+ CyrillicLowerCharacterSequence: {
198
+ type: "CharacterSequence",
199
+ properties: { characters: [...CYRILLIC_LOWER], expansion_rule: "prepend_prefix" },
200
+ },
201
+ GreekUpperCharacterSequence: {
202
+ type: "CharacterSequence",
203
+ properties: { characters: [...GREEK_UPPER], expansion_rule: "prepend_prefix" },
204
+ },
205
+ GreekLowerCharacterSequence: {
206
+ type: "CharacterSequence",
207
+ properties: { characters: [...GREEK_LOWER], expansion_rule: "prepend_prefix" },
208
+ },
209
+ HebrewNumericSequence: {
210
+ type: "CharacterSequence",
211
+ properties: { characters: [...HEBREW], expansion_rule: "prepend_prefix" },
212
+ },
213
+ };
214
+ const ARABIC_INDIC_DIGITS = "٠١٢٣٤٥٦٧٨٩";
215
+ // Labeling formats: renders a 1-based numeric value in a particular
216
+ // alphanumeric system (MN 112 "labeling format").
217
+ exports.Formatters = {
218
+ format(fmt, number) {
219
+ if (number < 1) {
220
+ throw new ResolutionError(`sequence value must be positive, got ${number}`);
221
+ }
222
+ switch (fmt) {
223
+ case "decimal": return String(number);
224
+ case "roman_upper": return exports.Formatters.roman(number);
225
+ case "roman_lower": return exports.Formatters.roman(number).toLowerCase();
226
+ case "alpha_upper": return exports.Formatters.alpha(number);
227
+ case "alpha_lower": return exports.Formatters.alpha(number).toLowerCase();
228
+ case "arabic_indic": {
229
+ let out = "";
230
+ for (const ch of String(number)) {
231
+ const d = ch.charCodeAt(0) - 48;
232
+ out += d >= 0 && d <= 9 ? ARABIC_INDIC_DIGITS[d] : ch;
233
+ }
234
+ return out;
235
+ }
236
+ case "chinese":
237
+ case "japanese":
238
+ case "korean":
239
+ return exports.Formatters.eastAsian(fmt, number);
240
+ default:
241
+ throw new ResolutionError(`unknown labeling format: ${JSON.stringify(fmt)}`);
242
+ }
243
+ },
244
+ roman(number) {
245
+ const pairs = [
246
+ [1000, "M"], [900, "CM"], [500, "D"], [400, "CD"], [100, "C"],
247
+ [90, "XC"], [50, "L"], [40, "XL"], [10, "X"], [9, "IX"],
248
+ [5, "V"], [4, "IV"], [1, "I"],
249
+ ];
250
+ let out = "";
251
+ let n = number;
252
+ for (const [value, letters] of pairs) {
253
+ while (n >= value) {
254
+ out += letters;
255
+ n -= value;
256
+ }
257
+ }
258
+ return out;
259
+ },
260
+ alpha(number) {
261
+ return exports.Formatters.digits(number, 26).map((d) => String.fromCharCode(64 + d)).join("");
262
+ },
263
+ eastAsian(fmt, number) {
264
+ const units = exports.Formatters.cjkUnits[fmt];
265
+ const smallTen = exports.Formatters.cjkSmallTen[fmt];
266
+ const smallHundred = exports.Formatters.cjkSmallHundred[fmt];
267
+ const smallThousand = exports.Formatters.cjkSmallThousand[fmt];
268
+ const thousands = Math.floor(number / 1000);
269
+ const restThousands = number % 1000;
270
+ const hundreds = Math.floor(restThousands / 100);
271
+ const restHundreds = restThousands % 100;
272
+ const tens = Math.floor(restHundreds / 10);
273
+ const ones = restHundreds % 10;
274
+ let out = "";
275
+ if (thousands > 0)
276
+ out += exports.Formatters.compound(units, thousands, smallThousand, false);
277
+ if (hundreds > 0)
278
+ out += exports.Formatters.compound(units, hundreds, smallHundred, false);
279
+ if (tens > 0)
280
+ out += exports.Formatters.compound(units, tens, smallTen, true);
281
+ if (ones > 0)
282
+ out += units[ones];
283
+ return out;
284
+ },
285
+ cjkUnits: {
286
+ chinese: ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"],
287
+ japanese: ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"],
288
+ korean: ["영", "일", "이", "삼", "사", "오", "육", "칠", "팔", "구"],
289
+ },
290
+ cjkSmallTen: { chinese: "十", japanese: "十", korean: "십" },
291
+ cjkSmallHundred: { chinese: "百", japanese: "百", korean: "백" },
292
+ cjkSmallThousand: { chinese: "千", japanese: "千", korean: "천" },
293
+ compound(units, count, marker, dropSingleUnit) {
294
+ const prefix = count === 1 && dropSingleUnit ? "" : units[count];
295
+ return `${prefix}${marker}`;
296
+ },
297
+ // Bijective (spreadsheet-style) decomposition of a 1-based number
298
+ // into digits of the given radix.
299
+ digits(number, radix) {
300
+ const digits = [];
301
+ let n = number;
302
+ while (n > 0) {
303
+ n -= 1;
304
+ digits.unshift((n % radix) + 1);
305
+ n = Math.floor(n / radix);
306
+ }
307
+ return digits;
308
+ },
309
+ };
310
+ const elementIds = new WeakMap();
311
+ let nextElementId = 1;
312
+ function objectId(element) {
313
+ let id = elementIds.get(element);
314
+ if (id === undefined) {
315
+ id = nextElementId++;
316
+ elementIds.set(element, id);
317
+ }
318
+ return id;
319
+ }
320
+ class Resolver {
321
+ profile;
322
+ nameOf = new Map();
323
+ labellersByContext = new Map();
324
+ constructor(profile) {
325
+ this.profile = profile;
326
+ for (const inst of Object.values(profile.instances)) {
327
+ if (inst.type !== "Labeller")
328
+ continue;
329
+ const context = ref(inst, "context");
330
+ if (!context) {
331
+ throw new ResolutionError(`labeller ${inst.name} declares no context`);
332
+ }
333
+ this.nameOf.set(inst, inst.name);
334
+ if (!this.labellersByContext.has(context)) {
335
+ this.labellersByContext.set(context, new Map());
336
+ }
337
+ this.labellersByContext
338
+ .get(context).set(inst.properties?.type, inst);
339
+ }
340
+ }
341
+ labellerForContext(context, elementType) {
342
+ return this.labellersByContext.get(context)?.get(elementType) ?? null;
343
+ }
344
+ instanceNameOf(labeller) {
345
+ return this.nameOf.get(labeller);
346
+ }
347
+ ancestorChain(labellerName) {
348
+ const chain = [labellerName];
349
+ const seen = new Set([labellerName]);
350
+ let current = labellerName;
351
+ for (;;) {
352
+ const labeller = this.profile.instances[current];
353
+ if (!labeller)
354
+ break;
355
+ const parent = ref(labeller, "parent");
356
+ if (!parent || seen.has(parent))
357
+ break;
358
+ chain.push(parent);
359
+ seen.add(parent);
360
+ current = parent;
361
+ }
362
+ return chain;
363
+ }
364
+ }
365
+ exports.Resolver = Resolver;
366
+ function conditionHolds(condition, total) {
367
+ if (!condition)
368
+ return false;
369
+ if (condition.type === "element_count_gt")
370
+ return total > condition.threshold;
371
+ if (condition.type === "element_count_lt")
372
+ return total < condition.threshold;
373
+ return false;
374
+ }
375
+ function selectTemplate(templates, total) {
376
+ const holding = templates.find((t) => t.properties?.condition && conditionHolds(t.properties.condition, total));
377
+ if (holding)
378
+ return holding;
379
+ return templates.find((t) => !t.properties?.condition) ?? templates[0] ?? null;
380
+ }
381
+ function joinHierarchical(parentHier, raw) {
382
+ if (parentHier && raw === null)
383
+ return parentHier;
384
+ if (parentHier === null)
385
+ return raw;
386
+ return `${parentHier}.${raw}`;
387
+ }
388
+ class Engine {
389
+ labels = new Map();
390
+ resolved;
391
+ labelsInput;
392
+ plan = [];
393
+ totals = new Map();
394
+ constructor(profile, labels) {
395
+ this.resolved = new Resolver(profile);
396
+ this.labelsInput = labels ?? {};
397
+ }
398
+ label(tree) {
399
+ this.plan = [];
400
+ this.totals = new Map();
401
+ this.labels = new Map();
402
+ this.walk(tree, []);
403
+ this.render();
404
+ return this;
405
+ }
406
+ walk(element, ancestors) {
407
+ const [labeller, contextName, labelCarrier] = this.resolveOwnLabel(element, ancestors);
408
+ const association = this.nearestAssociation(element, ancestors);
409
+ const frame = { element, declared: element.context, entry: null };
410
+ if (labeller) {
411
+ frame.entry = this.planElement(element, labeller, contextName, labelCarrier, association, ancestors);
412
+ }
413
+ ancestors.push(frame);
414
+ for (const child of element.children ?? [])
415
+ this.walk(child, ancestors);
416
+ ancestors.pop();
417
+ }
418
+ resolveOwnLabel(element, ancestors) {
419
+ if (element.context) {
420
+ const labeller = this.resolved.labellerForContext(element.context, element.type);
421
+ if (labeller) {
422
+ const carrier = { element, declared: element.context, entry: null };
423
+ return [labeller, element.context, carrier];
424
+ }
425
+ }
426
+ for (const frame of [...ancestors].reverse()) {
427
+ if (!frame.declared)
428
+ continue;
429
+ const labeller = this.resolved.labellerForContext(frame.declared, element.type);
430
+ if (labeller)
431
+ return [labeller, frame.declared, frame];
432
+ }
433
+ return [null, null, null];
434
+ }
435
+ nearestAssociation(element, ancestors) {
436
+ if (element.context) {
437
+ return { element, declared: element.context, entry: null };
438
+ }
439
+ for (const frame of [...ancestors].reverse()) {
440
+ if (frame.declared)
441
+ return frame;
442
+ }
443
+ return null;
444
+ }
445
+ planElement(element, labeller, contextName, labelCarrier, scopeAssociation, ancestors) {
446
+ const parent = this.findParentEntry(labeller, ancestors);
447
+ const parentHier = parent ? parent.hierarchical : null;
448
+ const position = this.incrementCounter(labelCarrier, labeller, parentHier);
449
+ const raw = this.sequenceRaw(labeller, position);
450
+ const entry = {
451
+ element,
452
+ etype: element.type,
453
+ labeller,
454
+ labellerName: this.resolved.instanceNameOf(labeller),
455
+ contextName,
456
+ carrierObjectId: objectId(labelCarrier.element),
457
+ carrierEntry: scopeAssociation ? scopeAssociation.entry : null,
458
+ position,
459
+ rawValue: raw,
460
+ parentHier,
461
+ parentEntry: parent,
462
+ hierarchical: joinHierarchical(parentHier, raw),
463
+ local: null,
464
+ global: null,
465
+ };
466
+ if (scopeAssociation && scopeAssociation.element === element) {
467
+ scopeAssociation.entry = entry;
468
+ entry.carrierEntry = entry;
469
+ }
470
+ this.plan.push(entry);
471
+ return entry;
472
+ }
473
+ findParentEntry(labeller, ancestors) {
474
+ const parentName = ref(labeller, "parent");
475
+ if (!parentName)
476
+ return null;
477
+ const parentLabeller = this.resolved.profile.instances[parentName];
478
+ if (!parentLabeller) {
479
+ throw new ResolutionError(`labeller ${JSON.stringify(this.resolved.instanceNameOf(labeller))} ` +
480
+ `references undefined parent labeller ${JSON.stringify(parentName)}`);
481
+ }
482
+ const chain = this.resolved.ancestorChain(this.resolved.instanceNameOf(labeller));
483
+ for (const frame of [...ancestors].reverse()) {
484
+ const entry = frame.entry;
485
+ if (entry && chain.includes(entry.labellerName))
486
+ return entry;
487
+ }
488
+ const parentType = parentLabeller.properties?.type;
489
+ for (const frame of [...ancestors].reverse()) {
490
+ const entry = frame.entry;
491
+ if (entry && entry.etype === parentType)
492
+ return entry;
493
+ }
494
+ return null;
495
+ }
496
+ incrementCounter(carrier, labeller, parentHier) {
497
+ const key = `${objectId(carrier.element)}\u0000` +
498
+ `${this.resolved.instanceNameOf(labeller)}\u0000${parentHier ?? ""}`;
499
+ const n = (this.totals.get(key) ?? 0) + 1;
500
+ this.totals.set(key, n);
501
+ return n;
502
+ }
503
+ sequenceRaw(labeller, position) {
504
+ const sequence = ref(labeller, "sequence");
505
+ if (!sequence)
506
+ return null;
507
+ return this.sequenceValue(this.lookupSequence(sequence), position);
508
+ }
509
+ lookupSequence(name) {
510
+ const instance = this.resolved.profile.instances[name];
511
+ if (instance &&
512
+ (instance.type === "NumericSequence" ||
513
+ instance.type === "CharacterSequence")) {
514
+ return instance;
515
+ }
516
+ const spec = exports.BUILTIN_SEQUENCE_SPECS[name];
517
+ if (!spec) {
518
+ throw new ResolutionError(`undefined sequence: ${JSON.stringify(name)}`);
519
+ }
520
+ return { name, type: spec.type, properties: { ...spec.properties } };
521
+ }
522
+ sequenceValue(sequence, position) {
523
+ return sequence.type === "NumericSequence"
524
+ ? this.numericValue(sequence, position)
525
+ : this.characterValue(sequence, position);
526
+ }
527
+ numericValue(sequence, position) {
528
+ const initial = sequence.properties.initial_value || 1;
529
+ const increment = sequence.properties.increment || 1;
530
+ const raw = initial + (position - 1) * increment;
531
+ const baseName = ref(sequence, "base_sequence");
532
+ if (baseName)
533
+ return this.sequenceValue(this.lookupSequence(baseName), raw);
534
+ const fmt = sequence.properties.format || "decimal";
535
+ const cycleLength = sequence.properties.cycle_length;
536
+ if (Number.isInteger(cycleLength) && cycleLength > 0) {
537
+ return exports.Formatters.digits(raw, cycleLength)
538
+ .map((d) => exports.Formatters.format(fmt, d))
539
+ .join("");
540
+ }
541
+ return exports.Formatters.format(fmt, raw);
542
+ }
543
+ characterValue(sequence, position) {
544
+ const chars = [...(sequence.properties.characters ?? [])];
545
+ if (!chars.length) {
546
+ throw new SequenceExhaustedError("sequence has no characters");
547
+ }
548
+ const pos = position - 1;
549
+ if (pos >= 0 && pos < chars.length)
550
+ return chars[pos];
551
+ const size = chars.length;
552
+ const cycle = Math.floor(pos / size);
553
+ const rule = sequence.properties.expansion_rule;
554
+ if (rule === "repeat_label")
555
+ return chars[pos % size];
556
+ if (rule === "prepend_prefix") {
557
+ const prefixes = this.prefixesFor(sequence, chars);
558
+ return prefixes[(cycle - 1) % prefixes.length] + chars[pos % size];
559
+ }
560
+ if (rule === "double_character") {
561
+ return chars[pos % size].repeat(cycle + 1);
562
+ }
563
+ if (rule === "append_suffix") {
564
+ const suffixes = this.prefixesFor(sequence, chars);
565
+ return chars[pos % size] + suffixes[(cycle - 1) % suffixes.length];
566
+ }
567
+ if (rule === "none" || rule == null) {
568
+ throw new SequenceExhaustedError(`sequence exhausted at position ${pos + 1} (expansion_rule none)`);
569
+ }
570
+ throw new ResolutionError(`unknown expansion_rule: ${JSON.stringify(rule)}`);
571
+ }
572
+ prefixesFor(sequence, chars) {
573
+ let prefixes = sequence.properties.expansion_prefix ?? [];
574
+ if (typeof prefixes === "string")
575
+ prefixes = [prefixes];
576
+ prefixes = prefixes.filter((p) => p);
577
+ return prefixes.length ? prefixes : chars;
578
+ }
579
+ render() {
580
+ for (const entry of this.plan) {
581
+ const labeller = entry.labeller;
582
+ const key = `${entry.carrierObjectId}\u0000` +
583
+ `${entry.labellerName}\u0000${entry.parentHier ?? ""}`;
584
+ const total = this.totals.get(key) ?? 1;
585
+ const localTemplate = selectTemplate(this.templates(labeller, "template"), total);
586
+ if (!localTemplate) {
587
+ throw new ResolutionError(`labeller ${JSON.stringify(entry.labellerName)} has no label template`);
588
+ }
589
+ const bindings = {
590
+ n: entry.rawValue,
591
+ pn: entry.parentHier,
592
+ parent: entry.carrierEntry ? entry.carrierEntry.global : null,
593
+ labels: this.labelsInput,
594
+ pattern: localTemplate.properties?.pattern,
595
+ };
596
+ entry.local = render(localTemplate.properties.pattern, bindings);
597
+ const globals = this.templates(labeller, "global_template");
598
+ if (!globals.length) {
599
+ entry.global = entry.local;
600
+ }
601
+ else {
602
+ const globalTemplate = selectTemplate(globals, total);
603
+ bindings.pattern = globalTemplate.properties?.pattern;
604
+ bindings.self = entry.local;
605
+ entry.global = render(globalTemplate.properties.pattern, bindings);
606
+ }
607
+ if (entry.element.id) {
608
+ this.labels.set(entry.element.id, {
609
+ value: entry.local,
610
+ reference: entry.global,
611
+ });
612
+ }
613
+ }
614
+ }
615
+ templates(labeller, key) {
616
+ return refs(labeller, key)
617
+ .map((n) => this.resolved.profile.instances[n])
618
+ .filter((t) => t != null);
619
+ }
620
+ }
621
+ exports.Engine = Engine;
@@ -0,0 +1,78 @@
1
+ export interface Instance {
2
+ name: string;
3
+ type: string;
4
+ properties: Record<string, any>;
5
+ }
6
+ export interface Profile {
7
+ instances: Record<string, Instance>;
8
+ }
9
+ export interface Element {
10
+ type: string;
11
+ id: string;
12
+ context?: string | null;
13
+ children?: Element[];
14
+ }
15
+ export interface Label {
16
+ value: string;
17
+ reference: string;
18
+ }
19
+ export declare class ResolutionError extends Error {
20
+ }
21
+ export declare const LABEL_VOCABULARY: Record<string, string>;
22
+ export declare function ref(instance: Instance, key: string): string;
23
+ export declare function refs(instance: Instance, key: string): string[];
24
+ export declare const FLUENT_MAX_DEPTH = 5;
25
+ export declare function messageTable(bindings: Record<string, any>): Record<string, string>;
26
+ export declare function resolveMessage(value: string, bindings: Record<string, any>, depth?: number): string;
27
+ export declare function render(pattern: string, bindings: Record<string, any>): string;
28
+ export declare function loadProfile(text: string): Profile;
29
+ export declare class SequenceExhaustedError extends Error {
30
+ }
31
+ export declare const BUILTIN_SEQUENCE_SPECS: Record<string, {
32
+ type: string;
33
+ properties: Record<string, any>;
34
+ }>;
35
+ export declare const Formatters: {
36
+ format(fmt: string, number: number): string;
37
+ roman(number: number): string;
38
+ alpha(number: number): string;
39
+ eastAsian(fmt: string, number: number): string;
40
+ cjkUnits: Record<string, string[]>;
41
+ cjkSmallTen: Record<string, string>;
42
+ cjkSmallHundred: Record<string, string>;
43
+ cjkSmallThousand: Record<string, string>;
44
+ compound(units: string[], count: number, marker: string, dropSingleUnit: boolean): string;
45
+ digits(number: number, radix: number): number[];
46
+ };
47
+ export declare class Resolver {
48
+ profile: Profile;
49
+ private nameOf;
50
+ private labellersByContext;
51
+ constructor(profile: Profile);
52
+ labellerForContext(context: string, elementType: string): Instance | null;
53
+ instanceNameOf(labeller: Instance): string;
54
+ ancestorChain(labellerName: string): string[];
55
+ }
56
+ export declare class Engine {
57
+ labels: Map<string, Label>;
58
+ private resolved;
59
+ private labelsInput;
60
+ private plan;
61
+ private totals;
62
+ constructor(profile: Profile, labels?: Record<string, string>);
63
+ label(tree: Element): this;
64
+ private walk;
65
+ private resolveOwnLabel;
66
+ private nearestAssociation;
67
+ private planElement;
68
+ private findParentEntry;
69
+ private incrementCounter;
70
+ private sequenceRaw;
71
+ private lookupSequence;
72
+ private sequenceValue;
73
+ private numericValue;
74
+ private characterValue;
75
+ private prefixesFor;
76
+ private render;
77
+ private templates;
78
+ }