@spintax/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,35 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@spintax/core` are documented here. This project adheres to
4
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
+
6
+ ## 0.1.0 — 2026-07-07
7
+
8
+ First public release. Feature-complete engine; the TS suite passes the full **deterministic**
9
+ golden corpus that encodes the Spintax WordPress plugin's behavior contract (validation verdicts,
10
+ plural buckets, conditional truthiness, `#set` collapse, post-process output, enum/perm selection).
11
+ Cross-engine execution of that corpus by the PHP plugin is the remaining verification gate (see Notes).
12
+
13
+ ### Added
14
+
15
+ - `parse(input)` — opaque, versioned AST for reuse.
16
+ - `render(input, opts)` — seeded, lenient rendering: enumerations, permutations (config +
17
+ per-element separators), variables (recursive), `#set` (collapse-once), conditionals, plurals
18
+ (locale buckets), `#include` (host-injected resolver, scope isolation, circular guard), and the
19
+ 12-step cosmetic post-process (URL/email/domain/abbreviation shielding, spacing, capitalization).
20
+ Post-process defaults on; `postProcess: false` yields the raw pick.
21
+ - `validate(input, opts)` — diagnostics with a parity-gated verdict (valid ⇔ no `error`);
22
+ `knownIncludes` / `knownVariables` options.
23
+ - `extract(input)` — `{ refs, sets, includes }`.
24
+ - `analyze(input, opts)` — extract + validate + a best-effort construct census.
25
+ - `neutralize(value)` — text-safe shielding of data-derived input, with a mandatory safety-restore.
26
+
27
+ ### Notes
28
+
29
+ - `render()` is lenient on depth: a circular / too-deep `#include` resolves to `''` (there is
30
+ **no** `MaxDepthExceededError`), matching the plugin. It throws only on a resolver that itself
31
+ throws (`IncludeResolverError`) or a foreign `Ast` (`AstVersionError`) — revised after the
32
+ reference-Worker dogfood surfaced the phantom error export.
33
+ - Zero runtime dependencies; ESM-first with dual CJS. Node 18+, Cloudflare Workers, browser.
34
+ - Cross-engine RNG-sequence parity with the PHP plugin is a non-goal; only deterministic behavior
35
+ is parity-gated. The PHP-side corpus runner is the remaining cross-engine verification gate.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 301st (https://301.st)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,122 @@
1
+ # @spintax/core
2
+
3
+ Framework-agnostic **[spintax](https://spintax.net) engine** for JavaScript / TypeScript —
4
+ parse, render, validate, extract, analyze, and neutralize GTW-compatible spintax templates.
5
+
6
+ - **Zero runtime dependencies.** Runs unchanged on Cloudflare Workers, Node 18+, and in the browser.
7
+ - **ESM-first, dual CJS.** Ships `.d.ts` types for both.
8
+ - **Built to the [Spintax WordPress plugin](https://wordpress.org/plugins/spintax/)'s behavior
9
+ contract** via a shared golden corpus — an *independent* TypeScript implementation, not a
10
+ line-by-line port. The TS suite passes the full deterministic corpus; cross-engine execution
11
+ of that corpus by the PHP plugin is pending.
12
+ - **MIT** licensed.
13
+
14
+ > **Status: `0.1.0`** — first public release. Feature-complete; passes the full deterministic
15
+ > golden corpus (encoding the plugin's contract, TS side); the §9.2 API is proven by a reference
16
+ > Cloudflare Worker (`examples/worker`).
17
+
18
+ ## Install
19
+
20
+ ```sh
21
+ npm install @spintax/core
22
+ ```
23
+
24
+ ## Quick start
25
+
26
+ ```ts
27
+ import { render, validate, extract } from '@spintax/core';
28
+
29
+ render('{Hello|Hi|Hey} %name%!', { context: { name: 'Ada' }, seed: 42 });
30
+ // → "Hi Ada!" (deterministic for a given seed; post-processed by default)
31
+
32
+ validate('{a|b'); // → [{ severity: 'error', code: 'bracket.unclosed', … }]
33
+ extract('%title% {?promo?Sale}'); // → { refs: ['title', 'promo'], sets: [], includes: [] }
34
+ ```
35
+
36
+ ## Spintax syntax
37
+
38
+ | Construct | Example | Meaning |
39
+ | --- | --- | --- |
40
+ | Enumeration | `{a\|b\|c}` | pick one (nestable: `{a\|{b\|c}}`) |
41
+ | Permutation | `[a\|b\|c]` | pick N, shuffle, join — `[<minsize=1;maxsize=2;sep=", ">a\|b\|c]` |
42
+ | Variable | `%var%` | substitute a context value |
43
+ | Local set | `#set %v% = value` | define a variable (one line) |
44
+ | Conditional | `{?VAR?then\|else}` | `then` if `VAR` is truthy, else `else` |
45
+ | Plural | `{plural %n%: one\|few\|many}` | grammatical agreement by locale |
46
+ | Include | `#include "slug-or-id"` | embed another template (host-resolved) |
47
+ | Comment | `/# … #/` | stripped before rendering |
48
+
49
+ ## API
50
+
51
+ All functions accept a `string` **or** a parsed `Ast` (from `parse`) as their first argument.
52
+
53
+ ### `render(input, options?): string`
54
+
55
+ Renders a template to a single string. **Lenient** — never throws on malformed markup (a bad
56
+ block is emitted verbatim with fullwidth braces `{…}`). Cosmetic post-processing (spacing,
57
+ capitalization, URL/email shielding) is **on by default**.
58
+
59
+ ```ts
60
+ render(input, {
61
+ context?: Record<string, string>, // variable map
62
+ seed?: number | string, // deterministic RNG; omit ⇒ random
63
+ locale?: string, // plural buckets, e.g. 'ru' (3-form)
64
+ includeResolver?: (ref: string) => string | null, // host-injected, synchronous
65
+ postProcess?: boolean, // default true; false ⇒ raw pick
66
+ maxDepth?: number, // #include / nesting guard (default 20)
67
+ });
68
+ ```
69
+
70
+ `#include` is resolved only when you pass an `includeResolver`; child templates inherit the
71
+ runtime context but **not** the parent's `#set` locals. Circular / too-deep includes resolve to
72
+ `''` (lenient).
73
+
74
+ ### `validate(input, options?): Diagnostic[]`
75
+
76
+ Returns diagnostics. A template is **valid** ⇔ no diagnostic has `severity: 'error'`. An
77
+ unresolved `%var%` is a `warning`, not an error.
78
+
79
+ ```ts
80
+ validate(input, {
81
+ locale?: string, // locale-aware plural-arity verdicts
82
+ knownIncludes?: readonly string[], // enables "unknown #include target" errors
83
+ knownVariables?: readonly string[], // suppresses undefined-variable warnings
84
+ });
85
+ // Diagnostic: { severity, code, message, line, column, endLine?, endColumn?, data? }
86
+ ```
87
+
88
+ ### `extract(input): { refs, sets, includes }`
89
+
90
+ Variable references (`%var%`, `{?…}`, plural counts), `#set` names, and `#include` targets.
91
+
92
+ ### `analyze(input, options?): Analysis`
93
+
94
+ `extract` + `validate` + a best-effort `constructs` census (`{ enumeration, permutation,
95
+ variable, conditional, plural, set, include }`). The census counts author-visible constructs;
96
+ it is **not** a variant-cardinality promise.
97
+
98
+ ### `parse(input): Ast`
99
+
100
+ Parses once for reuse. `Ast` is **opaque and versioned** — pass it back to the other functions,
101
+ do not introspect or persist it across engine versions.
102
+
103
+ ### `neutralize(value): string`
104
+
105
+ Shields data-derived (untrusted) text so it can't be re-interpreted as spintax markup — use it
106
+ on any value you inject via `context` that isn't author-controlled. It is **text-safe**
107
+ (round-trips to literal glyphs in any sink), not HTML/XSS escaping.
108
+
109
+ ```ts
110
+ render('%bio%', { context: { bio: neutralize('Save {50|60}% today') }, postProcess: false });
111
+ // → "Save {50|60}% today" (the braces stay literal, not a random pick)
112
+ ```
113
+
114
+ ## Determinism & RNG
115
+
116
+ With a `seed`, `render` is reproducible within this engine. Cross-engine RNG-sequence parity
117
+ with the PHP plugin is a **non-goal** — only the *deterministic* behavior (validation verdicts,
118
+ plural buckets, conditional truthiness, `#set` collapse, post-process output) is parity-gated.
119
+
120
+ ## License
121
+
122
+ [MIT](../../LICENSE). The Spintax WordPress plugin remains GPL; MIT/Expat is GPL-compatible.