@stll/agent-input 0.1.6 → 0.1.8

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.js CHANGED
@@ -1,104 +1,12 @@
1
+ import { a as isAbsentPlaceholder, i as ABSENT_PLACEHOLDERS, n as normalizeDateBound, r as normalizeDateValue, t as DATE_VALUE_HINT } from "./date-value-CXL60jnN.js";
2
+ import { a as readValueAs, i as readValue, n as askSentence, r as readAsAbsent, t as askForFix } from "./normalized-Kt_5vfXW.js";
3
+ import { COUNTRY_INPUT_MAX_CHARS, countryCodeIn, normalizeCountry } from "./country.js";
4
+ import { isPlausibleLocale, normalizeLocale } from "./locale.js";
5
+ import { normalizeStringList } from "./string-list.js";
1
6
  import { foldToAscii } from "@stll/text-normalize";
2
- import { COUNTRY_ALPHA3_BY_CODE, COUNTRY_CODES, countryCodeFromAlpha3, isCountryCode } from "@stll/country-codes";
3
7
  import { DATE_FORMAT_STYLES } from "@stll/template-conditions";
8
+ import { distance } from "@stll/fuzzy-search";
4
9
  import { Result, panic } from "better-result";
5
- import { Temporal, parsePlainDate } from "@stll/time";
6
- //#region src/absent.ts
7
- /**
8
- * Placeholders on optional filters.
9
- *
10
- * A model fills every slot a schema shows it, so a filter it means to leave
11
- * unset still arrives as `"any"`, `"-"` or `"none"`. Those words name no
12
- * court, no type, no record: read as a value they match nothing and the call
13
- * returns an empty page the model then explains away. The set is closed and
14
- * short on purpose; a word outside it is a value and goes to the kind's own
15
- * reader.
16
- *
17
- * This is not for free text. `"none"` is a fine answer to a question and `"-"`
18
- * a fine clause body, so the caller decides which inputs a placeholder can
19
- * stand in for.
20
- */
21
- /** The words, already in the folded lowercase form they are compared in. */
22
- const ABSENT_PLACEHOLDERS = [
23
- "-",
24
- "--",
25
- "–",
26
- "—",
27
- "*",
28
- "all",
29
- "any",
30
- "none",
31
- "null",
32
- "nil",
33
- "undefined",
34
- "n/a",
35
- "(none)",
36
- "<none>",
37
- "(any)",
38
- "(all)"
39
- ];
40
- const PLACEHOLDERS = new Set(ABSENT_PLACEHOLDERS);
41
- /** Whether a string stands for "no value" on an optional filter: blank, or one
42
- * of the placeholder words in any case and spacing. */
43
- const isAbsentPlaceholder = (input) => {
44
- if (typeof input !== "string") return false;
45
- const trimmed = input.trim();
46
- return trimmed === "" || PLACEHOLDERS.has(foldToAscii(trimmed).toLowerCase());
47
- };
48
- //#endregion
49
- //#region src/normalized.ts
50
- /** Wire values carry matter content and personal data, so an echo back to the
51
- * model is bounded to the length of a spelling. */
52
- const MAX_RECEIVED_CHARS = 80;
53
- /** The input as one quoted token: what the agent sent, ready to drop into a
54
- * sentence. */
55
- const describeInput = (input) => {
56
- const spelled = typeof input === "function" || typeof input === "symbol" ? void 0 : JSON.stringify(input);
57
- const rendered = input === void 0 ? "undefined" : spelled ?? `a ${typeof input}`;
58
- return rendered.length <= MAX_RECEIVED_CHARS ? rendered : `${rendered.slice(0, MAX_RECEIVED_CHARS)}…`;
59
- };
60
- const readValue = (value) => ({
61
- ok: true,
62
- value
63
- });
64
- /**
65
- * The canonical value, plus the "read X as Y" note when the agent's spelling
66
- * was not already the canonical one. That sentence is spelled here alone, so
67
- * every kind reports a coercion the same way. `canonical` overrides how the
68
- * result is rendered in the note, for a kind whose canonical spelling is not
69
- * the JSON form of its value.
70
- */
71
- const readValueAs = (input, value, canonical = describeInput(value)) => {
72
- const received = describeInput(input);
73
- return received === canonical ? {
74
- ok: true,
75
- value
76
- } : {
77
- ok: true,
78
- value,
79
- note: `Read ${received} as ${canonical}.`
80
- };
81
- };
82
- const askForFix = ({ input, expected, hint }) => ({
83
- ok: false,
84
- received: describeInput(input),
85
- expected,
86
- hint
87
- });
88
- /** The ask as one sentence, for a caller whose issue shape carries a message
89
- * beside the hint. */
90
- const askSentence = (ask) => `${ask.received} is not ${ask.expected}.`;
91
- /** The absent outcome, with the one "read X as no value" sentence every kind
92
- * reports it with. `reason` says why, when the spelling alone does not. */
93
- const readAsAbsent = (input, reason) => {
94
- const received = describeInput(input);
95
- return {
96
- ok: "absent",
97
- received,
98
- note: reason === void 0 ? `Read ${received} as no value.` : `Read ${received} as no value: ${reason}.`
99
- };
100
- };
101
- //#endregion
102
10
  //#region src/boolean.ts
