@orkestrel/template 0.0.6 → 0.0.7
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/README.md +8 -6
- package/dist/src/core/index.cjs +53 -31
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +130 -57
- package/dist/src/core/index.d.ts +130 -57
- package/dist/src/core/index.js +53 -31
- package/dist/src/core/index.js.map +1 -1
- package/package.json +9 -10
package/README.md
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
# @orkestrel/template
|
|
2
2
|
|
|
3
|
-
A
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
3
|
+
> A named, versionable template layer: `{{name}}` tokens in a `content`
|
|
4
|
+
> string, resolved against a values record by a single-pass fill engine, and
|
|
5
|
+
> registered and looked up by id through a self-owning `TemplateManager`.
|
|
6
|
+
|
|
7
|
+
Declare a template with the `createTemplate` function, fill it against the
|
|
8
|
+
values record your caller supplies, and register it in a `TemplateManager`
|
|
9
|
+
where several templates are looked up by id. Reach for `validate` where you
|
|
10
|
+
need to know which placeholders a fill would reject before you run it. Part of
|
|
9
11
|
the `@orkestrel` line.
|
|
10
12
|
|
|
11
13
|
## Install
|
package/dist/src/core/index.cjs
CHANGED
|
@@ -7,14 +7,14 @@ let _orkestrel_emitter = require("@orkestrel/emitter");
|
|
|
7
7
|
* `Template#fill` and `Template#validate`.
|
|
8
8
|
*
|
|
9
9
|
* @remarks
|
|
10
|
-
* Global-flagged, two-alternative pattern: a match of the
|
|
10
|
+
* Global-flagged, two-alternative pattern: a match of the first alternative
|
|
11
11
|
* (`\{{` — a literal backslash followed by `{{`) means "emit a literal
|
|
12
12
|
* `{{`" — the escape hatch for content that must show `{{` without
|
|
13
13
|
* triggering substitution. A match that instead populates capture group 1
|
|
14
14
|
* (`\{{([^{}]+?)\}\}`) means "substitute the named token" — group 1 is the
|
|
15
|
-
*
|
|
15
|
+
* untrimmed token text between the braces; every call site trims it
|
|
16
16
|
* (`token.trim()`) before using it as a lookup name, so `'{{ name }}'` still
|
|
17
|
-
* resolves `'name'`. The pattern
|
|
17
|
+
* resolves `'name'`. The pattern deliberately does not wrap the token in
|
|
18
18
|
* `\s*` — an unclosed `'{{' + ' '.repeat(n)` with no closing `}}` would
|
|
19
19
|
* otherwise force the regex engine into catastrophic backtracking over the
|
|
20
20
|
* whitespace run (O(n^2)); trimming after the match keeps the same
|
|
@@ -23,14 +23,20 @@ let _orkestrel_emitter = require("@orkestrel/emitter");
|
|
|
23
23
|
* instance's mutable `lastIndex` across scans.
|
|
24
24
|
*/
|
|
25
25
|
var FILL_PATTERN = /\\\{\{|\{\{([^{}]+?)\}\}/g;
|
|
26
|
-
/**
|
|
26
|
+
/**
|
|
27
|
+
* Holds `'error'`, the default `missing` policy for `Template#fill` /
|
|
28
|
+
* `TemplateManager#fill` when unspecified.
|
|
29
|
+
*/
|
|
27
30
|
var DEFAULT_MISSING_POLICY = "error";
|
|
28
|
-
/**
|
|
31
|
+
/**
|
|
32
|
+
* Holds `'en-US'`, the default `locale` for `Template#fill` /
|
|
33
|
+
* `TemplateManager#fill` when unspecified.
|
|
34
|
+
*/
|
|
29
35
|
var DEFAULT_LOCALE = "en-US";
|
|
30
36
|
/**
|
|
31
|
-
* Lists the prototype-pollution-unsafe field-path segments
|
|
32
|
-
*
|
|
33
|
-
* unresolved.
|
|
37
|
+
* Lists the prototype-pollution-unsafe field-path segments `'__proto__'`,
|
|
38
|
+
* `'constructor'`, and `'prototype'` — a fill lookup refuses to resolve a path
|
|
39
|
+
* containing one of them, treating the placeholder as unresolved.
|
|
34
40
|
*/
|
|
35
41
|
var UNSAFE_FIELD_SEGMENTS = Object.freeze([
|
|
36
42
|
"__proto__",
|
|
@@ -40,15 +46,16 @@ var UNSAFE_FIELD_SEGMENTS = Object.freeze([
|
|
|
40
46
|
//#endregion
|
|
41
47
|
//#region src/core/errors.ts
|
|
42
48
|
/**
|
|
43
|
-
* Represents an error thrown by the template layer
|
|
49
|
+
* Represents an error thrown by the template layer — a machine-readable
|
|
50
|
+
* {@link TemplateErrorCode} and an optional `context` record naming the
|
|
51
|
+
* offending id or placeholder name.
|
|
44
52
|
*
|
|
45
53
|
* @remarks
|
|
46
54
|
* Thrown for: a required placeholder staying unresolved under the `error`
|
|
47
55
|
* {@link MissingPolicy} (`MISSING`), an unknown template id
|
|
48
56
|
* (`NOTFOUND`), `createTemplate` handed invalid data (`INVALID`), and
|
|
49
57
|
* `TemplateManagerInterface#register` handed an id already present without
|
|
50
|
-
* `options.replace` (`CONFLICT`).
|
|
51
|
-
* offending id / name.
|
|
58
|
+
* `options.replace` (`CONFLICT`).
|
|
52
59
|
*/
|
|
53
60
|
var TemplateError = class extends Error {
|
|
54
61
|
code;
|
|
@@ -118,9 +125,9 @@ function formatValue(value, locale) {
|
|
|
118
125
|
* @remarks
|
|
119
126
|
* A prototype-pollution guard shared by `fillTemplate` and `Template#validate`
|
|
120
127
|
* so the two stay in lockstep: `path` normalizes to a segment array (a bare
|
|
121
|
-
* string `path` becomes a single-segment array); if
|
|
128
|
+
* string `path` becomes a single-segment array); if any segment appears in
|
|
122
129
|
* `UNSAFE_FIELD_SEGMENTS` (`'__proto__'`, `'constructor'`, `'prototype'`), the
|
|
123
|
-
* lookup is refused and `undefined` is returned
|
|
130
|
+
* lookup is refused and `undefined` is returned without ever calling
|
|
124
131
|
* `resolveField` — a path like `['__proto__', 'polluted']` can never reach
|
|
125
132
|
* the record's actual prototype chain through this function. Every other
|
|
126
133
|
* path resolves through `@orkestrel/contract`'s `resolveField`.
|
|
@@ -188,13 +195,13 @@ function resolveToken(record, placeholders, token) {
|
|
|
188
195
|
* never re-scanned. Each token resolves through `resolveToken`, the one rule
|
|
189
196
|
* `Template#validate` also applies: the matching declared
|
|
190
197
|
* {@link TemplatePlaceholder} (exact `name`) supplies its `path` (falling
|
|
191
|
-
* back to the token split on `.`);
|
|
198
|
+
* back to the token split on `.`); any path segment in `UNSAFE_FIELD_SEGMENTS`
|
|
192
199
|
* makes the token unresolved without ever calling `resolveField` (a
|
|
193
200
|
* prototype-pollution guard). A resolved value formats through `formatValue`; an
|
|
194
201
|
* unresolved value falls back to the placeholder's `fallback` when declared;
|
|
195
202
|
* otherwise `options.missing` governs — `'literal'` re-emits the original
|
|
196
203
|
* `{{name}}` text, `'empty'` emits `''`, and `'error'` emits `''` for every
|
|
197
|
-
* token but collects
|
|
204
|
+
* token but collects every unresolved required token (an undeclared token, or
|
|
198
205
|
* a declared token with `required !== false`) and throws one
|
|
199
206
|
* {@link TemplateError} coded `MISSING` listing them all, in first-appearance
|
|
200
207
|
* order, once the scan completes. An escaped `\{{` emits a literal `{{`.
|
|
@@ -278,7 +285,7 @@ function placeholderShape(placeholders) {
|
|
|
278
285
|
//#region src/core/templates/Template.ts
|
|
279
286
|
/**
|
|
280
287
|
* Represents a named, versionable template — `{{name}}` tokens in `content`,
|
|
281
|
-
* filled against a values record.
|
|
288
|
+
* filled against a values record — implementing `TemplateInterface` exactly.
|
|
282
289
|
*
|
|
283
290
|
* @remarks
|
|
284
291
|
* `missing` / `locale` seed this instance's default {@link TemplateFillOptions},
|
|
@@ -383,7 +390,7 @@ var Template = class {
|
|
|
383
390
|
* token rule `fill` also applies — a declared {@link TemplatePlaceholder}
|
|
384
391
|
* sharing its `name` supplies `path` (falling back to the token split on
|
|
385
392
|
* `.`), and the value resolves through `resolveSafeField`. The token is `missing`
|
|
386
|
-
* only when the value is unresolved
|
|
393
|
+
* only when the value is unresolved, no `fallback` is declared, and the
|
|
387
394
|
* placeholder is required (`required !== false`, including undeclared
|
|
388
395
|
* tokens). `extra` lists every `values` key with no declared placeholder.
|
|
389
396
|
*
|
|
@@ -445,21 +452,22 @@ var Template = class {
|
|
|
445
452
|
//#endregion
|
|
446
453
|
//#region src/core/templates/TemplateManager.ts
|
|
447
454
|
/**
|
|
448
|
-
* Represents the template registry — a self-owning, id-keyed record-holder for
|
|
449
|
-
* {@link TemplateInterface} instances a consumer registers, looks up,
|
|
450
|
-
* and validates by id
|
|
451
|
-
*
|
|
455
|
+
* Represents the template registry — a self-owning, id-keyed record-holder for
|
|
456
|
+
* the {@link TemplateInterface} instances a consumer registers, looks up,
|
|
457
|
+
* fills, and validates by id — implementing `TemplateManagerInterface`
|
|
458
|
+
* exactly.
|
|
452
459
|
*
|
|
453
460
|
* @remarks
|
|
454
|
-
*
|
|
461
|
+
* Singular and plural accessors, the batch `remove` overloads, and ownership
|
|
462
|
+
* of the emitter all sit here. `register` accepts either a constructed {@link TemplateInterface} (kept
|
|
455
463
|
* as-is, including its own `missing` / `locale` defaults) or a plain
|
|
456
464
|
* {@link TemplateOptions} bag — constructed into a `Template` with this
|
|
457
465
|
* manager's `missing` / `locale` defaults applied wherever the bag omits
|
|
458
466
|
* them. A duplicate `id` throws a {@link TemplateError} coded `CONFLICT`
|
|
459
467
|
* unless `options.replace` is `true`, in which case the existing entry is
|
|
460
|
-
* overwritten. `options.templates`
|
|
461
|
-
*
|
|
462
|
-
*
|
|
468
|
+
* overwritten. `options.templates` seeds the registry at construction without
|
|
469
|
+
* emitting `register` — only calls to `register` after construction emit.
|
|
470
|
+
* The batch `remove(ids)` form removes every present id and returns
|
|
463
471
|
* `true` only when every listed id was present.
|
|
464
472
|
*
|
|
465
473
|
* @example
|
|
@@ -537,8 +545,8 @@ var TemplateManager = class {
|
|
|
537
545
|
return [...this.#templates.values()];
|
|
538
546
|
}
|
|
539
547
|
/**
|
|
540
|
-
* Filters registered templates by name
|
|
541
|
-
* field must match
|
|
548
|
+
* Filters registered templates by `name`, `category`, and `tag` — every
|
|
549
|
+
* supplied field must match.
|
|
542
550
|
*
|
|
543
551
|
* @param query - The {@link TemplateQuery} to filter by; omit for every registered template
|
|
544
552
|
* @returns The matching templates
|
|
@@ -665,7 +673,8 @@ var TemplateManager = class {
|
|
|
665
673
|
//#endregion
|
|
666
674
|
//#region src/core/factories.ts
|
|
667
675
|
/**
|
|
668
|
-
* Creates a
|
|
676
|
+
* Creates a working {@link TemplateInterface} from a {@link TemplateOptions}
|
|
677
|
+
* bag, backed by the `Template` class.
|
|
669
678
|
*
|
|
670
679
|
* @param options - The template's `name` / `content`, an optional `id`
|
|
671
680
|
* (defaults to a generated UUID), `placeholders`, catalog metadata, and
|
|
@@ -673,19 +682,32 @@ var TemplateManager = class {
|
|
|
673
682
|
* @returns A working {@link TemplateInterface}
|
|
674
683
|
* @throws {@link TemplateError} Thrown when `options.placeholders` declares a duplicate `name` or an empty `path` (coded `INVALID`)
|
|
675
684
|
*
|
|
676
|
-
* @example
|
|
685
|
+
* @example Create a template and a registry
|
|
677
686
|
* ```ts
|
|
678
|
-
* import { createTemplate } from '@
|
|
687
|
+
* import { createTemplate, createTemplateManager } from '@orkestrel/template'
|
|
679
688
|
*
|
|
680
689
|
* const greeting = createTemplate({ name: 'greeting', content: 'Hi {{name}}' })
|
|
681
690
|
* greeting.fill({ name: 'Ada' }) // 'Hi Ada'
|
|
691
|
+
*
|
|
692
|
+
* const templates = createTemplateManager({
|
|
693
|
+
* templates: [
|
|
694
|
+
* { id: 'greeting', name: 'greeting', content: 'Hi {{name}}', category: 'mail' },
|
|
695
|
+
* { id: 'farewell', name: 'farewell', content: 'Bye {{name}}', category: 'mail' },
|
|
696
|
+
* { id: 'alert', name: 'alert', content: 'Alert: {{reason}}', category: 'ops' },
|
|
697
|
+
* ],
|
|
698
|
+
* })
|
|
699
|
+
* templates.fill('greeting', { name: 'Ada' }) // 'Hi Ada'
|
|
700
|
+
* templates.find({ category: 'mail' }).map((one) => one.id) // ['greeting', 'farewell']
|
|
701
|
+
* templates.has('alert') // true
|
|
702
|
+
* templates.has('missing') // false
|
|
682
703
|
* ```
|
|
683
704
|
*/
|
|
684
705
|
function createTemplate(options) {
|
|
685
706
|
return new Template(options);
|
|
686
707
|
}
|
|
687
708
|
/**
|
|
688
|
-
* Creates a
|
|
709
|
+
* Creates a working {@link TemplateManagerInterface}, optionally seeded with
|
|
710
|
+
* the templates the options carry, backed by the `TemplateManager` class.
|
|
689
711
|
*
|
|
690
712
|
* @param options - Optional initial `templates` seed collection and
|
|
691
713
|
* manager-wide `missing` / `locale` fill defaults, emitter `on` hooks, and
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["#missing","#locale","#contract","#templates","#emitter","#missing","#locale","#instantiate","#require","#isInstance"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/helpers.ts","../../../src/core/shapers.ts","../../../src/core/templates/Template.ts","../../../src/core/templates/TemplateManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { MissingPolicy } from './types.js'\n\n// Frozen default data for the template module — constants are\n// UPPER_SNAKE_CASE data, the sole home for module-scope literal defaults.\n\n/**\n * Holds the single-pass `{{name}}` substitution pattern shared by\n * `Template#fill` and `Template#validate`.\n *\n * @remarks\n * Global-flagged, two-alternative pattern: a match of the FIRST alternative\n * (`\\{{` — a literal backslash followed by `{{`) means \"emit a literal\n * `{{`\" — the escape hatch for content that must show `{{` without\n * triggering substitution. A match that instead populates capture group 1\n * (`\\{{([^{}]+?)\\}\\}`) means \"substitute the named token\" — group 1 is the\n * RAW (untrimmed) token text between the braces; every call site trims it\n * (`token.trim()`) before using it as a lookup name, so `'{{ name }}'` still\n * resolves `'name'`. The pattern intentionally does NOT wrap the token in\n * `\\s*` — an unclosed `'{{' + ' '.repeat(n)` with no closing `}}` would\n * otherwise force the regex engine into catastrophic backtracking over the\n * whitespace run (O(n^2)); trimming after the match keeps the same\n * whitespace tolerance without the backtracking hazard. Every call site\n * builds a fresh `RegExp` from `.source` / `.flags` rather than sharing this\n * instance's mutable `lastIndex` across scans.\n */\nexport const FILL_PATTERN = /\\\\\\{\\{|\\{\\{([^{}]+?)\\}\\}/g\n\n/** Holds the default `missing` policy for `Template#fill` / `TemplateManager#fill` when unspecified. */\nexport const DEFAULT_MISSING_POLICY: MissingPolicy = 'error'\n\n/** Holds the default `locale` for `Template#fill` / `TemplateManager#fill` when unspecified. */\nexport const DEFAULT_LOCALE = 'en-US'\n\n/**\n * Lists the prototype-pollution-unsafe field-path segments — a fill lookup\n * refuses to resolve ANY path containing one, treating the placeholder as\n * unresolved.\n */\nexport const UNSAFE_FIELD_SEGMENTS: readonly string[] = Object.freeze([\n\t'__proto__',\n\t'constructor',\n\t'prototype',\n])\n","import type { TemplateErrorCode } from './types.js'\n\n// Misuse of the template layer `throw`s a `TemplateError` carrying a\n// machine-readable `code`, so a `catch` branches on `error.code`.\n\n/**\n * Represents an error thrown by the template layer.\n *\n * @remarks\n * Thrown for: a required placeholder staying unresolved under the `error`\n * {@link MissingPolicy} (`MISSING`), an unknown template id\n * (`NOTFOUND`), `createTemplate` handed invalid data (`INVALID`), and\n * `TemplateManagerInterface#register` handed an id already present without\n * `options.replace` (`CONFLICT`). `context`, when present, carries the\n * offending id / name.\n */\nexport class TemplateError extends Error {\n\treadonly code: TemplateErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: TemplateErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'TemplateError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrows an unknown caught value to a {@link TemplateError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns True if `value` is a {@link TemplateError}; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateError } from '@src/core'\n *\n * try {\n * \tmanager.fill('missing')\n * } catch (error) {\n * \tif (isTemplateError(error) && error.code === 'NOTFOUND') return\n * }\n * ```\n */\nexport function isTemplateError(value: unknown): value is TemplateError {\n\treturn value instanceof TemplateError\n}\n","import type { FieldPath } from '@orkestrel/contract'\nimport type {\n\tTemplateFillContext,\n\tTemplateFillValues,\n\tTemplatePlaceholder,\n\tTemplateTokenResolution,\n} from './types.js'\nimport { isFiniteNumber, resolveField } from '@orkestrel/contract'\nimport {\n\tDEFAULT_LOCALE,\n\tDEFAULT_MISSING_POLICY,\n\tFILL_PATTERN,\n\tUNSAFE_FIELD_SEGMENTS,\n} from './constants.js'\nimport { TemplateError } from './errors.js'\n\n// The templates pure-leaf inventory — every function here is a\n// referentially-transparent computation with no instance state, exported and\n// independently unit-testable. `Template#fill` / `#validate` route through\n// these leaves rather than duplicating the substitution logic.\n\n/**\n * Formats a resolved fill value for substitution into a template's `content`.\n *\n * @remarks\n * A finite number renders with the given locale's thousand grouping (through\n * `toLocaleString`); every other value — including `null` — String-coerces.\n * `null` therefore renders as the literal string `'null'`, matching\n * `String(value)` exactly, so a resolved `null` is visible in the output\n * rather than silently empty. An\n * invalid BCP-47 `locale` tag throws a `RangeError` from the underlying\n * `toLocaleString` call when `value` is a finite number — this is a caller\n * error (an invalid locale argument), by design, and is not caught here.\n *\n * @param value - The resolved value to format\n * @param locale - The locale used for finite-number formatting\n * @returns The formatted string\n *\n * @example\n * ```ts\n * import { formatValue } from '@src/core'\n *\n * formatValue(5010, 'en-US') // '5,010'\n * formatValue(null, 'en-US') // 'null'\n * ```\n */\nexport function formatValue(value: unknown, locale: string): string {\n\tif (isFiniteNumber(value)) return value.toLocaleString(locale)\n\treturn String(value)\n}\n\n/**\n * Resolves a field path against a fill-values record, refusing any path that\n * touches a prototype-pollution-unsafe segment.\n *\n * @remarks\n * A prototype-pollution guard shared by `fillTemplate` and `Template#validate`\n * so the two stay in lockstep: `path` normalizes to a segment array (a bare\n * string `path` becomes a single-segment array); if ANY segment appears in\n * `UNSAFE_FIELD_SEGMENTS` (`'__proto__'`, `'constructor'`, `'prototype'`), the\n * lookup is refused and `undefined` is returned WITHOUT ever calling\n * `resolveField` — a path like `['__proto__', 'polluted']` can never reach\n * the record's actual prototype chain through this function. Every other\n * path resolves through `@orkestrel/contract`'s `resolveField`.\n *\n * @param record - The fill-values record to resolve against\n * @param path - The field path — a single segment or a segment array\n * @returns The resolved value, or `undefined` when unresolved or the path is unsafe\n *\n * @example\n * ```ts\n * import { resolveSafeField } from '@src/core'\n *\n * resolveSafeField({ a: { b: 1 } }, ['a', 'b']) // 1\n * resolveSafeField({}, ['__proto__', 'polluted']) // undefined\n * ```\n */\nexport function resolveSafeField(record: TemplateFillValues, path: FieldPath): unknown {\n\tconst segments = Array.isArray(path) ? path : [path]\n\tif (segments.some((segment) => UNSAFE_FIELD_SEGMENTS.includes(segment))) return undefined\n\treturn resolveField(record, path)\n}\n\n/**\n * Resolves one `{{name}}` token against the declared placeholders and the\n * fill-values record.\n *\n * @remarks\n * The single implementation of the token rule `fillTemplate` and\n * `Template#validate` both apply, so the two can never drift: the declared\n * {@link TemplatePlaceholder} sharing the token's `name` (exact match)\n * supplies its `path`, falling back to the token split on `.`; the value\n * resolves through `resolveSafeField`, so any segment in\n * `UNSAFE_FIELD_SEGMENTS` yields `undefined` without ever calling\n * `resolveField`; `required` is `true` for an undeclared token and for a\n * declared placeholder whose `required` is not `false`. The token is passed\n * already trimmed. `fallback` is not applied here — it is read from\n * `declared` by each caller, because `fill` substitutes it and `validate`\n * only counts it.\n *\n * @param record - The fill-values record the token resolves against\n * @param placeholders - The declared placeholders the token matches by name\n * @param token - The trimmed token text, without its `{{` / `}}` delimiters\n * @returns The {@link TemplateTokenResolution} for the token\n *\n * @example\n * ```ts\n * import { resolveToken } from '@src/core'\n *\n * resolveToken({ name: 'Ada' }, [], 'name').value // 'Ada'\n * resolveToken({}, [{ name: 'nickname', required: false }], 'nickname').required // false\n * ```\n */\nexport function resolveToken(\n\trecord: TemplateFillValues,\n\tplaceholders: readonly TemplatePlaceholder[],\n\ttoken: string,\n): TemplateTokenResolution {\n\tconst declared = placeholders.find((placeholder) => placeholder.name === token)\n\tconst path = declared?.path ?? token.split('.')\n\treturn {\n\t\tvalue: resolveSafeField(record, path),\n\t\tdeclared,\n\t\trequired: declared === undefined || declared.required !== false,\n\t}\n}\n\n/**\n * Substitutes every `{{name}}` token in `content` in a single pass.\n *\n * @remarks\n * Uses a fresh `RegExp` clone of `FILL_PATTERN` per call (never sharing its\n * `lastIndex`) and a single `String#replace` scan — substituted output is\n * never re-scanned. Each token resolves through `resolveToken`, the one rule\n * `Template#validate` also applies: the matching declared\n * {@link TemplatePlaceholder} (exact `name`) supplies its `path` (falling\n * back to the token split on `.`); ANY path segment in `UNSAFE_FIELD_SEGMENTS`\n * makes the token unresolved without ever calling `resolveField` (a\n * prototype-pollution guard). A resolved value formats through `formatValue`; an\n * unresolved value falls back to the placeholder's `fallback` when declared;\n * otherwise `options.missing` governs — `'literal'` re-emits the original\n * `{{name}}` text, `'empty'` emits `''`, and `'error'` emits `''` for every\n * token but collects EVERY unresolved required token (an undeclared token, or\n * a declared token with `required !== false`) and throws one\n * {@link TemplateError} coded `MISSING` listing them all, in first-appearance\n * order, once the scan completes. An escaped `\\{{` emits a literal `{{`.\n *\n * Called with no declared `placeholders` and `{ missing: 'empty' }`, this is a\n * bare interpolation over `content` — every token resolves by dotted path\n * against the values record and every unresolved token emits `''`.\n * `FILL_PATTERN`'s token class (`[^{}]`) excludes `{`, so a token containing\n * `{` never matches and the surrounding `{{` stays literal.\n *\n * @param content - The template content carrying `{{name}}` tokens\n * @param values - The values tokens resolve against\n * @param options - `missing` (default `'error'`), `locale` (default `'en-US'`), and the declared `placeholders` (default none) tokens resolve against\n * @returns The substituted content\n *\n * @example\n * ```ts\n * import { fillTemplate } from '@src/core'\n *\n * fillTemplate('Hi {{name}}', { name: 'Ada' }) // 'Hi Ada'\n * fillTemplate('Limit {{limit}}', { limit: 5010 }, { missing: 'empty' }) // 'Limit 5,010'\n * ```\n */\nexport function fillTemplate(\n\tcontent: string,\n\tvalues?: TemplateFillValues,\n\toptions?: TemplateFillContext,\n): string {\n\tconst placeholders = options?.placeholders ?? []\n\tconst missing = options?.missing ?? DEFAULT_MISSING_POLICY\n\tconst locale = options?.locale ?? DEFAULT_LOCALE\n\tconst record = values ?? {}\n\n\tconst missingNames: string[] = []\n\tconst seen = new Set<string>()\n\n\tconst pattern = new RegExp(FILL_PATTERN.source, FILL_PATTERN.flags)\n\tconst result = content.replace(pattern, (matchText: string, rawToken: string | undefined) => {\n\t\tif (rawToken === undefined) return '{{'\n\t\tconst token = rawToken.trim()\n\n\t\tconst { value, declared, required } = resolveToken(record, placeholders, token)\n\n\t\tif (value !== undefined) return formatValue(value, locale)\n\t\tif (declared?.fallback !== undefined) return formatValue(declared.fallback, locale)\n\n\t\tif (missing === 'literal') return matchText\n\t\tif (missing === 'empty') return ''\n\n\t\tif (required && !seen.has(token)) {\n\t\t\tseen.add(token)\n\t\t\tmissingNames.push(token)\n\t\t}\n\t\treturn ''\n\t})\n\n\tif (missing === 'error' && missingNames.length > 0) {\n\t\tthrow new TemplateError(\n\t\t\t'MISSING',\n\t\t\t`Missing required placeholder(s): ${missingNames.join(', ')}`,\n\t\t\t{ missing: missingNames },\n\t\t)\n\t}\n\n\treturn result\n}\n","import type { ContractShape } from '@orkestrel/contract'\nimport type { TemplatePlaceholder } from './types.js'\nimport { objectShape, optionalShape, stringShape } from '@orkestrel/contract'\n\n// The templates shape-value inventory — every function here builds an\n// `@orkestrel/contract` shape from declared template data. Shapers sit above\n// the `helpers.ts` leaf pair: they consume it, and it never consumes them.\n\n/**\n * Builds the `@orkestrel/contract` object shape describing a template's\n * declared placeholders.\n *\n * @remarks\n * Each placeholder becomes a `stringShape` carrying its `description`;\n * `required === false` wraps it in `optionalShape`. Used by `Template` to\n * compile its `parameters()` contract once per instance.\n *\n * @param placeholders - The declared placeholders to shape\n * @returns The contract shape for `createContract`\n *\n * @example\n * ```ts\n * import { placeholderShape } from '@src/core'\n * import { createContract } from '@orkestrel/contract'\n *\n * const contract = createContract(placeholderShape([{ name: 'city' }]))\n * ```\n */\nexport function placeholderShape(placeholders: readonly TemplatePlaceholder[]): ContractShape {\n\tconst properties: Record<string, ContractShape> = {}\n\tfor (const placeholder of placeholders) {\n\t\tconst description = placeholder.description\n\t\tconst field = stringShape({\n\t\t\t...(description !== undefined ? { description } : {}),\n\t\t})\n\t\tproperties[placeholder.name] = placeholder.required === false ? optionalShape(field) : field\n\t}\n\treturn objectShape(properties)\n}\n","import type { ContractInterface } from '@orkestrel/contract'\nimport type {\n\tMissingPolicy,\n\tTemplateDefinition,\n\tTemplateFillOptions,\n\tTemplateFillValues,\n\tTemplateInterface,\n\tTemplateOptions,\n\tTemplatePlaceholder,\n\tTemplateValidationResult,\n} from '../types.js'\nimport { createContract, schemaToParameters } from '@orkestrel/contract'\nimport { DEFAULT_LOCALE, DEFAULT_MISSING_POLICY, FILL_PATTERN } from '../constants.js'\nimport { fillTemplate, resolveToken } from '../helpers.js'\nimport { placeholderShape } from '../shapers.js'\nimport { TemplateError } from '../errors.js'\n\n/**\n * Represents a named, versionable template — `{{name}}` tokens in `content`,\n * filled against a values record.\n *\n * @remarks\n * `missing` / `locale` seed this instance's default {@link TemplateFillOptions},\n * overridable per `fill` call. Its `parameters()` contract (built from\n * `placeholders` through `placeholderShape`) compiles once, in the constructor.\n *\n * @throws {@link TemplateError} Thrown when `options.placeholders` declares a duplicate `name` or an empty `path` (coded `INVALID`)\n *\n * @example\n * ```ts\n * const greeting = new Template({ name: 'greeting', content: 'Hi {{name}}' })\n * greeting.fill({ name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport class Template implements TemplateInterface {\n\treadonly #missing: MissingPolicy\n\treadonly #locale: string\n\treadonly #contract: ContractInterface<unknown>\n\treadonly id: string\n\treadonly name: string\n\treadonly content: string\n\treadonly placeholders: readonly TemplatePlaceholder[]\n\treadonly summary?: string\n\treadonly description?: string\n\treadonly category?: string\n\treadonly tags?: readonly string[]\n\n\tconstructor(options: TemplateOptions) {\n\t\tconst placeholders = options.placeholders ?? []\n\t\tconst seenNames = new Set<string>()\n\t\tfor (const placeholder of placeholders) {\n\t\t\tif (seenNames.has(placeholder.name)) {\n\t\t\t\tthrow new TemplateError('INVALID', `Duplicate placeholder name: ${placeholder.name}`, {\n\t\t\t\t\tname: placeholder.name,\n\t\t\t\t})\n\t\t\t}\n\t\t\tseenNames.add(placeholder.name)\n\t\t\tif (Array.isArray(placeholder.path) && placeholder.path.length === 0) {\n\t\t\t\tthrow new TemplateError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Placeholder path must not be empty: ${placeholder.name}`,\n\t\t\t\t\t{ name: placeholder.name },\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tthis.id = typeof options.id === 'string' ? options.id : crypto.randomUUID()\n\t\tthis.name = options.name\n\t\tthis.content = options.content\n\t\tthis.placeholders = placeholders\n\t\tif (options.summary !== undefined) this.summary = options.summary\n\t\tif (options.description !== undefined) this.description = options.description\n\t\tif (options.category !== undefined) this.category = options.category\n\t\tif (options.tags !== undefined) this.tags = options.tags\n\t\tthis.#missing = options.missing ?? DEFAULT_MISSING_POLICY\n\t\tthis.#locale = options.locale ?? DEFAULT_LOCALE\n\t\tthis.#contract = createContract(placeholderShape(this.placeholders))\n\t}\n\n\t/**\n\t * Returns the plain, JSON-serializable data this template carries.\n\t *\n\t * @returns The {@link TemplateDefinition} record\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({ name: 'greeting', content: 'Hi {{name}}' })\n\t * instance.definition().name // 'greeting'\n\t * ```\n\t */\n\tdefinition(): TemplateDefinition {\n\t\treturn {\n\t\t\tid: this.id,\n\t\t\tname: this.name,\n\t\t\tcontent: this.content,\n\t\t\tplaceholders: this.placeholders,\n\t\t\t...(this.summary !== undefined ? { summary: this.summary } : {}),\n\t\t\t...(this.description !== undefined ? { description: this.description } : {}),\n\t\t\t...(this.category !== undefined ? { category: this.category } : {}),\n\t\t\t...(this.tags !== undefined ? { tags: this.tags } : {}),\n\t\t}\n\t}\n\n\t/**\n\t * Substitutes every `{{name}}` token in `content` against `values`.\n\t *\n\t * @param values - The values tokens resolve against\n\t * @param options - Per-call overrides for this instance's `missing` / `locale` defaults\n\t * @returns The substituted content\n\t * @throws {@link TemplateError} Thrown when a required placeholder stays unresolved under the `'error'` policy (coded `MISSING`)\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({ name: 'greeting', content: 'Hi {{name}}' })\n\t * instance.fill({ name: 'Ada' }) // 'Hi Ada'\n\t * ```\n\t */\n\tfill(values?: TemplateFillValues, options?: TemplateFillOptions): string {\n\t\treturn fillTemplate(this.content, values, {\n\t\t\tmissing: options?.missing ?? this.#missing,\n\t\t\tlocale: options?.locale ?? this.#locale,\n\t\t\tplaceholders: this.placeholders,\n\t\t})\n\t}\n\n\t/**\n\t * Reports which required placeholders would stay unresolved, and which\n\t * `values` keys go unused, without producing output.\n\t *\n\t * @remarks\n\t * Content-token driven: scans `this.content` for every `{{name}}` token\n\t * (skipping escaped `\\{{` matches) the same way `fill` does, so `validate`\n\t * predicts `fill`'s `'error'`-{@link MissingPolicy} outcome exactly — a\n\t * token reported here as missing is precisely a token that would throw\n\t * under `fill(values, { missing: 'error' })`. For each distinct token\n\t * (first-appearance order, trimmed): `resolveToken` applies the one shared\n\t * token rule `fill` also applies — a declared {@link TemplatePlaceholder}\n\t * sharing its `name` supplies `path` (falling back to the token split on\n\t * `.`), and the value resolves through `resolveSafeField`. The token is `missing`\n\t * only when the value is unresolved AND no `fallback` is declared AND the\n\t * placeholder is required (`required !== false`, including undeclared\n\t * tokens). `extra` lists every `values` key with no declared placeholder.\n\t *\n\t * @param values - The values to check\n\t * @returns The {@link TemplateValidationResult}\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({\n\t * \tname: 'greeting',\n\t * \tcontent: 'Hi {{name}}',\n\t * \tplaceholders: [{ name: 'name' }],\n\t * })\n\t * instance.validate({}).missing // ['name']\n\t * ```\n\t */\n\tvalidate(values?: TemplateFillValues): TemplateValidationResult {\n\t\tconst record = values ?? {}\n\t\tconst missing: string[] = []\n\t\tconst seen = new Set<string>()\n\n\t\tconst pattern = new RegExp(FILL_PATTERN.source, FILL_PATTERN.flags)\n\t\tfor (const match of this.content.matchAll(pattern)) {\n\t\t\tconst rawToken = match[1]\n\t\t\tif (rawToken === undefined) continue\n\t\t\tconst token = rawToken.trim()\n\t\t\tif (seen.has(token)) continue\n\t\t\tseen.add(token)\n\n\t\t\tconst { value, declared, required } = resolveToken(record, this.placeholders, token)\n\n\t\t\tif (value === undefined && declared?.fallback === undefined && required) {\n\t\t\t\tmissing.push(token)\n\t\t\t}\n\t\t}\n\n\t\tconst declaredNames = new Set(this.placeholders.map((placeholder) => placeholder.name))\n\t\tconst extra = Object.keys(record).filter((key) => !declaredNames.has(key))\n\n\t\treturn { valid: missing.length === 0, missing, extra }\n\t}\n\n\t/**\n\t * Projects this template's placeholders to the open tool-parameters record\n\t * shape.\n\t *\n\t * @returns The compiled parameters record, or `undefined` when `schemaToParameters` yields none\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({\n\t * \tname: 'greeting',\n\t * \tcontent: 'Hi {{name}}',\n\t * \tplaceholders: [{ name: 'name' }],\n\t * })\n\t * instance.parameters()\n\t * ```\n\t */\n\tparameters(): Readonly<Record<string, unknown>> | undefined {\n\t\treturn schemaToParameters(this.#contract.schema)\n\t}\n}\n","import type {\n\tMissingPolicy,\n\tTemplateFillValues,\n\tTemplateFillOptions,\n\tTemplateInterface,\n\tTemplateManagerEventMap,\n\tTemplateManagerInterface,\n\tTemplateManagerOptions,\n\tTemplateOptions,\n\tTemplateQuery,\n\tTemplateRegisterOptions,\n\tTemplateValidationResult,\n} from '../types.js'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport { Emitter } from '@orkestrel/emitter'\nimport { DEFAULT_LOCALE, DEFAULT_MISSING_POLICY } from '../constants.js'\nimport { TemplateError } from '../errors.js'\nimport { Template } from './Template.js'\n\n/**\n * Represents the template registry — a self-owning, id-keyed record-holder for the\n * {@link TemplateInterface} instances a consumer registers, looks up, fills,\n * and validates by id, with singular/plural accessors, batch `remove`\n * overloads, and emitter ownership.\n *\n * @remarks\n * `register` accepts either a constructed {@link TemplateInterface} (kept\n * as-is, including its own `missing` / `locale` defaults) or a plain\n * {@link TemplateOptions} bag — constructed into a `Template` with this\n * manager's `missing` / `locale` defaults applied wherever the bag omits\n * them. A duplicate `id` throws a {@link TemplateError} coded `CONFLICT`\n * unless `options.replace` is `true`, in which case the existing entry is\n * overwritten. `options.templates` SEEDS the registry at construction\n * WITHOUT emitting `register` — only calls to `register` after construction\n * emit. The batch `remove(ids)` form removes every present id and returns\n * `true` only when every listed id was present.\n *\n * @example\n * ```ts\n * import { TemplateManager } from '@src/core'\n *\n * const manager = new TemplateManager()\n * const instance = manager.register({ name: 'greeting', content: 'Hi {{name}}' })\n * manager.fill(instance.id, { name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport class TemplateManager implements TemplateManagerInterface {\n\treadonly #templates = new Map<string, TemplateInterface>()\n\treadonly #emitter: Emitter<TemplateManagerEventMap>\n\treadonly #missing: MissingPolicy\n\treadonly #locale: string\n\n\tconstructor(options?: TemplateManagerOptions) {\n\t\tconst on = options?.on\n\t\tconst error = options?.error\n\t\tthis.#emitter = new Emitter<TemplateManagerEventMap>({\n\t\t\t...(on !== undefined ? { on } : {}),\n\t\t\t...(error !== undefined ? { error } : {}),\n\t\t})\n\t\tthis.#missing = options?.missing ?? DEFAULT_MISSING_POLICY\n\t\tthis.#locale = options?.locale ?? DEFAULT_LOCALE\n\t\tfor (const template of options?.templates ?? []) {\n\t\t\tconst instance = this.#instantiate(template)\n\t\t\tthis.#templates.set(instance.id, instance)\n\t\t}\n\t}\n\n\tget emitter(): EmitterInterface<TemplateManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget count(): number {\n\t\treturn this.#templates.size\n\t}\n\n\t/**\n\t * Registers a template — a constructed {@link TemplateInterface} (kept\n\t * as-is) or a plain {@link TemplateOptions} bag (constructed into a\n\t * `Template` with this manager's `missing` / `locale` defaults applied\n\t * wherever the bag omits them).\n\t *\n\t * @param template - The template instance or options to register\n\t * @param options - `replace` — overwrite an existing entry sharing the same id instead of throwing\n\t * @returns The registered {@link TemplateInterface}\n\t * @throws {@link TemplateError} Thrown when the id is already registered and `options.replace` is not `true` (coded `CONFLICT`), or when an options bag declares a duplicate placeholder `name` or an empty `path` (coded `INVALID`)\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = manager.register({ id: 'greeting', name: 'greeting', content: 'Hi {{name}}' })\n\t * ```\n\t */\n\tregister(\n\t\ttemplate: TemplateInterface | TemplateOptions,\n\t\toptions?: TemplateRegisterOptions,\n\t): TemplateInterface {\n\t\tconst instance = this.#instantiate(template)\n\t\tconst existing = this.#templates.get(instance.id)\n\t\tif (existing !== undefined && options?.replace !== true) {\n\t\t\tthrow new TemplateError('CONFLICT', `Template already registered: ${instance.id}`, {\n\t\t\t\tid: instance.id,\n\t\t\t})\n\t\t}\n\t\tthis.#templates.set(instance.id, instance)\n\t\tthis.#emitter.emit('register', instance)\n\t\treturn instance\n\t}\n\n\t/**\n\t * Returns one registered {@link TemplateInterface} by id.\n\t *\n\t * @param id - The template id\n\t * @returns The registered {@link TemplateInterface}, or `undefined` when `id` is unregistered\n\t */\n\ttemplate(id: string): TemplateInterface | undefined {\n\t\treturn this.#templates.get(id)\n\t}\n\n\t/**\n\t * Lists every registered template.\n\t *\n\t * @returns A snapshot array of every registered {@link TemplateInterface}\n\t */\n\ttemplates(): readonly TemplateInterface[] {\n\t\treturn [...this.#templates.values()]\n\t}\n\n\t/**\n\t * Filters registered templates by name / category / tag — every supplied\n\t * field must match (logical AND).\n\t *\n\t * @param query - The {@link TemplateQuery} to filter by; omit for every registered template\n\t * @returns The matching templates\n\t */\n\tfind(query?: TemplateQuery): readonly TemplateInterface[] {\n\t\tif (query === undefined) return this.templates()\n\t\treturn this.templates().filter((instance) => {\n\t\t\tif (query.name !== undefined && instance.name !== query.name) return false\n\t\t\tif (query.category !== undefined && instance.category !== query.category) return false\n\t\t\tif (query.tag !== undefined && !(instance.tags ?? []).includes(query.tag)) return false\n\t\t\treturn true\n\t\t})\n\t}\n\n\t/**\n\t * Tests whether a template id is registered.\n\t *\n\t * @param id - The template id\n\t * @returns True if `id` is registered; false otherwise\n\t */\n\thas(id: string): boolean {\n\t\treturn this.#templates.has(id)\n\t}\n\n\t/**\n\t * Removes one, several, or every registered template.\n\t *\n\t * @remarks\n\t * `remove()` removes every registered template, emitting `remove` once per\n\t * instance. `remove(id)` removes one template by id, emitting `remove` and\n\t * returning `true` when it existed, `false` otherwise. `remove(ids)`\n\t * removes every listed id that is present, emitting `remove` once per\n\t * removed instance, and returns `true` only when every listed id was\n\t * present.\n\t *\n\t * @param target - Omit to remove all, a single id, or a list of ids\n\t * @returns `boolean` for the single-id / list-of-ids forms; `void` for the remove-all form\n\t */\n\t// `readonly string[]` is not assignable to `id: string`, so a list resolves to the\n\t// batch signature whatever order the signatures are declared in.\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(): void\n\tremove(target?: string | readonly string[]): boolean | void {\n\t\tif (target === undefined) {\n\t\t\tfor (const instance of this.#templates.values()) this.#emitter.emit('remove', instance)\n\t\t\tthis.#templates.clear()\n\t\t\treturn\n\t\t}\n\t\tif (typeof target === 'string') {\n\t\t\tconst instance = this.#templates.get(target)\n\t\t\tif (instance === undefined) return false\n\t\t\tthis.#templates.delete(target)\n\t\t\tthis.#emitter.emit('remove', instance)\n\t\t\treturn true\n\t\t}\n\t\tlet all = true\n\t\tfor (const id of target) {\n\t\t\tconst instance = this.#templates.get(id)\n\t\t\tif (instance === undefined) {\n\t\t\t\tall = false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tthis.#templates.delete(id)\n\t\t\tthis.#emitter.emit('remove', instance)\n\t\t}\n\t\treturn all\n\t}\n\n\t/** Removes every registered template, emitting `clear`. */\n\tclear(): void {\n\t\tthis.#templates.clear()\n\t\tthis.#emitter.emit('clear')\n\t}\n\n\t/**\n\t * Tears down the registry: drops every registered template and destroys the\n\t * owned emitter. Idempotent.\n\t *\n\t * @remarks\n\t * Teardown is not an observable registry operation and the emitter is being\n\t * released, so this emits neither `clear` nor `remove`. The emitter is torn\n\t * down last, after the registry is dropped.\n\t *\n\t * @example\n\t * ```ts\n\t * const manager = new TemplateManager()\n\t * manager.destroy()\n\t * manager.emitter.destroyed // true\n\t * ```\n\t */\n\tdestroy(): void {\n\t\tthis.#templates.clear()\n\t\tthis.#emitter.destroy()\n\t}\n\n\t/**\n\t * Fills a registered template by id.\n\t *\n\t * @param id - The template id\n\t * @param values - The values tokens resolve against\n\t * @param options - Per-call overrides for the template's `missing` / `locale` defaults\n\t * @returns The substituted content\n\t * @throws {@link TemplateError} coded `NOTFOUND` when `id` is unknown\n\t * @throws {@link TemplateError} Thrown when a required placeholder stays unresolved under the `'error'` policy (coded `MISSING`)\n\t */\n\tfill(id: string, values?: TemplateFillValues, options?: TemplateFillOptions): string {\n\t\treturn this.#require(id).fill(values, options)\n\t}\n\n\t/**\n\t * Validates values against a registered template by id.\n\t *\n\t * @param id - The template id\n\t * @param values - The values to check\n\t * @returns The {@link TemplateValidationResult}\n\t * @throws {@link TemplateError} coded `NOTFOUND` when `id` is unknown\n\t */\n\tvalidate(id: string, values?: TemplateFillValues): TemplateValidationResult {\n\t\treturn this.#require(id).validate(values)\n\t}\n\n\t/**\n\t * Projects a registered template's parameters by id.\n\t *\n\t * @param id - The template id\n\t * @returns The compiled parameters record, or `undefined` when the template has none\n\t * @throws {@link TemplateError} coded `NOTFOUND` when `id` is unknown\n\t */\n\tparameters(id: string): Readonly<Record<string, unknown>> | undefined {\n\t\treturn this.#require(id).parameters()\n\t}\n\n\t#instantiate(template: TemplateInterface | TemplateOptions): TemplateInterface {\n\t\tif (this.#isInstance(template)) return template\n\t\treturn new Template({\n\t\t\t...template,\n\t\t\tmissing: template.missing ?? this.#missing,\n\t\t\tlocale: template.locale ?? this.#locale,\n\t\t})\n\t}\n\n\t// A TemplateOptions bag is plain data with no `fill` / `validate` /\n\t// `parameters` methods; a TemplateInterface instance always exposes all three.\n\t#isInstance(template: TemplateInterface | TemplateOptions): template is TemplateInterface {\n\t\treturn (\n\t\t\t'fill' in template &&\n\t\t\ttypeof template.fill === 'function' &&\n\t\t\t'validate' in template &&\n\t\t\ttypeof template.validate === 'function' &&\n\t\t\t'parameters' in template &&\n\t\t\ttypeof template.parameters === 'function'\n\t\t)\n\t}\n\n\t// Every by-id operation that needs a template to proceed shares this lookup.\n\t// The `template` accessor deliberately does not, and returns `undefined`.\n\t#require(id: string): TemplateInterface {\n\t\tconst instance = this.#templates.get(id)\n\t\tif (instance === undefined) {\n\t\t\tthrow new TemplateError('NOTFOUND', `Unknown template id: ${id}`, { id })\n\t\t}\n\t\treturn instance\n\t}\n}\n","import type {\n\tTemplateInterface,\n\tTemplateManagerInterface,\n\tTemplateManagerOptions,\n\tTemplateOptions,\n} from './types.js'\nimport { Template } from './templates/Template.js'\nimport { TemplateManager } from './templates/TemplateManager.js'\n\n/**\n * Creates a template.\n *\n * @param options - The template's `name` / `content`, an optional `id`\n * (defaults to a generated UUID), `placeholders`, catalog metadata, and\n * `missing` / `locale` fill defaults\n * @returns A working {@link TemplateInterface}\n * @throws {@link TemplateError} Thrown when `options.placeholders` declares a duplicate `name` or an empty `path` (coded `INVALID`)\n *\n * @example\n * ```ts\n * import { createTemplate } from '@src/core'\n *\n * const greeting = createTemplate({ name: 'greeting', content: 'Hi {{name}}' })\n * greeting.fill({ name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport function createTemplate(options: TemplateOptions): TemplateInterface {\n\treturn new Template(options)\n}\n\n/**\n * Creates a template registry.\n *\n * @param options - Optional initial `templates` seed collection and\n * manager-wide `missing` / `locale` fill defaults, emitter `on` hooks, and\n * an `error` handler\n * @returns A working {@link TemplateManagerInterface}\n * @throws {@link TemplateError} Thrown when a seeded `options.templates` bag declares a duplicate placeholder `name` or an empty `path` (coded `INVALID`)\n *\n * @example\n * ```ts\n * import { createTemplateManager } from '@src/core'\n *\n * const templates = createTemplateManager({\n * \ttemplates: [{ id: 'greeting', name: 'greeting', content: 'Hi {{name}}' }],\n * })\n * templates.fill('greeting', { name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport function createTemplateManager(options?: TemplateManagerOptions): TemplateManagerInterface {\n\treturn new TemplateManager(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,eAAe;;AAG5B,IAAa,yBAAwC;;AAGrD,IAAa,iBAAiB;;;;;;AAO9B,IAAa,wBAA2C,OAAO,OAAO;CACrE;CACA;CACA;AACD,CAAC;;;;;;;;;;;;;;AC1BD,IAAa,gBAAb,cAAmC,MAAM;CACxC;CACA;CAEA,YACC,MACA,SACA,SACC;EACD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,IAAI,YAAY,KAAA,GAAW,KAAK,UAAU;CAC3C;AACD;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,gBAAgB,OAAwC;CACvE,OAAO,iBAAiB;AACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACLA,SAAgB,YAAY,OAAgB,QAAwB;CACnE,KAAA,GAAI,oBAAA,eAAA,CAAe,KAAK,GAAG,OAAO,MAAM,eAAe,MAAM;CAC7D,OAAO,OAAO,KAAK;AACpB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,iBAAiB,QAA4B,MAA0B;CAEtF,KADiB,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI,EAAA,CACtC,MAAM,YAAY,sBAAsB,SAAS,OAAO,CAAC,GAAG,OAAO,KAAA;CAChF,QAAA,GAAO,oBAAA,aAAA,CAAa,QAAQ,IAAI;AACjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,aACf,QACA,cACA,OAC0B;CAC1B,MAAM,WAAW,aAAa,MAAM,gBAAgB,YAAY,SAAS,KAAK;CAE9E,OAAO;EACN,OAAO,iBAAiB,QAFZ,UAAU,QAAQ,MAAM,MAAM,GAAG,CAET;EACpC;EACA,UAAU,aAAa,KAAA,KAAa,SAAS,aAAa;CAC3D;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;CACvB;;;;;;;;;;;CAYA,KAAK,IAAY,QAA6B,SAAuC;EACpF,OAAO,KAAKI,SAAS,EAAE,CAAC,CAAC,KAAK,QAAQ,OAAO;CAC9C;;;;;;;;;CAUA,SAAS,IAAY,QAAuD;EAC3E,OAAO,KAAKA,SAAS,EAAE,CAAC,CAAC,SAAS,MAAM;CACzC;;;;;;;;CASA,WAAW,IAA2D;EACrE,OAAO,KAAKA,SAAS,EAAE,CAAC,CAAC,WAAW;CACrC;CAEA,aAAa,UAAkE;EAC9E,IAAI,KAAKC,YAAY,QAAQ,GAAG,OAAO;EACvC,OAAO,IAAI,SAAS;GACnB,GAAG;GACH,SAAS,SAAS,WAAW,KAAKJ;GAClC,QAAQ,SAAS,UAAU,KAAKC;EACjC,CAAC;CACF;CAIA,YAAY,UAA8E;EACzF,OACC,UAAU,YACV,OAAO,SAAS,SAAS,cACzB,cAAc,YACd,OAAO,SAAS,aAAa,cAC7B,gBAAgB,YAChB,OAAO,SAAS,eAAe;CAEjC;CAIA,SAAS,IAA+B;EACvC,MAAM,WAAW,KAAKH,WAAW,IAAI,EAAE;EACvC,IAAI,aAAa,KAAA,GAChB,MAAM,IAAI,cAAc,YAAY,wBAAwB,MAAM,EAAE,GAAG,CAAC;EAEzE,OAAO;CACR;AACD;;;;;;;;;;;;;;;;;;;;AC3QA,SAAgB,eAAe,SAA6C;CAC3E,OAAO,IAAI,SAAS,OAAO;AAC5B;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,sBAAsB,SAA4D;CACjG,OAAO,IAAI,gBAAgB,OAAO;AACnC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/helpers.ts","../../../src/core/shapers.ts","../../../src/core/templates/Template.ts","../../../src/core/templates/TemplateManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { MissingPolicy } from './types.js'\n\n// Frozen default data for the template module — constants are\n// UPPER_SNAKE_CASE data, the sole home for module-scope literal defaults.\n\n/**\n * Holds the single-pass `{{name}}` substitution pattern shared by\n * `Template#fill` and `Template#validate`.\n *\n * @remarks\n * Global-flagged, two-alternative pattern: a match of the first alternative\n * (`\\{{` — a literal backslash followed by `{{`) means \"emit a literal\n * `{{`\" — the escape hatch for content that must show `{{` without\n * triggering substitution. A match that instead populates capture group 1\n * (`\\{{([^{}]+?)\\}\\}`) means \"substitute the named token\" — group 1 is the\n * untrimmed token text between the braces; every call site trims it\n * (`token.trim()`) before using it as a lookup name, so `'{{ name }}'` still\n * resolves `'name'`. The pattern deliberately does not wrap the token in\n * `\\s*` — an unclosed `'{{' + ' '.repeat(n)` with no closing `}}` would\n * otherwise force the regex engine into catastrophic backtracking over the\n * whitespace run (O(n^2)); trimming after the match keeps the same\n * whitespace tolerance without the backtracking hazard. Every call site\n * builds a fresh `RegExp` from `.source` / `.flags` rather than sharing this\n * instance's mutable `lastIndex` across scans.\n */\nexport const FILL_PATTERN = /\\\\\\{\\{|\\{\\{([^{}]+?)\\}\\}/g\n\n/**\n * Holds `'error'`, the default `missing` policy for `Template#fill` /\n * `TemplateManager#fill` when unspecified.\n */\nexport const DEFAULT_MISSING_POLICY: MissingPolicy = 'error'\n\n/**\n * Holds `'en-US'`, the default `locale` for `Template#fill` /\n * `TemplateManager#fill` when unspecified.\n */\nexport const DEFAULT_LOCALE = 'en-US'\n\n/**\n * Lists the prototype-pollution-unsafe field-path segments `'__proto__'`,\n * `'constructor'`, and `'prototype'` — a fill lookup refuses to resolve a path\n * containing one of them, treating the placeholder as unresolved.\n */\nexport const UNSAFE_FIELD_SEGMENTS: readonly string[] = Object.freeze([\n\t'__proto__',\n\t'constructor',\n\t'prototype',\n])\n","import type { TemplateErrorCode } from './types.js'\n\n// Misuse of the template layer `throw`s a `TemplateError` carrying a\n// machine-readable `code`, so a `catch` branches on `error.code`.\n\n/**\n * Represents an error thrown by the template layer — a machine-readable\n * {@link TemplateErrorCode} and an optional `context` record naming the\n * offending id or placeholder name.\n *\n * @remarks\n * Thrown for: a required placeholder staying unresolved under the `error`\n * {@link MissingPolicy} (`MISSING`), an unknown template id\n * (`NOTFOUND`), `createTemplate` handed invalid data (`INVALID`), and\n * `TemplateManagerInterface#register` handed an id already present without\n * `options.replace` (`CONFLICT`).\n */\nexport class TemplateError extends Error {\n\treadonly code: TemplateErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: TemplateErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'TemplateError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrows an unknown caught value to a {@link TemplateError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns True if `value` is a {@link TemplateError}; false otherwise\n *\n * @example\n * ```ts\n * import { isTemplateError } from '@src/core'\n *\n * try {\n * \tmanager.fill('missing')\n * } catch (error) {\n * \tif (isTemplateError(error) && error.code === 'NOTFOUND') return\n * }\n * ```\n */\nexport function isTemplateError(value: unknown): value is TemplateError {\n\treturn value instanceof TemplateError\n}\n","import type { FieldPath } from '@orkestrel/contract'\nimport type {\n\tTemplateFillContext,\n\tTemplateFillValues,\n\tTemplatePlaceholder,\n\tTemplateTokenResolution,\n} from './types.js'\nimport { isFiniteNumber, resolveField } from '@orkestrel/contract'\nimport {\n\tDEFAULT_LOCALE,\n\tDEFAULT_MISSING_POLICY,\n\tFILL_PATTERN,\n\tUNSAFE_FIELD_SEGMENTS,\n} from './constants.js'\nimport { TemplateError } from './errors.js'\n\n// The templates pure-leaf inventory — every function here is a\n// referentially-transparent computation with no instance state, exported and\n// independently unit-testable. `Template#fill` / `#validate` route through\n// these leaves rather than duplicating the substitution logic.\n\n/**\n * Formats a resolved fill value for substitution into a template's `content`.\n *\n * @remarks\n * A finite number renders with the given locale's thousand grouping (through\n * `toLocaleString`); every other value — including `null` — String-coerces.\n * `null` therefore renders as the literal string `'null'`, matching\n * `String(value)` exactly, so a resolved `null` is visible in the output\n * rather than silently empty. An\n * invalid BCP-47 `locale` tag throws a `RangeError` from the underlying\n * `toLocaleString` call when `value` is a finite number — this is a caller\n * error (an invalid locale argument), by design, and is not caught here.\n *\n * @param value - The resolved value to format\n * @param locale - The locale used for finite-number formatting\n * @returns The formatted string\n *\n * @example\n * ```ts\n * import { formatValue } from '@src/core'\n *\n * formatValue(5010, 'en-US') // '5,010'\n * formatValue(null, 'en-US') // 'null'\n * ```\n */\nexport function formatValue(value: unknown, locale: string): string {\n\tif (isFiniteNumber(value)) return value.toLocaleString(locale)\n\treturn String(value)\n}\n\n/**\n * Resolves a field path against a fill-values record, refusing any path that\n * touches a prototype-pollution-unsafe segment.\n *\n * @remarks\n * A prototype-pollution guard shared by `fillTemplate` and `Template#validate`\n * so the two stay in lockstep: `path` normalizes to a segment array (a bare\n * string `path` becomes a single-segment array); if any segment appears in\n * `UNSAFE_FIELD_SEGMENTS` (`'__proto__'`, `'constructor'`, `'prototype'`), the\n * lookup is refused and `undefined` is returned without ever calling\n * `resolveField` — a path like `['__proto__', 'polluted']` can never reach\n * the record's actual prototype chain through this function. Every other\n * path resolves through `@orkestrel/contract`'s `resolveField`.\n *\n * @param record - The fill-values record to resolve against\n * @param path - The field path — a single segment or a segment array\n * @returns The resolved value, or `undefined` when unresolved or the path is unsafe\n *\n * @example\n * ```ts\n * import { resolveSafeField } from '@src/core'\n *\n * resolveSafeField({ a: { b: 1 } }, ['a', 'b']) // 1\n * resolveSafeField({}, ['__proto__', 'polluted']) // undefined\n * ```\n */\nexport function resolveSafeField(record: TemplateFillValues, path: FieldPath): unknown {\n\tconst segments = Array.isArray(path) ? path : [path]\n\tif (segments.some((segment) => UNSAFE_FIELD_SEGMENTS.includes(segment))) return undefined\n\treturn resolveField(record, path)\n}\n\n/**\n * Resolves one `{{name}}` token against the declared placeholders and the\n * fill-values record.\n *\n * @remarks\n * The single implementation of the token rule `fillTemplate` and\n * `Template#validate` both apply, so the two can never drift: the declared\n * {@link TemplatePlaceholder} sharing the token's `name` (exact match)\n * supplies its `path`, falling back to the token split on `.`; the value\n * resolves through `resolveSafeField`, so any segment in\n * `UNSAFE_FIELD_SEGMENTS` yields `undefined` without ever calling\n * `resolveField`; `required` is `true` for an undeclared token and for a\n * declared placeholder whose `required` is not `false`. The token is passed\n * already trimmed. `fallback` is not applied here — it is read from\n * `declared` by each caller, because `fill` substitutes it and `validate`\n * only counts it.\n *\n * @param record - The fill-values record the token resolves against\n * @param placeholders - The declared placeholders the token matches by name\n * @param token - The trimmed token text, without its `{{` / `}}` delimiters\n * @returns The {@link TemplateTokenResolution} for the token\n *\n * @example\n * ```ts\n * import { resolveToken } from '@src/core'\n *\n * resolveToken({ name: 'Ada' }, [], 'name').value // 'Ada'\n * resolveToken({}, [{ name: 'nickname', required: false }], 'nickname').required // false\n * ```\n */\nexport function resolveToken(\n\trecord: TemplateFillValues,\n\tplaceholders: readonly TemplatePlaceholder[],\n\ttoken: string,\n): TemplateTokenResolution {\n\tconst declared = placeholders.find((placeholder) => placeholder.name === token)\n\tconst path = declared?.path ?? token.split('.')\n\treturn {\n\t\tvalue: resolveSafeField(record, path),\n\t\tdeclared,\n\t\trequired: declared === undefined || declared.required !== false,\n\t}\n}\n\n/**\n * Substitutes every `{{name}}` token in `content` in a single pass.\n *\n * @remarks\n * Uses a fresh `RegExp` clone of `FILL_PATTERN` per call (never sharing its\n * `lastIndex`) and a single `String#replace` scan — substituted output is\n * never re-scanned. Each token resolves through `resolveToken`, the one rule\n * `Template#validate` also applies: the matching declared\n * {@link TemplatePlaceholder} (exact `name`) supplies its `path` (falling\n * back to the token split on `.`); any path segment in `UNSAFE_FIELD_SEGMENTS`\n * makes the token unresolved without ever calling `resolveField` (a\n * prototype-pollution guard). A resolved value formats through `formatValue`; an\n * unresolved value falls back to the placeholder's `fallback` when declared;\n * otherwise `options.missing` governs — `'literal'` re-emits the original\n * `{{name}}` text, `'empty'` emits `''`, and `'error'` emits `''` for every\n * token but collects every unresolved required token (an undeclared token, or\n * a declared token with `required !== false`) and throws one\n * {@link TemplateError} coded `MISSING` listing them all, in first-appearance\n * order, once the scan completes. An escaped `\\{{` emits a literal `{{`.\n *\n * Called with no declared `placeholders` and `{ missing: 'empty' }`, this is a\n * bare interpolation over `content` — every token resolves by dotted path\n * against the values record and every unresolved token emits `''`.\n * `FILL_PATTERN`'s token class (`[^{}]`) excludes `{`, so a token containing\n * `{` never matches and the surrounding `{{` stays literal.\n *\n * @param content - The template content carrying `{{name}}` tokens\n * @param values - The values tokens resolve against\n * @param options - `missing` (default `'error'`), `locale` (default `'en-US'`), and the declared `placeholders` (default none) tokens resolve against\n * @returns The substituted content\n *\n * @example\n * ```ts\n * import { fillTemplate } from '@src/core'\n *\n * fillTemplate('Hi {{name}}', { name: 'Ada' }) // 'Hi Ada'\n * fillTemplate('Limit {{limit}}', { limit: 5010 }, { missing: 'empty' }) // 'Limit 5,010'\n * ```\n */\nexport function fillTemplate(\n\tcontent: string,\n\tvalues?: TemplateFillValues,\n\toptions?: TemplateFillContext,\n): string {\n\tconst placeholders = options?.placeholders ?? []\n\tconst missing = options?.missing ?? DEFAULT_MISSING_POLICY\n\tconst locale = options?.locale ?? DEFAULT_LOCALE\n\tconst record = values ?? {}\n\n\tconst missingNames: string[] = []\n\tconst seen = new Set<string>()\n\n\tconst pattern = new RegExp(FILL_PATTERN.source, FILL_PATTERN.flags)\n\tconst result = content.replace(pattern, (matchText: string, rawToken: string | undefined) => {\n\t\tif (rawToken === undefined) return '{{'\n\t\tconst token = rawToken.trim()\n\n\t\tconst { value, declared, required } = resolveToken(record, placeholders, token)\n\n\t\tif (value !== undefined) return formatValue(value, locale)\n\t\tif (declared?.fallback !== undefined) return formatValue(declared.fallback, locale)\n\n\t\tif (missing === 'literal') return matchText\n\t\tif (missing === 'empty') return ''\n\n\t\tif (required && !seen.has(token)) {\n\t\t\tseen.add(token)\n\t\t\tmissingNames.push(token)\n\t\t}\n\t\treturn ''\n\t})\n\n\tif (missing === 'error' && missingNames.length > 0) {\n\t\tthrow new TemplateError(\n\t\t\t'MISSING',\n\t\t\t`Missing required placeholder(s): ${missingNames.join(', ')}`,\n\t\t\t{ missing: missingNames },\n\t\t)\n\t}\n\n\treturn result\n}\n","import type { ContractShape } from '@orkestrel/contract'\nimport type { TemplatePlaceholder } from './types.js'\nimport { objectShape, optionalShape, stringShape } from '@orkestrel/contract'\n\n// The templates shape-value inventory — every function here builds an\n// `@orkestrel/contract` shape from declared template data. Shapers sit above\n// the `helpers.ts` leaf pair: they consume it, and it never consumes them.\n\n/**\n * Builds the `@orkestrel/contract` object shape describing a template's\n * declared placeholders.\n *\n * @remarks\n * Each placeholder becomes a `stringShape` carrying its `description`;\n * `required === false` wraps it in `optionalShape`. Used by `Template` to\n * compile its `parameters()` contract once per instance.\n *\n * @param placeholders - The declared placeholders to shape\n * @returns The contract shape for `createContract`\n *\n * @example\n * ```ts\n * import { placeholderShape } from '@src/core'\n * import { createContract } from '@orkestrel/contract'\n *\n * const contract = createContract(placeholderShape([{ name: 'city' }]))\n * ```\n */\nexport function placeholderShape(placeholders: readonly TemplatePlaceholder[]): ContractShape {\n\tconst properties: Record<string, ContractShape> = {}\n\tfor (const placeholder of placeholders) {\n\t\tconst description = placeholder.description\n\t\tconst field = stringShape({\n\t\t\t...(description !== undefined ? { description } : {}),\n\t\t})\n\t\tproperties[placeholder.name] = placeholder.required === false ? optionalShape(field) : field\n\t}\n\treturn objectShape(properties)\n}\n","import type { ContractInterface } from '@orkestrel/contract'\nimport type {\n\tMissingPolicy,\n\tTemplateDefinition,\n\tTemplateFillOptions,\n\tTemplateFillValues,\n\tTemplateInterface,\n\tTemplateOptions,\n\tTemplatePlaceholder,\n\tTemplateValidationResult,\n} from '../types.js'\nimport { createContract, schemaToParameters } from '@orkestrel/contract'\nimport { DEFAULT_LOCALE, DEFAULT_MISSING_POLICY, FILL_PATTERN } from '../constants.js'\nimport { fillTemplate, resolveToken } from '../helpers.js'\nimport { placeholderShape } from '../shapers.js'\nimport { TemplateError } from '../errors.js'\n\n/**\n * Represents a named, versionable template — `{{name}}` tokens in `content`,\n * filled against a values record — implementing `TemplateInterface` exactly.\n *\n * @remarks\n * `missing` / `locale` seed this instance's default {@link TemplateFillOptions},\n * overridable per `fill` call. Its `parameters()` contract (built from\n * `placeholders` through `placeholderShape`) compiles once, in the constructor.\n *\n * @throws {@link TemplateError} Thrown when `options.placeholders` declares a duplicate `name` or an empty `path` (coded `INVALID`)\n *\n * @example\n * ```ts\n * const greeting = new Template({ name: 'greeting', content: 'Hi {{name}}' })\n * greeting.fill({ name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport class Template implements TemplateInterface {\n\treadonly #missing: MissingPolicy\n\treadonly #locale: string\n\treadonly #contract: ContractInterface<unknown>\n\treadonly id: string\n\treadonly name: string\n\treadonly content: string\n\treadonly placeholders: readonly TemplatePlaceholder[]\n\treadonly summary?: string\n\treadonly description?: string\n\treadonly category?: string\n\treadonly tags?: readonly string[]\n\n\tconstructor(options: TemplateOptions) {\n\t\tconst placeholders = options.placeholders ?? []\n\t\tconst seenNames = new Set<string>()\n\t\tfor (const placeholder of placeholders) {\n\t\t\tif (seenNames.has(placeholder.name)) {\n\t\t\t\tthrow new TemplateError('INVALID', `Duplicate placeholder name: ${placeholder.name}`, {\n\t\t\t\t\tname: placeholder.name,\n\t\t\t\t})\n\t\t\t}\n\t\t\tseenNames.add(placeholder.name)\n\t\t\tif (Array.isArray(placeholder.path) && placeholder.path.length === 0) {\n\t\t\t\tthrow new TemplateError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Placeholder path must not be empty: ${placeholder.name}`,\n\t\t\t\t\t{ name: placeholder.name },\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tthis.id = typeof options.id === 'string' ? options.id : crypto.randomUUID()\n\t\tthis.name = options.name\n\t\tthis.content = options.content\n\t\tthis.placeholders = placeholders\n\t\tif (options.summary !== undefined) this.summary = options.summary\n\t\tif (options.description !== undefined) this.description = options.description\n\t\tif (options.category !== undefined) this.category = options.category\n\t\tif (options.tags !== undefined) this.tags = options.tags\n\t\tthis.#missing = options.missing ?? DEFAULT_MISSING_POLICY\n\t\tthis.#locale = options.locale ?? DEFAULT_LOCALE\n\t\tthis.#contract = createContract(placeholderShape(this.placeholders))\n\t}\n\n\t/**\n\t * Returns the plain, JSON-serializable data this template carries.\n\t *\n\t * @returns The {@link TemplateDefinition} record\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({ name: 'greeting', content: 'Hi {{name}}' })\n\t * instance.definition().name // 'greeting'\n\t * ```\n\t */\n\tdefinition(): TemplateDefinition {\n\t\treturn {\n\t\t\tid: this.id,\n\t\t\tname: this.name,\n\t\t\tcontent: this.content,\n\t\t\tplaceholders: this.placeholders,\n\t\t\t...(this.summary !== undefined ? { summary: this.summary } : {}),\n\t\t\t...(this.description !== undefined ? { description: this.description } : {}),\n\t\t\t...(this.category !== undefined ? { category: this.category } : {}),\n\t\t\t...(this.tags !== undefined ? { tags: this.tags } : {}),\n\t\t}\n\t}\n\n\t/**\n\t * Substitutes every `{{name}}` token in `content` against `values`.\n\t *\n\t * @param values - The values tokens resolve against\n\t * @param options - Per-call overrides for this instance's `missing` / `locale` defaults\n\t * @returns The substituted content\n\t * @throws {@link TemplateError} Thrown when a required placeholder stays unresolved under the `'error'` policy (coded `MISSING`)\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({ name: 'greeting', content: 'Hi {{name}}' })\n\t * instance.fill({ name: 'Ada' }) // 'Hi Ada'\n\t * ```\n\t */\n\tfill(values?: TemplateFillValues, options?: TemplateFillOptions): string {\n\t\treturn fillTemplate(this.content, values, {\n\t\t\tmissing: options?.missing ?? this.#missing,\n\t\t\tlocale: options?.locale ?? this.#locale,\n\t\t\tplaceholders: this.placeholders,\n\t\t})\n\t}\n\n\t/**\n\t * Reports which required placeholders would stay unresolved, and which\n\t * `values` keys go unused, without producing output.\n\t *\n\t * @remarks\n\t * Content-token driven: scans `this.content` for every `{{name}}` token\n\t * (skipping escaped `\\{{` matches) the same way `fill` does, so `validate`\n\t * predicts `fill`'s `'error'`-{@link MissingPolicy} outcome exactly — a\n\t * token reported here as missing is precisely a token that would throw\n\t * under `fill(values, { missing: 'error' })`. For each distinct token\n\t * (first-appearance order, trimmed): `resolveToken` applies the one shared\n\t * token rule `fill` also applies — a declared {@link TemplatePlaceholder}\n\t * sharing its `name` supplies `path` (falling back to the token split on\n\t * `.`), and the value resolves through `resolveSafeField`. The token is `missing`\n\t * only when the value is unresolved, no `fallback` is declared, and the\n\t * placeholder is required (`required !== false`, including undeclared\n\t * tokens). `extra` lists every `values` key with no declared placeholder.\n\t *\n\t * @param values - The values to check\n\t * @returns The {@link TemplateValidationResult}\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({\n\t * \tname: 'greeting',\n\t * \tcontent: 'Hi {{name}}',\n\t * \tplaceholders: [{ name: 'name' }],\n\t * })\n\t * instance.validate({}).missing // ['name']\n\t * ```\n\t */\n\tvalidate(values?: TemplateFillValues): TemplateValidationResult {\n\t\tconst record = values ?? {}\n\t\tconst missing: string[] = []\n\t\tconst seen = new Set<string>()\n\n\t\tconst pattern = new RegExp(FILL_PATTERN.source, FILL_PATTERN.flags)\n\t\tfor (const match of this.content.matchAll(pattern)) {\n\t\t\tconst rawToken = match[1]\n\t\t\tif (rawToken === undefined) continue\n\t\t\tconst token = rawToken.trim()\n\t\t\tif (seen.has(token)) continue\n\t\t\tseen.add(token)\n\n\t\t\tconst { value, declared, required } = resolveToken(record, this.placeholders, token)\n\n\t\t\tif (value === undefined && declared?.fallback === undefined && required) {\n\t\t\t\tmissing.push(token)\n\t\t\t}\n\t\t}\n\n\t\tconst declaredNames = new Set(this.placeholders.map((placeholder) => placeholder.name))\n\t\tconst extra = Object.keys(record).filter((key) => !declaredNames.has(key))\n\n\t\treturn { valid: missing.length === 0, missing, extra }\n\t}\n\n\t/**\n\t * Projects this template's placeholders to the open tool-parameters record\n\t * shape.\n\t *\n\t * @returns The compiled parameters record, or `undefined` when `schemaToParameters` yields none\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = new Template({\n\t * \tname: 'greeting',\n\t * \tcontent: 'Hi {{name}}',\n\t * \tplaceholders: [{ name: 'name' }],\n\t * })\n\t * instance.parameters()\n\t * ```\n\t */\n\tparameters(): Readonly<Record<string, unknown>> | undefined {\n\t\treturn schemaToParameters(this.#contract.schema)\n\t}\n}\n","import type {\n\tMissingPolicy,\n\tTemplateFillValues,\n\tTemplateFillOptions,\n\tTemplateInterface,\n\tTemplateManagerEventMap,\n\tTemplateManagerInterface,\n\tTemplateManagerOptions,\n\tTemplateOptions,\n\tTemplateQuery,\n\tTemplateRegisterOptions,\n\tTemplateValidationResult,\n} from '../types.js'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport { Emitter } from '@orkestrel/emitter'\nimport { DEFAULT_LOCALE, DEFAULT_MISSING_POLICY } from '../constants.js'\nimport { TemplateError } from '../errors.js'\nimport { Template } from './Template.js'\n\n/**\n * Represents the template registry — a self-owning, id-keyed record-holder for\n * the {@link TemplateInterface} instances a consumer registers, looks up,\n * fills, and validates by id — implementing `TemplateManagerInterface`\n * exactly.\n *\n * @remarks\n * Singular and plural accessors, the batch `remove` overloads, and ownership\n * of the emitter all sit here. `register` accepts either a constructed {@link TemplateInterface} (kept\n * as-is, including its own `missing` / `locale` defaults) or a plain\n * {@link TemplateOptions} bag — constructed into a `Template` with this\n * manager's `missing` / `locale` defaults applied wherever the bag omits\n * them. A duplicate `id` throws a {@link TemplateError} coded `CONFLICT`\n * unless `options.replace` is `true`, in which case the existing entry is\n * overwritten. `options.templates` seeds the registry at construction without\n * emitting `register` — only calls to `register` after construction emit.\n * The batch `remove(ids)` form removes every present id and returns\n * `true` only when every listed id was present.\n *\n * @example\n * ```ts\n * import { TemplateManager } from '@src/core'\n *\n * const manager = new TemplateManager()\n * const instance = manager.register({ name: 'greeting', content: 'Hi {{name}}' })\n * manager.fill(instance.id, { name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport class TemplateManager implements TemplateManagerInterface {\n\treadonly #templates = new Map<string, TemplateInterface>()\n\treadonly #emitter: Emitter<TemplateManagerEventMap>\n\treadonly #missing: MissingPolicy\n\treadonly #locale: string\n\n\tconstructor(options?: TemplateManagerOptions) {\n\t\tconst on = options?.on\n\t\tconst error = options?.error\n\t\tthis.#emitter = new Emitter<TemplateManagerEventMap>({\n\t\t\t...(on !== undefined ? { on } : {}),\n\t\t\t...(error !== undefined ? { error } : {}),\n\t\t})\n\t\tthis.#missing = options?.missing ?? DEFAULT_MISSING_POLICY\n\t\tthis.#locale = options?.locale ?? DEFAULT_LOCALE\n\t\tfor (const template of options?.templates ?? []) {\n\t\t\tconst instance = this.#instantiate(template)\n\t\t\tthis.#templates.set(instance.id, instance)\n\t\t}\n\t}\n\n\tget emitter(): EmitterInterface<TemplateManagerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget count(): number {\n\t\treturn this.#templates.size\n\t}\n\n\t/**\n\t * Registers a template — a constructed {@link TemplateInterface} (kept\n\t * as-is) or a plain {@link TemplateOptions} bag (constructed into a\n\t * `Template` with this manager's `missing` / `locale` defaults applied\n\t * wherever the bag omits them).\n\t *\n\t * @param template - The template instance or options to register\n\t * @param options - `replace` — overwrite an existing entry sharing the same id instead of throwing\n\t * @returns The registered {@link TemplateInterface}\n\t * @throws {@link TemplateError} Thrown when the id is already registered and `options.replace` is not `true` (coded `CONFLICT`), or when an options bag declares a duplicate placeholder `name` or an empty `path` (coded `INVALID`)\n\t *\n\t * @example\n\t * ```ts\n\t * const instance = manager.register({ id: 'greeting', name: 'greeting', content: 'Hi {{name}}' })\n\t * ```\n\t */\n\tregister(\n\t\ttemplate: TemplateInterface | TemplateOptions,\n\t\toptions?: TemplateRegisterOptions,\n\t): TemplateInterface {\n\t\tconst instance = this.#instantiate(template)\n\t\tconst existing = this.#templates.get(instance.id)\n\t\tif (existing !== undefined && options?.replace !== true) {\n\t\t\tthrow new TemplateError('CONFLICT', `Template already registered: ${instance.id}`, {\n\t\t\t\tid: instance.id,\n\t\t\t})\n\t\t}\n\t\tthis.#templates.set(instance.id, instance)\n\t\tthis.#emitter.emit('register', instance)\n\t\treturn instance\n\t}\n\n\t/**\n\t * Returns one registered {@link TemplateInterface} by id.\n\t *\n\t * @param id - The template id\n\t * @returns The registered {@link TemplateInterface}, or `undefined` when `id` is unregistered\n\t */\n\ttemplate(id: string): TemplateInterface | undefined {\n\t\treturn this.#templates.get(id)\n\t}\n\n\t/**\n\t * Lists every registered template.\n\t *\n\t * @returns A snapshot array of every registered {@link TemplateInterface}\n\t */\n\ttemplates(): readonly TemplateInterface[] {\n\t\treturn [...this.#templates.values()]\n\t}\n\n\t/**\n\t * Filters registered templates by `name`, `category`, and `tag` — every\n\t * supplied field must match.\n\t *\n\t * @param query - The {@link TemplateQuery} to filter by; omit for every registered template\n\t * @returns The matching templates\n\t */\n\tfind(query?: TemplateQuery): readonly TemplateInterface[] {\n\t\tif (query === undefined) return this.templates()\n\t\treturn this.templates().filter((instance) => {\n\t\t\tif (query.name !== undefined && instance.name !== query.name) return false\n\t\t\tif (query.category !== undefined && instance.category !== query.category) return false\n\t\t\tif (query.tag !== undefined && !(instance.tags ?? []).includes(query.tag)) return false\n\t\t\treturn true\n\t\t})\n\t}\n\n\t/**\n\t * Tests whether a template id is registered.\n\t *\n\t * @param id - The template id\n\t * @returns True if `id` is registered; false otherwise\n\t */\n\thas(id: string): boolean {\n\t\treturn this.#templates.has(id)\n\t}\n\n\t/**\n\t * Removes one, several, or every registered template.\n\t *\n\t * @remarks\n\t * `remove()` removes every registered template, emitting `remove` once per\n\t * instance. `remove(id)` removes one template by id, emitting `remove` and\n\t * returning `true` when it existed, `false` otherwise. `remove(ids)`\n\t * removes every listed id that is present, emitting `remove` once per\n\t * removed instance, and returns `true` only when every listed id was\n\t * present.\n\t *\n\t * @param target - Omit to remove all, a single id, or a list of ids\n\t * @returns `boolean` for the single-id / list-of-ids forms; `void` for the remove-all form\n\t */\n\t// `readonly string[]` is not assignable to `id: string`, so a list resolves to the\n\t// batch signature whatever order the signatures are declared in.\n\tremove(ids: readonly string[]): boolean\n\tremove(id: string): boolean\n\tremove(): void\n\tremove(target?: string | readonly string[]): boolean | void {\n\t\tif (target === undefined) {\n\t\t\tfor (const instance of this.#templates.values()) this.#emitter.emit('remove', instance)\n\t\t\tthis.#templates.clear()\n\t\t\treturn\n\t\t}\n\t\tif (typeof target === 'string') {\n\t\t\tconst instance = this.#templates.get(target)\n\t\t\tif (instance === undefined) return false\n\t\t\tthis.#templates.delete(target)\n\t\t\tthis.#emitter.emit('remove', instance)\n\t\t\treturn true\n\t\t}\n\t\tlet all = true\n\t\tfor (const id of target) {\n\t\t\tconst instance = this.#templates.get(id)\n\t\t\tif (instance === undefined) {\n\t\t\t\tall = false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tthis.#templates.delete(id)\n\t\t\tthis.#emitter.emit('remove', instance)\n\t\t}\n\t\treturn all\n\t}\n\n\t/** Removes every registered template, emitting `clear`. */\n\tclear(): void {\n\t\tthis.#templates.clear()\n\t\tthis.#emitter.emit('clear')\n\t}\n\n\t/**\n\t * Tears down the registry: drops every registered template and destroys the\n\t * owned emitter. Idempotent.\n\t *\n\t * @remarks\n\t * Teardown is not an observable registry operation and the emitter is being\n\t * released, so this emits neither `clear` nor `remove`. The emitter is torn\n\t * down last, after the registry is dropped.\n\t *\n\t * @example\n\t * ```ts\n\t * const manager = new TemplateManager()\n\t * manager.destroy()\n\t * manager.emitter.destroyed // true\n\t * ```\n\t */\n\tdestroy(): void {\n\t\tthis.#templates.clear()\n\t\tthis.#emitter.destroy()\n\t}\n\n\t/**\n\t * Fills a registered template by id.\n\t *\n\t * @param id - The template id\n\t * @param values - The values tokens resolve against\n\t * @param options - Per-call overrides for the template's `missing` / `locale` defaults\n\t * @returns The substituted content\n\t * @throws {@link TemplateError} coded `NOTFOUND` when `id` is unknown\n\t * @throws {@link TemplateError} Thrown when a required placeholder stays unresolved under the `'error'` policy (coded `MISSING`)\n\t */\n\tfill(id: string, values?: TemplateFillValues, options?: TemplateFillOptions): string {\n\t\treturn this.#require(id).fill(values, options)\n\t}\n\n\t/**\n\t * Validates values against a registered template by id.\n\t *\n\t * @param id - The template id\n\t * @param values - The values to check\n\t * @returns The {@link TemplateValidationResult}\n\t * @throws {@link TemplateError} coded `NOTFOUND` when `id` is unknown\n\t */\n\tvalidate(id: string, values?: TemplateFillValues): TemplateValidationResult {\n\t\treturn this.#require(id).validate(values)\n\t}\n\n\t/**\n\t * Projects a registered template's parameters by id.\n\t *\n\t * @param id - The template id\n\t * @returns The compiled parameters record, or `undefined` when the template has none\n\t * @throws {@link TemplateError} coded `NOTFOUND` when `id` is unknown\n\t */\n\tparameters(id: string): Readonly<Record<string, unknown>> | undefined {\n\t\treturn this.#require(id).parameters()\n\t}\n\n\t#instantiate(template: TemplateInterface | TemplateOptions): TemplateInterface {\n\t\tif (this.#isInstance(template)) return template\n\t\treturn new Template({\n\t\t\t...template,\n\t\t\tmissing: template.missing ?? this.#missing,\n\t\t\tlocale: template.locale ?? this.#locale,\n\t\t})\n\t}\n\n\t// A TemplateOptions bag is plain data with no `fill` / `validate` /\n\t// `parameters` methods; a TemplateInterface instance always exposes all three.\n\t#isInstance(template: TemplateInterface | TemplateOptions): template is TemplateInterface {\n\t\treturn (\n\t\t\t'fill' in template &&\n\t\t\ttypeof template.fill === 'function' &&\n\t\t\t'validate' in template &&\n\t\t\ttypeof template.validate === 'function' &&\n\t\t\t'parameters' in template &&\n\t\t\ttypeof template.parameters === 'function'\n\t\t)\n\t}\n\n\t// Every by-id operation that needs a template to proceed shares this lookup.\n\t// The `template` accessor deliberately does not, and returns `undefined`.\n\t#require(id: string): TemplateInterface {\n\t\tconst instance = this.#templates.get(id)\n\t\tif (instance === undefined) {\n\t\t\tthrow new TemplateError('NOTFOUND', `Unknown template id: ${id}`, { id })\n\t\t}\n\t\treturn instance\n\t}\n}\n","import type {\n\tTemplateInterface,\n\tTemplateManagerInterface,\n\tTemplateManagerOptions,\n\tTemplateOptions,\n} from './types.js'\nimport { Template } from './templates/Template.js'\nimport { TemplateManager } from './templates/TemplateManager.js'\n\n/**\n * Creates a working {@link TemplateInterface} from a {@link TemplateOptions}\n * bag, backed by the `Template` class.\n *\n * @param options - The template's `name` / `content`, an optional `id`\n * (defaults to a generated UUID), `placeholders`, catalog metadata, and\n * `missing` / `locale` fill defaults\n * @returns A working {@link TemplateInterface}\n * @throws {@link TemplateError} Thrown when `options.placeholders` declares a duplicate `name` or an empty `path` (coded `INVALID`)\n *\n * @example Create a template and a registry\n * ```ts\n * import { createTemplate, createTemplateManager } from '@orkestrel/template'\n *\n * const greeting = createTemplate({ name: 'greeting', content: 'Hi {{name}}' })\n * greeting.fill({ name: 'Ada' }) // 'Hi Ada'\n *\n * const templates = createTemplateManager({\n * \ttemplates: [\n * \t\t{ id: 'greeting', name: 'greeting', content: 'Hi {{name}}', category: 'mail' },\n * \t\t{ id: 'farewell', name: 'farewell', content: 'Bye {{name}}', category: 'mail' },\n * \t\t{ id: 'alert', name: 'alert', content: 'Alert: {{reason}}', category: 'ops' },\n * \t],\n * })\n * templates.fill('greeting', { name: 'Ada' }) // 'Hi Ada'\n * templates.find({ category: 'mail' }).map((one) => one.id) // ['greeting', 'farewell']\n * templates.has('alert') // true\n * templates.has('missing') // false\n * ```\n */\nexport function createTemplate(options: TemplateOptions): TemplateInterface {\n\treturn new Template(options)\n}\n\n/**\n * Creates a working {@link TemplateManagerInterface}, optionally seeded with\n * the templates the options carry, backed by the `TemplateManager` class.\n *\n * @param options - Optional initial `templates` seed collection and\n * manager-wide `missing` / `locale` fill defaults, emitter `on` hooks, and\n * an `error` handler\n * @returns A working {@link TemplateManagerInterface}\n * @throws {@link TemplateError} Thrown when a seeded `options.templates` bag declares a duplicate placeholder `name` or an empty `path` (coded `INVALID`)\n *\n * @example\n * ```ts\n * import { createTemplateManager } from '@src/core'\n *\n * const templates = createTemplateManager({\n * \ttemplates: [{ id: 'greeting', name: 'greeting', content: 'Hi {{name}}' }],\n * })\n * templates.fill('greeting', { name: 'Ada' }) // 'Hi Ada'\n * ```\n */\nexport function createTemplateManager(options?: TemplateManagerOptions): TemplateManagerInterface {\n\treturn new TemplateManager(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,eAAe;;;;;AAM5B,IAAa,yBAAwC;;;;;AAMrD,IAAa,iBAAiB;;;;;;AAO9B,IAAa,wBAA2C,OAAO,OAAO;CACrE;CACA;CACA;AACD,CAAC;;;;;;;;;;;;;;;AC/BD,IAAa,gBAAb,cAAmC,MAAM;CACxC;CACA;CAEA,YACC,MACA,SACA,SACC;EACD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,IAAI,YAAY,KAAA,GAAW,KAAK,UAAU;CAC3C;AACD;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,gBAAgB,OAAwC;CACvE,OAAO,iBAAiB;AACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACNA,SAAgB,YAAY,OAAgB,QAAwB;CACnE,KAAA,GAAI,oBAAA,eAAA,CAAe,KAAK,GAAG,OAAO,MAAM,eAAe,MAAM;CAC7D,OAAO,OAAO,KAAK;AACpB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,iBAAiB,QAA4B,MAA0B;CAEtF,KADiB,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI,EAAA,CACtC,MAAM,YAAY,sBAAsB,SAAS,OAAO,CAAC,GAAG,OAAO,KAAA;CAChF,QAAA,GAAO,oBAAA,aAAA,CAAa,QAAQ,IAAI;AACjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,aACf,QACA,cACA,OAC0B;CAC1B,MAAM,WAAW,aAAa,MAAM,gBAAgB,YAAY,SAAS,KAAK;CAE9E,OAAO;EACN,OAAO,iBAAiB,QAFZ,UAAU,QAAQ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