103
11
  /**
104
12
  * Yes/no answers on the agent wire.
@@ -159,235 +67,6 @@ const normalizeBoolean = (input) => {
159
67
  return readValueAs(input, word);
160
68
  };
161
69
  //#endregion
162
- //#region src/country.ts
163
- /**
164
- * Jurisdictions that publish law without being ISO 3166-1 countries.
165
- *
166
- * The EU is the one this corpus holds: the Court of Justice and the Official
167
- * Journal are supranational, and legal corpora and ELI identifiers spell that
168
- * jurisdiction `EU`. CLDR carries `EU` as a region, so its names arrive from
169
- * the same place as a country's, and ISO assigns it neither alpha-2 nor
170
- * alpha-3, so `EU` is both.
171
- */
172
- const SUPRANATIONAL_CODES = ["EU"];
173
- /**
174
- * The languages whose spellings are read.
175
- *
176
- * These are the languages this corpus's jurisdictions legislate and adjudicate
177
- * in, plus English, which every model falls back to. A locale added here widens
178
- * what is accepted and can only introduce an ambiguity that the index reports
179
- * rather than guesses.
180
- */
181
- const NAME_LOCALES = [
182
- "en",
183
- "cs",
184
- "sk",
185
- "pl",
186
- "de",
187
- "hu"
188
- ];
189
- /**
190
- * Official long forms CLDR does not carry, keyed by CLDR region.
191
- *
192
- * CLDR holds the short name a locale uses day to day (`Česko`, `Slovensko`),
193
- * while a model drafting a legal document reaches for the constitutional name.
194
- * Listed are the jurisdictions this corpus serves, plus Germany, whose language
195
- * the corpus serves and whose law gets asked about in it. Each entry is in
196
- * English or in one of those languages: an entry earns its place by being a
197
- * name some surface actually receives, not by completeness. Case, spacing and
198
- * diacritics need no entries of their own, because the index keys on the folded
199
- * form.
200
- */
201
- const OFFICIAL_NAMES = {
202
- AT: [
203
- "Republic of Austria",
204
- "Republik Österreich",
205
- "Rakouská republika"
206
- ],
207
- CZ: [
208
- "Czech Republic",
209
- "Česká republika",
210
- "Tschechische Republik",
211
- "Republika Czeska"
212
- ],
213
- DE: ["Federal Republic of Germany", "Bundesrepublik Deutschland"],
214
- HU: ["Republic of Hungary", "Magyar Köztársaság"],
215
- PL: [
216
- "Republic of Poland",
217
- "Rzeczpospolita Polska",
218
- "Polská republika"
219
- ],
220
- SK: [
221
- "Slovak Republic",
222
- "Slovenská republika",
223
- "Slowakische Republik",
224
- "Republika Słowacka"
225
- ],
226
- EU: ["European Communities"]
227
- };
228
- /**
229
- * Tokens that name two countries at once.
230
- *
231
- * Each maps to the readings the ask must name. A token here must not be a valid
232
- * alpha-2 code: the codes are read as themselves, and this table exists for the
233
- * spellings that are not codes at all.
234
- */
235
- const AMBIGUOUS_TOKENS = /* @__PURE__ */ new Map([["cs", ["CZE", "SVK"]]]);
236
- /** The comparison form of a name: case, diacritics and spacing carry no
237
- * meaning in a country name, so none of them reach the index key. */
238
- const fold$2 = (value) => foldToAscii(value.trim()).toLowerCase().replaceAll(/\s+/gu, " ");
239
- /**
240
- * The name index, built once on first read.
241
- *
242
- * `Intl.DisplayNames` is thousands of lookups across every region and locale,
243
- * so it is deferred rather than run at import: a module that only ever reads a
244
- * code should not pay for the names, and a shared module must not do work when
245
- * it is loaded.
246
- */
247
- let cachedIndex = null;
248
- const buildIndex = () => {
249
- const regions = [...COUNTRY_CODES, ...SUPRANATIONAL_CODES];
250
- const collected = /* @__PURE__ */ new Map();
251
- const add = (name, region) => {
252
- const key = fold$2(name);
253
- if (key.length === 0) return;
254
- const existing = collected.get(key);
255
- if (existing === void 0) {
256
- collected.set(key, [region]);
257
- return;
258
- }
259
- if (!existing.includes(region)) existing.push(region);
260
- };
261
- for (const locale of NAME_LOCALES) for (const style of ["long", "short"]) {
262
- const display = new Intl.DisplayNames([locale], {
263
- type: "region",
264
- style,
265
- fallback: "none"
266
- });
267
- for (const region of regions) {
268
- const name = display.of(region);
269
- if (name !== void 0 && name !== region) add(name, region);
270
- }
271
- }
272
- for (const [region, names] of Object.entries(OFFICIAL_NAMES)) for (const name of names) add(name, region);
273
- return { regionsByName: collected };
274
- };
275
- const index = () => {
276
- cachedIndex ??= buildIndex();
277
- return cachedIndex;
278
- };
279
- const isSupranational = (value) => SUPRANATIONAL_CODES.some((code) => code === value);
280
- /** The canonical pair a CLDR region names. */
281
- const valueOfRegion = (region) => {
282
- if (isSupranational(region)) return {
283
- alpha3: region,
284
- alpha2: region
285
- };
286
- return isCountryCode(region) ? {
287
- alpha3: COUNTRY_ALPHA3_BY_CODE[region],
288
- alpha2: region
289
- } : null;
290
- };
291
- /** The canonical pair a code names, in either ISO length. */
292
- const valueOfCode = (upper) => {
293
- if (isSupranational(upper)) return {
294
- alpha3: upper,
295
- alpha2: upper
296
- };
297
- const fromAlpha3 = countryCodeFromAlpha3(upper);
298
- if (fromAlpha3 !== null) return {
299
- alpha3: COUNTRY_ALPHA3_BY_CODE[fromAlpha3],
300
- alpha2: fromAlpha3
301
- };
302
- return isCountryCode(upper) ? {
303
- alpha3: COUNTRY_ALPHA3_BY_CODE[upper],
304
- alpha2: upper
305
- } : null;
306
- };
307
- /**
308
- * The longest country spelling a wire schema accepts.
309
- *
310
- * A country's own name is a spelling this reader reads, so the bound is a
311
- * name's length rather than a code's: `Federal Republic of Germany` is a
312
- * country input, and a schema capped at three characters was what turned it
313
- * into a rejection before the reader ever saw it. It lives with the reader so
314
- * the declared bound and what can be read cannot drift apart.
315
- */
316
- const COUNTRY_INPUT_MAX_CHARS = 64;
317
- const COUNTRY_EXPECTED = "a country";
318
- /** The code a caller keeping `spelling` stores. */
319
- const countryCodeIn = (value, spelling = "alpha-3") => spelling === "alpha-2" ? value.alpha2 : value.alpha3;
320
- /**
321
- * How the canonical value is quoted in a coercion note.
322
- *
323
- * The note compares against the spelling the agent sent, which is the quoted
324
- * JSON of a string, so the canonical code is quoted the same way. Without it,
325
- * `"CZE"` would be reported as read into `CZE` and a canonical input would not
326
- * be the fixed point it is.
327
- */
328
- const canonicalSpelling = (value, options) => JSON.stringify(countryCodeIn(value, options.spelling));
329
- const admittedSentence = (admitted) => admitted === void 0 || admitted.length === 0 ? "" : ` Admitted: ${admitted.join(", ")}.`;
330
- /** Where to make the correction, as far as the caller told us. */
331
- const target = ({ tool, parameter }) => {
332
- const property = parameter ?? "country";
333
- return tool === void 0 ? `\`${property}\`` : `\`${property}\` on ${tool}`;
334
- };
335
- const expectedWith = (options) => {
336
- const admitted = options.admitted;
337
- return admitted === void 0 || admitted.length === 0 ? COUNTRY_EXPECTED : `a country code, one of ${admitted.join(", ")}`;
338
- };
339
- /** The spellings the reader accepts, as one clause a hint drops in. */
340
- const ACCEPTED_SPELLINGS = "an ISO 3166-1 code, alpha-3 or alpha-2 (\"CZE\", \"CZ\"); the country's name in English or in a language the corpus serves (\"Czechia\", \"Česko\", \"Česká republika\") is read as well.";
341
- const spellingHint = (options) => `Set ${target(options)} to ${ACCEPTED_SPELLINGS}${admittedSentence(options.admitted)}`;
342
- /**
343
- * Read a country an agent spelled its own way.
344
- *
345
- * An absent value asks rather than defaulting: a corpus country decides which
346
- * body of law is searched, and picking one on the model's behalf answers a
347
- * question about Czech law with Slovak decisions.
348
- */
349
- const normalizeCountry = (input, options = {}) => {
350
- if (input === void 0 || input === null || typeof input === "string" && input.trim().length === 0) return askForFix({
351
- input,
352
- expected: expectedWith(options),
353
- hint: `${target(options)} is required. ${spellingHint(options)}`
354
- });
355
- if (typeof input !== "string") return askForFix({
356
- input,
357
- expected: expectedWith(options),
358
- hint: spellingHint(options)
359
- });
360
- const collapsed = input.trim().replaceAll(/\s+/gu, " ");
361
- const byCode = valueOfCode(collapsed.toUpperCase());
362
- if (byCode !== null) return readValueAs(input, byCode, canonicalSpelling(byCode, options));
363
- const key = fold$2(collapsed);
364
- const ambiguous = AMBIGUOUS_TOKENS.get(key);
365
- if (ambiguous !== void 0) return askForFix({
366
- input,
367
- expected: expectedWith(options),
368
- hint: `"${collapsed}" names more than one country here: ${ambiguous.join(" or ")}. Set ${target(options)} to the one you mean.${admittedSentence(options.admitted)}`
369
- });
370
- const regions = index().regionsByName.get(key);
371
- const single = regions?.length === 1 ? regions.at(0) : void 0;
372
- if (single !== void 0) {
373
- const value = valueOfRegion(single);
374
- if (value !== null) return readValueAs(input, value, canonicalSpelling(value, options));
375
- }
376
- if (regions !== void 0 && regions.length > 1) {
377
- const readings = regions.map((region) => valueOfRegion(region)?.alpha3).filter((alpha3) => alpha3 !== void 0);
378
- return askForFix({
379
- input,
380
- expected: expectedWith(options),
381
- hint: `"${collapsed}" names more than one country here: ${readings.join(" or ")}. Set ${target(options)} to the one you mean.${admittedSentence(options.admitted)}`
382
- });
383
- }
384
- return askForFix({
385
- input,
386
- expected: expectedWith(options),
387
- hint: spellingHint(options)
388
- });
389
- };
390
- //#endregion
391
70
  //#region src/enum-value.ts
392
71
  /**
393
72
  * Closed vocabularies on the agent wire: a style name, a registry slug, an
@@ -404,28 +83,6 @@ const NEAR_MISS_DISTANCE = 1;
404
83
  const fold$1 = (value) => foldToAscii(value.trim()).toLowerCase();
405
84
  const quote = (values) => values.map((value) => `"${value}"`).join(", ");
406
85
  /**
407
- * Levenshtein distance, abandoned once it exceeds `limit`. Only the "did you
408
- * mean" ranking reads it, so the exact distance beyond the limit is not
409
- * interesting and the early exit keeps a long value cheap.
410
- */
411
- const editDistanceWithin = (left, right, limit) => {
412
- if (Math.abs(left.length - right.length) > limit) return limit + 1;
413
- let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
414
- for (let row = 1; row <= left.length; row += 1) {
415
- const current = [row];
416
- let best = row;
417
- for (let column = 1; column <= right.length; column += 1) {
418
- const substitution = (previous[column - 1] ?? 0) + (left[row - 1] === right[column - 1] ? 0 : 1);
419
- const distance = Math.min(substitution, (previous[column] ?? 0) + 1, (current[column - 1] ?? 0) + 1);
420
- current.push(distance);
421
- best = Math.min(best, distance);
422
- }
423
- if (best > limit) return limit + 1;
424
- previous = current;
425
- }
426
- return previous[right.length] ?? limit + 1;
427
- };
428
- /**
429
86
  * Read one value of a closed set. An exact hit is taken verbatim; a hit that
430
87
  * differs only in case, spacing, or diacritics is read with a note; a value one
431
88
  * edit from an allowed one asks and names it; anything else asks with the whole
@@ -445,7 +102,7 @@ const normalizeEnumValue = (input, allowed, options) => {
445
102
  const folded = fold$1(input);
446
103
  const loose = allowed.find((value) => fold$1(value) === folded);
447
104
  if (loose !== void 0) return readValueAs(input, loose);
448
- const closest = allowed.find((value) => editDistanceWithin(folded, fold$1(value), NEAR_MISS_DISTANCE) <= NEAR_MISS_DISTANCE);
105
+ const closest = allowed.find((value) => distance(folded, fold$1(value)) <= NEAR_MISS_DISTANCE);
449
106
  return askForFix({
450
107
  input,
451
108
  expected,
@@ -453,51 +110,6 @@ const normalizeEnumValue = (input, allowed, options) => {
453
110
  });
454
111
  };
455
112
  //#endregion
456
- //#region src/locale.ts
457
- /**
458
- * Locale tags on the agent wire.
459
- *
460
- * `Intl` is the authority on both halves: it refuses a structurally malformed
461
- * tag (a well-formed but unknown one passes and merely falls back at format
462
- * time) and it spells the canonical form. Underscores are the ICU/POSIX
463
- * spelling of the same tag, and case carries no meaning, so `cs_cz` and
464
- * `cs-CZ` are one locale — but only the canonical spelling may be stored,
465
- * because `new Intl.DateTimeFormat("cs_CZ")` throws.
466
- */
467
- const LOCALE_EXPECTED = "a BCP-47 language tag";
468
- const LOCALE_HINT = "Write the tag as language or language-REGION: \"cs\", \"pl\", \"en-GB\", \"pt-BR\".";
469
- /** The canonical spelling of a well-formed tag, or null. `Intl` throws a
470
- * RangeError on a malformed tag rather than reporting it. */
471
- const canonicalize = (candidate) => {
472
- const canonical = Result.try({
473
- try: () => Intl.getCanonicalLocales(candidate),
474
- catch: (cause) => cause
475
- });
476
- return canonical.isOk() ? canonical.value.at(0) ?? null : null;
477
- };
478
- /**
479
- * Whether a tag is already the spelling `Intl` accepts. This is the check a
480
- * stored or advertised locale passes: a value that reaches
481
- * `Intl.DateTimeFormat` at fill time must not be able to make it throw, so the
482
- * leniency below stops at the boundary and never reaches persistence.
483
- */
484
- const isPlausibleLocale = (value) => canonicalize(value) !== null;
485
- /** Read a locale an agent spelled its own way, canonically. */
486
- const normalizeLocale = (input) => {
487
- if (typeof input !== "string") return askForFix({
488
- input,
489
- expected: LOCALE_EXPECTED,
490
- hint: LOCALE_HINT
491
- });
492
- const canonical = canonicalize(input.trim().replaceAll("_", "-"));
493
- if (canonical === null) return askForFix({
494
- input,
495
- expected: LOCALE_EXPECTED,
496
- hint: LOCALE_HINT
497
- });
498
- return readValueAs(input, canonical);
499
- };
500
- //#endregion
501
113
  //#region src/date-format-spec.ts
502
114
  /**
503
115
  * How a date field renders: a locale and a style.
@@ -612,360 +224,6 @@ const normalizeDateFormatSpec = (input) => {
612
224
  return specAsk(input);
613
225
  };
614
226
  //#endregion
615
- //#region src/date-value.ts
616
- /**
617
- * Calendar dates on the agent wire.
618
- *
619
- * ISO `YYYY-MM-DD` is the canonical form and the only one a document may store,
620
- * but a model drafting a Czech lease writes `1. 10. 2026` and one drafting an
621
- * English one writes `October 1, 2026`. Those spellings carry one meaning each,
622
- * so they are read.
623
- *
624
- * `01/02/2026` does not: it is 1 February under most of the world's convention
625
- * and 2 January under the United States', and nothing inside the string decides
626
- * which. A wrong date on an instrument is not a cosmetic defect, so an
627
- * ambiguous spelling is asked about with both readings named rather than
628
- * guessed from a default. Same for a two-digit year (`02-03-26`), which is
629
- * ambiguous in the day/month order as well as the century.
630
- *
631
- * A range bound (`date_from`, `date_to`) reads more, because which end it is
632
- * decides what a partial date means: `2020` as a start is 1 January and as an
633
- * end is 31 December, and `0001-01-01` or `9999-12-31` is the model saying the
634
- * range is open on that side. A single date is never read that way, since
635
- * nothing tells a lone `2020` which day of the year it is.
636
- */
637
- const DATE_VALUE_EXPECTED = "a calendar date";
638
- const DATE_VALUE_HINT = "Send the date as ISO YYYY-MM-DD (\"2026-10-01\"). The unambiguous spellings \"1. 10. 2026\", \"1 October 2026\" and \"October 1, 2026\" are read as well.";
639
- /** Day-first with dots is one convention wherever it is written, so it needs
640
- * no disambiguation: `1.10.2026`, `01. 10. 2026`, `1. 10. 2026.` */
641
- const DOTTED_DAY_FIRST_RE = /^(?<day>\d{1,2})\.\s*(?<month>\d{1,2})\.\s*(?<year>\d{4})\.?$/u;
642
- /** Year-first with any separator: the four-digit head fixes the order. */
643
- const YEAR_FIRST_RE = /^(?<year>\d{4})[-./]\s*(?<month>\d{1,2})[-./]\s*(?<day>\d{1,2})\.?$/u;
644
- /** Slash- or dash-separated with a four-digit year at the end: the day/month
645
- * order still has to be decided. */
646
- const YEAR_LAST_RE = /^(?<first>\d{1,2})[/-](?<second>\d{1,2})[/-](?<year>\d{4})$/u;
647
- /** An ISO datetime: the date part is the calendar date it names. */
648
- const ISO_DATETIME_RE = /^(?<date>\d{4}-\d{2}-\d{2})[T ]\S*/u;
649
- /** `1 October 2026`, `1. října 2026`, `1st October 2026`. */
650
- const DAY_MONTH_YEAR_RE = /^(?<day>\d{1,2})(?:st|nd|rd|th)?\.?\s+(?<month>\p{L}+\.?)\s+(?<year>\d{4})$/u;
651
- /** `October 1, 2026`, `Oct. 1 2026`. */
652
- const MONTH_DAY_YEAR_RE = /^(?<month>\p{L}+\.?)\s+(?<day>\d{1,2})(?:st|nd|rd|th)?,?\s+(?<year>\d{4})$/u;
653
- const MAX_MONTH = 12;
654
- const pad = (value) => String(value).padStart(2, "0");
655
- /** The ISO spelling of a real calendar date, or null. */
656
- const isoDate = (year, month, day) => parsePlainDate(`${String(year).padStart(4, "0")}-${pad(month)}-${pad(day)}`)?.toString() ?? null;
657
- /** A month name folded to the form the tables below are keyed by: lowercase,
658
- * no trailing abbreviation dot, diacritics kept (they distinguish nothing a
659
- * model gets wrong, and ICU emits them). */
660
- const foldMonthName = (name) => name.toLowerCase().replace(/\.$/u, "").trim();
661
- /**
662
- * Month names for one locale, in both the standalone form (`říjen`) and the
663
- * form ICU uses inside a full date (`října`, the Czech genitive), long and
664
- * abbreviated. Built from `Intl`, so a locale's names never have to be
665
- * hand-listed.
666
- */
667
- const monthNamesFor = (locale) => {
668
- const names = /* @__PURE__ */ new Map();
669
- const record = (name, month) => {
670
- if (name !== void 0 && /\p{L}/u.test(name)) names.set(foldMonthName(name), month);
671
- };
672
- for (const style of ["long", "short"]) {
673
- const standalone = new Intl.DateTimeFormat(locale, {
674
- month: style,
675
- timeZone: "UTC"
676
- });
677
- const inDate = new Intl.DateTimeFormat(locale, {
678
- day: "numeric",
679
- month: style,
680
- year: "numeric",
681
- timeZone: "UTC"
682
- });
683
- for (let month = 1; month <= MAX_MONTH; month += 1) {
684
- const instant = Temporal.PlainDate.from({
685
- year: 2026,
686
- month,
687
- day: 15
688
- }).toZonedDateTime("UTC").epochMilliseconds;
689
- record(standalone.format(instant), month);
690
- record(inDate.formatToParts(instant).find((part) => part.type === "month")?.value, month);
691
- }
692
- }
693
- return names;
694
- };
695
- const monthNameCache = /* @__PURE__ */ new Map();
696
- const monthNumber = (name, locales) => {
697
- const folded = foldMonthName(name);
698
- for (const locale of locales) {
699
- const cached = monthNameCache.get(locale) ?? monthNamesFor(locale);
700
- monthNameCache.set(locale, cached);
701
- const month = cached.get(folded);
702
- if (month !== void 0) return month;
703
- }
704
- return null;
705
- };
706
- const readNamedMonth = (spec, locales) => {
707
- const groups = (DAY_MONTH_YEAR_RE.exec(spec) ?? MONTH_DAY_YEAR_RE.exec(spec))?.groups;
708
- if (groups === void 0) return null;
709
- const month = monthNumber(groups["month"] ?? "", locales);
710
- return month === null ? null : {
711
- year: Number(groups["year"]),
712
- month,
713
- day: Number(groups["day"])
714
- };
715
- };
716
- const readNumeric = (spec) => {
717
- const groups = (DOTTED_DAY_FIRST_RE.exec(spec) ?? YEAR_FIRST_RE.exec(spec))?.groups;
718
- return groups === void 0 ? null : {
719
- year: Number(groups["year"]),
720
- month: Number(groups["month"]),
721
- day: Number(groups["day"])
722
- };
723
- };
724
- /** The month styles a date field renders in, and therefore the structures a
725
- * model copies back out of the document. */
726
- const READ_MONTH_STYLES = ["long", "short"];
727
- /** The instant every locale probe is formatted at: a two-digit day and a
728
- * two-digit month, so no part of the layout is a single character by
729
- * accident. */
730
- const LAYOUT_PROBE = Temporal.PlainDate.from("2026-10-15").toZonedDateTime("UTC").epochMilliseconds;
731
- /** Separators alone. A layout whose month is numeric and whose literals are
732
- * only these is `01/02/2026` with one locale's ordering imposed on it, which
733
- * is the reading this module refuses to guess. */
734
- const SEPARATORS_ONLY_RE = /^[\s./,-]*$/u;
735
- const REGEXP_META_RE = /[.*+?^${}()|[\]\\]/gu;
736
- /** A literal ICU emits between the parts (`. `, ` de `, `年`), matched with the
737
- * whitespace around it left to the writer. */
738
- const literalPattern = (literal) => literal.split(/\s+/u).map((chunk) => chunk.replace(REGEXP_META_RE, (meta) => `\\${meta}`)).join(String.raw`\s*`);
739
- /** The parts a calendar-date layout is built from. A formatter asked for a
740
- * day, a month and a year emits nothing else; anything else means the layout
741
- * is not one this reader can rebuild. */
742
- const LAYOUT_PART_KINDS = [
743
- "day",
744
- "month",
745
- "year",
746
- "literal"
747
- ];
748
- const layoutPartKind = (type) => LAYOUT_PART_KINDS.find((kind) => kind === type) ?? null;
749
- /**
750
- * The date structures one locale actually renders, as patterns: ICU's own
751
- * ordering and its own literals, so `1 de outubro de 2026` and
752
- * `2026. október 1.` are read where the field renders them that way. A layout
753
- * whose month is a number separated by nothing but punctuation is dropped: it
754
- * carries the day/month ambiguity this module never guesses at.
755
- */
756
- const localeLayouts = (locale) => {
757
- const layouts = [];
758
- for (const month of READ_MONTH_STYLES) {
759
- const parts = new Intl.DateTimeFormat(locale, {
760
- day: "numeric",
761
- month,
762
- year: "numeric",
763
- timeZone: "UTC"
764
- }).formatToParts(LAYOUT_PROBE);
765
- let source = "";
766
- let literals = "";
767
- let named = false;
768
- let readable = true;
769
- for (const part of parts) {
770
- const kind = layoutPartKind(part.type);
771
- if (kind === null) {
772
- readable = false;
773
- continue;
774
- }
775
- switch (kind) {
776
- case "day":
777
- source += String.raw`(?<day>\d{1,2})`;
778
- break;
779
- case "year":
780
- source += String.raw`(?<year>\d{4})`;
781
- break;
782
- case "month":
783
- named = /\p{L}/u.test(part.value);
784
- source += named ? String.raw`(?<month>[\p{L}\p{M}]+\.?)` : String.raw`(?<month>\d{1,2})`;
785
- break;
786
- case "literal":
787
- literals += part.value;
788
- source += literalPattern(part.value);
789
- }
790
- }
791
- if (readable && (named || !SEPARATORS_ONLY_RE.test(literals))) layouts.push(new RegExp(String.raw`^\s*${source}\s*$`, "u"));
792
- }
793
- return layouts;
794
- };
795
- const layoutCache = /* @__PURE__ */ new Map();
796
- const NUMERIC_RE = /^\d+$/u;
797
- const readLocaleLayout = (spec, locales) => {
798
- for (const locale of locales) {
799
- const layouts = layoutCache.get(locale) ?? localeLayouts(locale);
800
- layoutCache.set(locale, layouts);
801
- for (const layout of layouts) {
802
- const groups = layout.exec(spec)?.groups;
803
- if (groups === void 0) continue;
804
- const spelled = groups["month"] ?? "";
805
- const month = NUMERIC_RE.test(spelled) ? Number(spelled) : monthNumber(spelled, [locale]);
806
- if (month !== null) return {
807
- year: Number(groups["year"]),
808
- month,
809
- day: Number(groups["day"])
810
- };
811
- }
812
- }
813
- return null;
814
- };
815
- /** English is always read: it is the language of the schema and of most model
816
- * output, whatever the document's own language is. */
817
- const readingLocales = (options) => ["en", ...options?.locales ?? []];
818
- const invalidAsk = (input) => askForFix({
819
- input,
820
- expected: DATE_VALUE_EXPECTED,
821
- hint: DATE_VALUE_HINT
822
- });
823
- /** Both readings of a day/month pair, named, so the ask carries the fix rather
824
- * than a rule the model has to look up. */
825
- const ambiguousAsk$1 = ({ input, first, second, year }) => {
826
- const dayFirst = isoDate(year, second, first);
827
- const monthFirst = isoDate(year, first, second);
828
- if (dayFirst === null || monthFirst === null) return invalidAsk(input);
829
- return askForFix({
830
- input,
831
- expected: DATE_VALUE_EXPECTED,
832
- hint: `That reads as ${dayFirst} with the day first, or ${monthFirst} with the month first. Send "${dayFirst}" or "${monthFirst}".`
833
- });
834
- };
835
- /** One whole calendar date, the reading every field shares. */
836
- const readCalendarDate = (input, options) => {
837
- if (typeof input !== "string") return invalidAsk(input);
838
- const trimmed = input.trim();
839
- if (trimmed === "") return invalidAsk(input);
840
- const spec = ISO_DATETIME_RE.exec(trimmed)?.groups?.["date"] ?? trimmed;
841
- const locales = readingLocales(options);
842
- const unambiguous = readNumeric(spec) ?? readNamedMonth(spec, locales) ?? readLocaleLayout(spec, locales);
843
- if (unambiguous !== null) {
844
- const iso = isoDate(unambiguous.year, unambiguous.month, unambiguous.day);
845
- return iso === null ? invalidAsk(input) : readValueAs(input, iso);
846
- }
847
- const yearLast = YEAR_LAST_RE.exec(spec)?.groups;
848
- if (yearLast === void 0) return invalidAsk(input);
849
- const first = Number(yearLast["first"]);
850
- const second = Number(yearLast["second"]);
851
- const year = Number(yearLast["year"]);
852
- if (first > MAX_MONTH && second <= MAX_MONTH) {
853
- const iso = isoDate(year, second, first);
854
- return iso === null ? invalidAsk(input) : readValueAs(input, iso);
855
- }
856
- if (second > MAX_MONTH && first <= MAX_MONTH) {
857
- const iso = isoDate(year, first, second);
858
- return iso === null ? invalidAsk(input) : readValueAs(input, iso);
859
- }
860
- if (first > MAX_MONTH && second > MAX_MONTH) return invalidAsk(input);
861
- if (first === second) {
862
- const iso = isoDate(year, first, second);
863
- return iso === null ? invalidAsk(input) : readValueAs(input, iso);
864
- }
865
- return ambiguousAsk$1({
866
- input,
867
- first,
868
- second,
869
- year
870
- });
871
- };
872
- const YEAR_ONLY_RE = /^(?<year>\d{4})$/u;
873
- /** `2020-05`, `2020/5`: the four-digit head fixes which part is the year. */
874
- const YEAR_MONTH_RE = /^(?<year>\d{4})[-/](?<month>\d{1,2})$/u;
875
- /** `05/2020`, `5/2020`, `05.2020`: the four-digit tail fixes it the same way. */
876
- const MONTH_YEAR_RE = /^(?<month>\d{1,2})[-/.]\s*(?<year>\d{4})$/u;
877
- /**
878
- * A bare year or month as the first or last day it covers. Only a bound reads
879
- * these: as a start, `2020` means from the first day of 2020, and as an end,
880
- * through its last, which is what a model filtering "decisions from 2020"
881
- * means by it.
882
- */
883
- const readPartialDate = (trimmed, bound) => {
884
- const yearOnly = YEAR_ONLY_RE.exec(trimmed)?.groups;
885
- if (yearOnly !== void 0) {
886
- const year = Number(yearOnly["year"]);
887
- return bound === "start" ? isoDate(year, 1, 1) : isoDate(year, 12, 31);
888
- }
889
- const groups = (YEAR_MONTH_RE.exec(trimmed) ?? MONTH_YEAR_RE.exec(trimmed))?.groups;
890
- if (groups === void 0) return null;
891
- const year = Number(groups["year"]);
892
- const month = Number(groups["month"]);
893
- const first = isoDate(year, month, 1);
894
- if (first === null || bound === "start") return first;
895
- return isoDate(year, month, Temporal.PlainDate.from(first).daysInMonth);
896
- };
897
- /** How a model writes both ends of a range in one string, matched on the
898
- * string with its whitespace runs collapsed to one space (halves are trimmed
899
- * after the split), so no separator backtracks over a run of whitespace. The
900
- * unspaced dash and the slash split only where both halves are dates on
901
- * their own, so a single `2020-05` or `5/2020` never reads as two. */
902
- const RANGE_SEPARATORS = [
903
- /\.\./u,
904
- /[–—]/u,
905
- / to /iu,
906
- / - /u,
907
- /\//u,
908
- /-/u
909
- ];
910
- const WHITESPACE_RUN_RE = /\s+/gu;
911
- /** One bound read on its own: a whole date, else a partial one. */
912
- const readBoundHalf = (half, bound, options) => {
913
- const whole = readCalendarDate(half, options);
914
- return whole.ok ? whole.value : readPartialDate(half, bound);
915
- };
916
- /** Both ends of a range, when the string is one written into a single bound. */
917
- const readRange = (trimmed, options) => {
918
- const spaced = trimmed.replace(WHITESPACE_RUN_RE, " ");
919
- for (const separator of RANGE_SEPARATORS) {
920
- const halves = spaced.split(separator).map((half) => half.trim());
921
- const [left, right] = halves;
922
- if (halves.length !== 2 || left === void 0 || right === void 0) continue;
923
- const start = readBoundHalf(left, "start", options);
924
- const end = readBoundHalf(right, "end", options);
925
- if (start !== null && end !== null) return {
926
- start,
927
- end
928
- };
929
- }
930
- return null;
931
- };
932
- const rangeAsk = (input, range) => askForFix({
933
- input,
934
- expected: "a single date",
935
- hint: `This is one bound of a range: send the start and the end as two separate date properties (for example date_from "${range.start}" and date_to "${range.end}").`
936
- });
937
- /** Read a calendar date an agent spelled its own way, as ISO YYYY-MM-DD. With
938
- * a `bound`, a bare year or month reads as that end's day, and a whole range
939
- * in the one field asks for its two halves. */
940
- const normalizeDateValue = (input, options) => {
941
- const bound = options?.bound;
942
- if (bound === void 0 || typeof input !== "string") return readCalendarDate(input, options);
943
- const trimmed = input.trim();
944
- const range = readRange(trimmed, options);
945
- if (range !== null) return rangeAsk(input, range);
946
- const whole = readCalendarDate(input, options);
947
- if (whole.ok) return whole;
948
- const partial = readPartialDate(trimmed, bound);
949
- return partial === null ? whole : readValueAs(input, partial);
950
- };
951
- /** Years no range filter means literally: `0001-01-01` and `9999-12-31` are
952
- * how a database and a model spell "no limit on this side". Year 1000 is kept,
953
- * since a medieval charter is a real bound in a legal corpus. */
954
- const OPEN_BOUND_YEAR_BELOW = 1e3;
955
- const OPEN_BOUND_YEAR_FROM = 9e3;
956
- /**
957
- * Read one end of a date range. A placeholder or an open-ended sentinel date
958
- * is no bound at all, so the caller drops the property rather than filtering
959
- * to the year 1 or 9999.
960
- */
961
- const normalizeDateBound = (input, options) => {
962
- if (isAbsentPlaceholder(input)) return readAsAbsent(input);
963
- const result = normalizeDateValue(input, options);
964
- if (!result.ok) return result;
965
- const year = Temporal.PlainDate.from(result.value).year;
966
- return year < OPEN_BOUND_YEAR_BELOW || year >= OPEN_BOUND_YEAR_FROM ? readAsAbsent(input, "an open bound") : result;
967
- };
968
- //#endregion
969
227
  //#region src/eli.ts
970
228
  const ELI_EXPECTED = "an ELI";
971
229
  const ELI_HINT = "Pass the eli a search result returned.";
@@ -1247,45 +505,6 @@ const normalizeNumberInRange = (input, options) => {
1247
505
  return read;
1248
506
  };
1249
507
  //#endregion
1250
- //#region src/string-list.ts
1251
- /**
1252
- * Lists of strings on the agent wire.
1253
- *
1254
- * A model asked for an array often sends the array's JSON as a string
1255
- * (`"[\"a\", \"b\"]"`), or one bare string where the schema wanted a list of
1256
- * one. Both carry one meaning and are read. A comma-separated string carries
1257
- * one meaning only where an item cannot itself hold a comma: a list of court
1258
- * ids can be split, a list of search phrases cannot (`"Smith, J."` is one
1259
- * phrase), so the caller says which by `split`.
1260
- */
1261
- const STRING_LIST_EXPECTED = "a list of strings";
1262
- const STRING_LIST_HINT = "Send a JSON array of strings, for example [\"a\", \"b\"]";
1263
- const DELIMITERS_RE = /[,;\r\n]/u;
1264
- const isStringArray = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
1265
- /** The array a string spells as JSON, or null when it spells something else. */
1266
- const parseJsonArray = (trimmed) => {
1267
- if (!trimmed.startsWith("[")) return null;
1268
- const parsed = Result.try(() => JSON.parse(trimmed));
1269
- return parsed.isOk() && isStringArray(parsed.value) ? parsed.value : null;
1270
- };
1271
- /** Read a list of strings an agent spelled its own way. Only the list's own
1272
- * shape is read here: an array is taken as it is, and one holding anything
1273
- * but strings asks, since what an item should have been is the item's
1274
- * question, not the list's. */
1275
- const normalizeStringList = (input, options) => {
1276
- if (isStringArray(input)) return readValue(input);
1277
- if (typeof input !== "string") return askForFix({
1278
- input,
1279
- expected: STRING_LIST_EXPECTED,
1280
- hint: STRING_LIST_HINT
1281
- });
1282
- const parsed = parseJsonArray(input.trim());
1283
- if (parsed !== null) return readValueAs(input, parsed);
1284
- if (options.split === "never") return readValueAs(input, [input]);
1285
- const pieces = input.split(DELIMITERS_RE).map((piece) => piece.trim()).filter((piece) => piece !== "");
1286
- return readValueAs(input, pieces);
1287
- };
1288
- //#endregion
1289
508
  //#region src/uuid.ts
1290
509
  /**
1291
510
  * Record ids on the agent wire.