sjabloon 0.5.0 → 0.6.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/LICENSE CHANGED
@@ -1,21 +1,201 @@
1
- MIT License
2
-
3
- Copyright (c) Robin van der Vleuten <robin@webstronauts.com>
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.
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -3,9 +3,9 @@
3
3
  A tiny, CSP-safe template engine for JavaScript. **~1.8KB min+gzip (~3.6KB with [xprsn](https://www.npmjs.com/package/xprsn)), one dependency.**
4
4
 
5
5
  [![NPM version](https://img.shields.io/npm/v/sjabloon.svg)](https://www.npmjs.com/package/sjabloon)
6
- [![Build Status](https://github.com/robinvdvleuten/sjabloon/actions/workflows/test.yml/badge.svg)](https://github.com/robinvdvleuten/sjabloon/actions/workflows/test.yml)
6
+ [![Build Status](https://github.com/getquario/sjabloon/actions/workflows/test.yml/badge.svg)](https://github.com/getquario/sjabloon/actions/workflows/test.yml)
7
7
  [![NPM downloads](https://img.shields.io/npm/dm/sjabloon.svg)](https://www.npmjs.com/package/sjabloon)
8
- [![MIT license](https://img.shields.io/github/license/robinvdvleuten/sjabloon.svg)](https://github.com/robinvdvleuten/sjabloon/blob/main/LICENSE)
8
+ [![Apache-2.0 license](https://img.shields.io/github/license/getquario/sjabloon.svg)](https://github.com/getquario/sjabloon/blob/main/LICENSE)
9
9
 
10
10
  <a href="https://webstronauts.com?utm_source=github&utm_medium=readme&utm_campaign=sjabloon">
11
11
  <picture>
@@ -13,7 +13,7 @@ A tiny, CSP-safe template engine for JavaScript. **~1.8KB min+gzip (~3.6KB with
13
13
  </picture>
14
14
  </a>
15
15
 
16
- *Sjabloon* is Dutch for "template". It renders text templates with full [xprsn](https://github.com/robinvdvleuten/xprsn) expressions inside every tag, without turning template text into JavaScript. There is no `eval` and no `new Function`, so it runs under a strict Content Security Policy where engines that compile templates to code cannot.
16
+ *Sjabloon* is Dutch for "template". It renders text templates with full [xprsn](https://github.com/getquario/xprsn) expressions inside every tag, without turning template text into JavaScript. There is no `eval` and no `new Function`, so it runs under a strict Content Security Policy where engines that compile templates to code cannot.
17
17
 
18
18
  ```js
19
19
  import { template, render } from 'sjabloon';
@@ -47,6 +47,13 @@ tpl(base, { root: reportRoot, item: currentRow }); // $ = reportRoot, @ = curren
47
47
  tpl(base, { root: reportRoot }); // no item → @.x throws
48
48
  ```
49
49
 
50
+ The renderer's `withRaw(values?, scope?)` method renders once and returns both channels: `{ text, raws }` — the rendered string plus each interpolation's pre-escape, pre-stringify value, whatever the expression evaluated to before it became output text. A `{{ total }}` holding `1000` yields the number `1000`, not the string `"1000"` — the whole point for typed consumers like spreadsheet cells. Both `{{ }}` and `{{{ }}}` are captured, nullish included, in render order (loop bodies once per iteration, untaken branches never). Block expressions — `#if` conditions, `#each` collections — are not interpolations and are never captured.
51
+
52
+ ```js
53
+ const cell = template('{{ total * 1.21 }}');
54
+ cell.withRaw({ total: 1000 }); // => { text: '1210', raws: [1210] } — still a number
55
+ ```
56
+
50
57
  The renderer also carries `names` (every variable the template reads from your values, loop variables excluded) and `functions` (the registry functions it calls, methods excluded), both deduplicated. Check a stored template against your data model and its allowed functions before you render it, or fetch only the fields it needs.
51
58
 
52
59
  ```js
@@ -68,7 +75,7 @@ Sjabloon errors keep their native `SyntaxError` or `TypeError` class and expose:
68
75
  - `end`: the exclusive template offset;
69
76
  - `blocks`: a frozen, outermost-first array of `{ type, start, end }` opener spans.
70
77
 
71
- Parser codes are `SJABLOON_EACH_SYNTAX`, `SJABLOON_BLOCKED_BINDING`, `SJABLOON_UNEXPECTED_TAG`, `SJABLOON_UNKNOWN_BLOCK`, and `SJABLOON_UNCLOSED_BLOCK`. A missing closer uses an empty span at the end of the template. Expression offsets refer to the original template, so surrounding braces, whitespace, and trim markers contribute to their absolute position.
78
+ Parser codes are `SJABLOON_EACH_SYNTAX`, `SJABLOON_BLOCKED_BINDING`, `SJABLOON_UNEXPECTED_TAG`, `SJABLOON_UNKNOWN_BLOCK`, `SJABLOON_UNCLOSED_BLOCK`, and `SJABLOON_TOO_DEEP` (block nesting past 256 levels, located at the opener that crossed the cap). A missing closer uses an empty span at the end of the template. Expression offsets refer to the original template, so surrounding braces, whitespace, and trim markers contribute to their absolute position.
72
79
 
73
80
  Unauthenticated errors thrown by registered functions, getters, methods, or value coercion hooks are host errors. Sjabloon passes them through unchanged and does not attach template diagnostic fields.
74
81
 
@@ -88,7 +95,7 @@ Use `isDiagnostic(error)` when a host needs to distinguish those errors. It retu
88
95
  | `{{! anything }}` | Comment, removed from output |
89
96
  | `{{- expr -}}` | A dash hugging either brace trims the whitespace on that side, newlines included; works on every tag form |
90
97
 
91
- Every `expr` is an [xprsn expression](https://github.com/robinvdvleuten/xprsn#syntax): literals, arithmetic, string concatenation with `~` (`{{ first ~ " " ~ last }}`), comparisons, `and`/`or`/`not`/`in`, ternaries, property and method access, and functions from the registry you pass in. `null` and `undefined` render as empty strings.
98
+ Every `expr` is an [xprsn expression](https://github.com/getquario/xprsn#syntax): literals, arithmetic, string concatenation with `~` (`{{ first ~ " " ~ last }}`), comparisons, `and`/`or`/`not`/`in`, ternaries, property and method access, and functions from the registry you pass in. `null` and `undefined` render as empty strings.
92
99
 
93
100
  A loop body sees its loop variable plus the outer scope; reusing an outer name shadows it only inside that body. The engine keeps loop variables on a child scope, so the values you pass are never mutated.
94
101
 
@@ -115,14 +122,31 @@ Here the loop variable `company` shadows the root's for a bare name, but `$.comp
115
122
 
116
123
  sjabloon works under `script-src 'self'` with no `unsafe-eval`. Templates parse into a tree of closures that call other closures; xprsn compiles the expressions the same way. The test suite runs under `node --disallow-code-generation-from-strings`, which throws on any string-to-code construct exactly like a strict CSP does.
117
124
 
118
- This is the practical difference from engines like Handlebars (without precompilation) or tempura, which generate a JavaScript function per template and therefore need `unsafe-eval` at runtime. If you can precompile templates at build time, those engines are great and fast. If templates arrive at runtime (user-edited templates, CMS content, email templates) and your CSP is strict, sjabloon fits.
125
+ That runtime CSP support costs some render speed. Handlebars and tempura generate specialized JavaScript, so their compiled renderers are faster but runtime compilation requires `unsafe-eval`. Build-time precompilation avoids that restriction when templates are known in advance. If templates arrive at runtime (user-edited templates, CMS content, email templates) and your CSP is strict, sjabloon fits. See the [comparison benchmarks](bench/comparison/) for cold-compile and hot-render comparisons.
119
126
 
120
127
  ## Safety
121
128
 
122
129
  - `{{ expr }}` escapes `& < > " '` by default; unescaped output requires the explicit `{{{ }}}` form.
123
130
  - Expressions inherit all of xprsn's guards: no `__proto__`/`constructor`/`prototype` access, null-prototype hash literals, and functions resolved only from your registry.
124
131
  - Templates read your values; they cannot assign to them.
132
+ - Registered functions are host-provided capabilities, not a sandbox boundary. Only register helpers that template authors are allowed to invoke; likewise, treat explicit raw output as trusted HTML.
133
+
134
+ ## Environments
135
+
136
+ Node.js 22 and newer are supported through the ESM and CommonJS builds. Browser use is supported through a standards-based ESM bundler in environments supporting ES2024. Direct `<script>` globals and UMD builds are not provided.
125
137
 
126
138
  ## License
127
139
 
128
- MIT © [Robin van der Vleuten](https://robinvdvleuten.nl)
140
+ Copyright 2026 Robin van der Vleuten
141
+
142
+ Licensed under the Apache License, Version 2.0 (the "License");
143
+ you may not use this file except in compliance with the License.
144
+ You may obtain a copy of the License at
145
+
146
+ http://www.apache.org/licenses/LICENSE-2.0
147
+
148
+ Unless required by applicable law or agreed to in writing, software
149
+ distributed under the License is distributed on an "AS IS" BASIS,
150
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
151
+ See the License for the specific language governing permissions and
152
+ limitations under the License.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("xprsn");const t={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},n=e=>String(e).replace(/[&<>"']/g,e=>t[e]),r=/^(?:__proto__|constructor|prototype)$/,i=new WeakSet,a=i.add.bind(i),o=i.has.bind(i),s=e=>o(e);let c=e=>{let t=[];for(let n=0,r=1;n<e.length;){let i=e.indexOf(`{{`,n);if(i<0){t.push([0,e.slice(n)]);break}i>n&&t.push([0,e.slice(n,i)]);let a=e[i+2]===`{`,o=i+2+a,s=e[o]===`-`,c=-1;if(s&&o++,a&&r&&(c=e.indexOf(`}}}`,o),c<0&&(r=0)),c<0&&(a&&(a=!1,o=i+2,s=e[o]===`-`,s&&o++),c=e.indexOf(`}}`,o)),c<0){t.push([0,e.slice(i)]);break}let l=c>o&&e[c-1]===`-`,u=l?c-1:c,d=e.slice(o,u),f=d.trim(),p=o+d.length-d.trimStart().length,m=c+2+a,h=[a?1:2,f,i,m,o,u,p,p+f.length,s,l],g=t.at(-1);if(s&&g?.[0]===0&&g[1]&&(g[1]=g[1].trimEnd()),t.push(h),n=m,l)for(;/\s/.test(e[n]);)n++}return t},l,u,d,f,p,m,h,g,_,v=()=>Object.freeze(_.slice()),y=(e,t)=>Object.freeze({type:e,start:t[2],end:t[3]}),b=(e,t)=>(Object.defineProperty(e,"blocks",{value:t,enumerable:!0}),a(e),e),x=(e,t,n,r=n?.[2]??g.length,i=n?.[3]??g.length)=>{let a=SyntaxError(e);throw a.code=t,a.start=r,a.end=i,b(a,v())},S=(t,n,r,i=e.isDiagnostic)=>{throw i(t)?(t.start+=n,t.end+=n,b(t,r)):t},C=e=>x(`Unexpected {{`+e[1]+`}}`,`SJABLOON_UNEXPECTED_TAG`,e),w=(e,t)=>e.map(e=>e(t)).join(``),T=(e,t)=>(e=>n=>t(e(n)??``))(E(e[1],e[6],v())),E=(t,n,r)=>{let i;try{i=(0,e.compile)(t,d)}catch(e){S(e,n,r)}for(let e of i.names)p.includes(e)||m.add(e);for(let e of i.functions)h.add(e);return e=>{try{return i(e)}catch(e){S(e,n,r,i.isDiagnostic)}}},D=e=>{let t=O([`#elif`,`#else`,`/if`]),n=f[1],r=[];return n.startsWith(`#elif `)?r=[D(E(n.slice(6),f[6]+6,v()))]:n===`#else`?(r=O([`/if`]),f[1]===`/if`||C(f)):n!==`/if`&&C(f),n=>w(e(n)?t:r,n)},O=e=>{let t=[];for(let i;i=l[u++];){let a=i[1];if(!i[0])t.push((e=>()=>e)(a));else if(i[0]===1)t.push(T(i,String));else if(e.includes(a.split(` `)[0]))return f=i,t;else if(a[0]!==`!`)if(a.startsWith(`#if `))_.push(y(`if`,i)),t.push(D(E(a.slice(4),i[6]+4,v()))),_.pop();else if(/^#each(?:\s|$)/.test(a)){_.push(y(`each`,i));let e=/^#each ([\s\S]+) as ((\w+)(?:\s*,\s*(\w+))?)$/.exec(a);e||x(`Bad {{`+a+`}}`,`SJABLOON_EACH_SYNTAX`,i);let n=e[3],o=e[4],s=i[6]+a.length-e[2].length;if(r.test(n)&&x(`Bad {{`+a+`}}`,`SJABLOON_BLOCKED_BINDING`,i,s,s+n.length),o&&r.test(o)){let e=i[6]+a.length-o.length;x(`Bad {{`+a+`}}`,`SJABLOON_BLOCKED_BINDING`,i,e,e+o.length)}let c=E(e[1],i[6]+6,v()),l=p.length;p.push(n),o&&p.push(o),p.push(`loop`);let u=O([`#else`,`/each`]);p.length=l;let d=[];f[1]===`#else`?(d=O([`/each`]),f[1]===`/each`||C(f)):f[1]!==`/each`&&C(f),_.pop(),t.push(e=>{let t=c(e),r=Array.isArray(t),i=r?t.slice():t&&typeof t==`object`?Object.keys(t).map(e=>[t[e],e]):[];return i.length?i.map((t,a)=>{let s=r?t:t[0],c=r?a:t[1],l=Object.create(e);return l[n]=s,o&&(l[o]=c),l[`@`]=s,l.loop={index:a+1,index0:a,first:!a,last:a===i.length-1,length:i.length},w(u,l)}).join(``):w(d,e)})}else/^#(?:if|elif|else)(?:\s|$)/.test(a)||a[0]===`/`?C(i):a[0]===`#`?x(`Unknown {{`+a+`}}`,`SJABLOON_UNKNOWN_BLOCK`,i):t.push(T(i,n))}return e.length&&x(`Missing {{`+e[e.length-1]+`}}`,`SJABLOON_UNCLOSED_BLOCK`),t};function k(e,t){d=t,p=[`$`,`@`],m=new Set,h=new Set,g=String(e),_=[],l=c(g),u=0;let n=O([]),r=(e,t)=>{e||={};let r=Object.create(e);return r.$=t?t.root:e,t?`item`in t&&(r[`@`]=t.item):r[`@`]=e,w(n,r)};return r.names=Array.from(m),r.functions=Array.from(h),r}function A(e,t,n){return k(e,n)(t)}exports.isDiagnostic=s,exports.render=A,exports.template=k;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("xprsn");const t={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},n=e=>String(e).replace(/[&<>"']/g,e=>t[e]),r=/^(?:__proto__|constructor|prototype)$/,i=new WeakSet,a=i.add.bind(i),o=i.has.bind(i),s=e=>o(e);let c=e=>{let t=[];for(let n=0,r=1;n<e.length;){let i=e.indexOf(`{{`,n);if(i<0){t.push([0,e.slice(n)]);break}i>n&&t.push([0,e.slice(n,i)]);let a=e[i+2]===`{`,o=i+2+a,s=e[o]===`-`,c=-1;if(s&&o++,a&&r&&(c=e.indexOf(`}}}`,o),c<0&&(r=0)),c<0&&(a&&(a=!1,o=i+2,s=e[o]===`-`,s&&o++),c=e.indexOf(`}}`,o)),c<0){t.push([0,e.slice(i)]);break}let l=c>o&&e[c-1]===`-`,u=l?c-1:c,d=e.slice(o,u),f=d.trim(),p=o+d.length-d.trimStart().length,m=c+2+a,h=[a?1:2,f,i,m,p],g=t.at(-1);if(s&&g?.[0]===0&&g[1]&&(g[1]=g[1].trimEnd()),t.push(h),n=m,l)for(;/\s/.test(e[n]);)n++}return t},l,u,d,f,p,m,h,g,_;const v=Symbol();let y=()=>Object.freeze(_.slice()),b=(e,t)=>(_.length<256||S(`Template too deeply nested`,`SJABLOON_TOO_DEEP`,t),Object.freeze({type:e,start:t[2],end:t[3]})),x=(e,t)=>(Object.defineProperty(e,"blocks",{value:t,enumerable:!0}),a(e),e),S=(e,t,n,r=n?.[2]??g.length,i=n?.[3]??g.length)=>{let a=SyntaxError(e);throw a.code=t,a.start=r,a.end=i,x(a,y())},C=(t,n,r,i=e.isDiagnostic)=>{throw i(t)?(t.start+=n,t.end+=n,x(t,r)):t},w=e=>S(`Unexpected {{`+e[1]+`}}`,`SJABLOON_UNEXPECTED_TAG`,e),T=(e,t)=>e.map(e=>e(t)).join(``),E=(e,t)=>(e=>(n,r)=>(r=e(n),n[v]?.push(r),t(r??``)))(D(e[1],e[4],y())),D=(t,n,r)=>{let i;try{i=(0,e.compile)(t,d)}catch(e){C(e,n,r)}for(let e of i.names)p.includes(e)||m.add(e);for(let e of i.functions)h.add(e);return e=>{try{return i(e)}catch(e){C(e,n,r,i.isDiagnostic)}}},O=e=>{let t=k([`#elif`,`#else`,`/if`]),n=f[1],r=[];return n.startsWith(`#elif `)?r=[O(D(n.slice(6),f[4]+6,y()))]:n===`#else`?(r=k([`/if`]),f[1]===`/if`||w(f)):n!==`/if`&&w(f),n=>T(e(n)?t:r,n)},k=e=>{let t=[];for(let i;i=l[u++];){let a=i[1];if(!i[0])t.push((e=>()=>e)(a));else if(i[0]===1)t.push(E(i,String));else if(e.includes(a.split(` `)[0]))return f=i,t;else if(a[0]!==`!`)if(a.startsWith(`#if `))_.push(b(`if`,i)),t.push(O(D(a.slice(4),i[4]+4,y()))),_.pop();else if(/^#each(?:\s|$)/.test(a)){_.push(b(`each`,i));let e=/^#each ([\s\S]+) as ((\w+)(?:\s*,\s*(\w+))?)$/.exec(a);e||S(`Bad {{`+a+`}}`,`SJABLOON_EACH_SYNTAX`,i);let n=e[3],o=e[4],s=i[4]+a.length-e[2].length;if(r.test(n)&&S(`Bad {{`+a+`}}`,`SJABLOON_BLOCKED_BINDING`,i,s,s+n.length),o&&r.test(o)){let e=i[4]+a.length-o.length;S(`Bad {{`+a+`}}`,`SJABLOON_BLOCKED_BINDING`,i,e,e+o.length)}let c=D(e[1],i[4]+6,y()),l=p.length;p.push(n),o&&p.push(o),p.push(`loop`);let u=k([`#else`,`/each`]);p.length=l;let d=[];f[1]===`#else`?(d=k([`/each`]),f[1]===`/each`||w(f)):f[1]!==`/each`&&w(f),_.pop(),t.push(e=>{let t=c(e),r=Array.isArray(t),i=r?t.slice():t&&typeof t==`object`?Object.keys(t).map(e=>[t[e],e]):[];return i.length?i.map((t,a)=>{let s=r?t:t[0],c=r?a:t[1],l=Object.create(e);return l[n]=s,o&&(l[o]=c),l[`@`]=s,l.loop={index:a+1,index0:a,first:!a,last:a===i.length-1,length:i.length},T(u,l)}).join(``):T(d,e)})}else/^#(?:if|elif|else)(?:\s|$)/.test(a)||a[0]===`/`?w(i):a[0]===`#`?S(`Unknown {{`+a+`}}`,`SJABLOON_UNKNOWN_BLOCK`,i):t.push(E(i,n))}return e.length&&S(`Missing {{`+e[e.length-1]+`}}`,`SJABLOON_UNCLOSED_BLOCK`),t};function A(e,t){d=t,p=[`$`,`@`],m=new Set,h=new Set,g=String(e),_=[],l=c(g),u=0;let n;try{n=k([])}catch(e){throw e instanceof RangeError&&S(`Template too deeply nested`,`SJABLOON_TOO_DEEP`),e}let r=(e,t,r)=>{e||={};let i=Object.create(e);return i.$=t?t.root:e,t?`item`in t&&(i[`@`]=t.item):i[`@`]=e,i[v]=r,T(n,i)},i=(e,t)=>r(e,t);return i.withRaw=(e,t,n=[])=>({text:r(e,t,n),raws:n}),i.names=Array.from(m),i.functions=Array.from(h),i}function j(e,t,n){return A(e,n)(t)}exports.isDiagnostic=s,exports.render=j,exports.template=A;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{compile as e,isDiagnostic as t}from"xprsn";const n={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},r=e=>String(e).replace(/[&<>"']/g,e=>n[e]),i=/^(?:__proto__|constructor|prototype)$/,a=new WeakSet,o=a.add.bind(a),s=a.has.bind(a),c=e=>s(e);let l=e=>{let t=[];for(let n=0,r=1;n<e.length;){let i=e.indexOf(`{{`,n);if(i<0){t.push([0,e.slice(n)]);break}i>n&&t.push([0,e.slice(n,i)]);let a=e[i+2]===`{`,o=i+2+a,s=e[o]===`-`,c=-1;if(s&&o++,a&&r&&(c=e.indexOf(`}}}`,o),c<0&&(r=0)),c<0&&(a&&(a=!1,o=i+2,s=e[o]===`-`,s&&o++),c=e.indexOf(`}}`,o)),c<0){t.push([0,e.slice(i)]);break}let l=c>o&&e[c-1]===`-`,u=l?c-1:c,d=e.slice(o,u),f=d.trim(),p=o+d.length-d.trimStart().length,m=c+2+a,h=[a?1:2,f,i,m,o,u,p,p+f.length,s,l],g=t.at(-1);if(s&&g?.[0]===0&&g[1]&&(g[1]=g[1].trimEnd()),t.push(h),n=m,l)for(;/\s/.test(e[n]);)n++}return t},u,d,f,p,m,h,g,_,v,y=()=>Object.freeze(v.slice()),b=(e,t)=>Object.freeze({type:e,start:t[2],end:t[3]}),x=(e,t)=>(Object.defineProperty(e,"blocks",{value:t,enumerable:!0}),o(e),e),S=(e,t,n,r=n?.[2]??_.length,i=n?.[3]??_.length)=>{let a=SyntaxError(e);throw a.code=t,a.start=r,a.end=i,x(a,y())},C=(e,n,r,i=t)=>{throw i(e)?(e.start+=n,e.end+=n,x(e,r)):e},w=e=>S(`Unexpected {{`+e[1]+`}}`,`SJABLOON_UNEXPECTED_TAG`,e),T=(e,t)=>e.map(e=>e(t)).join(``),E=(e,t)=>(e=>n=>t(e(n)??``))(D(e[1],e[6],y())),D=(t,n,r)=>{let i;try{i=e(t,f)}catch(e){C(e,n,r)}for(let e of i.names)m.includes(e)||h.add(e);for(let e of i.functions)g.add(e);return e=>{try{return i(e)}catch(e){C(e,n,r,i.isDiagnostic)}}},O=e=>{let t=k([`#elif`,`#else`,`/if`]),n=p[1],r=[];return n.startsWith(`#elif `)?r=[O(D(n.slice(6),p[6]+6,y()))]:n===`#else`?(r=k([`/if`]),p[1]===`/if`||w(p)):n!==`/if`&&w(p),n=>T(e(n)?t:r,n)},k=e=>{let t=[];for(let n;n=u[d++];){let a=n[1];if(!n[0])t.push((e=>()=>e)(a));else if(n[0]===1)t.push(E(n,String));else if(e.includes(a.split(` `)[0]))return p=n,t;else if(a[0]!==`!`)if(a.startsWith(`#if `))v.push(b(`if`,n)),t.push(O(D(a.slice(4),n[6]+4,y()))),v.pop();else if(/^#each(?:\s|$)/.test(a)){v.push(b(`each`,n));let e=/^#each ([\s\S]+) as ((\w+)(?:\s*,\s*(\w+))?)$/.exec(a);e||S(`Bad {{`+a+`}}`,`SJABLOON_EACH_SYNTAX`,n);let r=e[3],o=e[4],s=n[6]+a.length-e[2].length;if(i.test(r)&&S(`Bad {{`+a+`}}`,`SJABLOON_BLOCKED_BINDING`,n,s,s+r.length),o&&i.test(o)){let e=n[6]+a.length-o.length;S(`Bad {{`+a+`}}`,`SJABLOON_BLOCKED_BINDING`,n,e,e+o.length)}let c=D(e[1],n[6]+6,y()),l=m.length;m.push(r),o&&m.push(o),m.push(`loop`);let u=k([`#else`,`/each`]);m.length=l;let d=[];p[1]===`#else`?(d=k([`/each`]),p[1]===`/each`||w(p)):p[1]!==`/each`&&w(p),v.pop(),t.push(e=>{let t=c(e),n=Array.isArray(t),i=n?t.slice():t&&typeof t==`object`?Object.keys(t).map(e=>[t[e],e]):[];return i.length?i.map((t,a)=>{let s=n?t:t[0],c=n?a:t[1],l=Object.create(e);return l[r]=s,o&&(l[o]=c),l[`@`]=s,l.loop={index:a+1,index0:a,first:!a,last:a===i.length-1,length:i.length},T(u,l)}).join(``):T(d,e)})}else/^#(?:if|elif|else)(?:\s|$)/.test(a)||a[0]===`/`?w(n):a[0]===`#`?S(`Unknown {{`+a+`}}`,`SJABLOON_UNKNOWN_BLOCK`,n):t.push(E(n,r))}return e.length&&S(`Missing {{`+e[e.length-1]+`}}`,`SJABLOON_UNCLOSED_BLOCK`),t};function A(e,t){f=t,m=[`$`,`@`],h=new Set,g=new Set,_=String(e),v=[],u=l(_),d=0;let n=k([]),r=(e,t)=>{e||={};let r=Object.create(e);return r.$=t?t.root:e,t?`item`in t&&(r[`@`]=t.item):r[`@`]=e,T(n,r)};return r.names=Array.from(h),r.functions=Array.from(g),r}function j(e,t,n){return A(e,n)(t)}export{c as isDiagnostic,j as render,A as template};
1
+ import{compile as e,isDiagnostic as t}from"xprsn";const n={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},r=e=>String(e).replace(/[&<>"']/g,e=>n[e]),i=/^(?:__proto__|constructor|prototype)$/,a=new WeakSet,o=a.add.bind(a),s=a.has.bind(a),c=e=>s(e);let l=e=>{let t=[];for(let n=0,r=1;n<e.length;){let i=e.indexOf(`{{`,n);if(i<0){t.push([0,e.slice(n)]);break}i>n&&t.push([0,e.slice(n,i)]);let a=e[i+2]===`{`,o=i+2+a,s=e[o]===`-`,c=-1;if(s&&o++,a&&r&&(c=e.indexOf(`}}}`,o),c<0&&(r=0)),c<0&&(a&&(a=!1,o=i+2,s=e[o]===`-`,s&&o++),c=e.indexOf(`}}`,o)),c<0){t.push([0,e.slice(i)]);break}let l=c>o&&e[c-1]===`-`,u=l?c-1:c,d=e.slice(o,u),f=d.trim(),p=o+d.length-d.trimStart().length,m=c+2+a,h=[a?1:2,f,i,m,p],g=t.at(-1);if(s&&g?.[0]===0&&g[1]&&(g[1]=g[1].trimEnd()),t.push(h),n=m,l)for(;/\s/.test(e[n]);)n++}return t},u,d,f,p,m,h,g,_,v;const y=Symbol();let b=()=>Object.freeze(v.slice()),x=(e,t)=>(v.length<256||C(`Template too deeply nested`,`SJABLOON_TOO_DEEP`,t),Object.freeze({type:e,start:t[2],end:t[3]})),S=(e,t)=>(Object.defineProperty(e,"blocks",{value:t,enumerable:!0}),o(e),e),C=(e,t,n,r=n?.[2]??_.length,i=n?.[3]??_.length)=>{let a=SyntaxError(e);throw a.code=t,a.start=r,a.end=i,S(a,b())},w=(e,n,r,i=t)=>{throw i(e)?(e.start+=n,e.end+=n,S(e,r)):e},T=e=>C(`Unexpected {{`+e[1]+`}}`,`SJABLOON_UNEXPECTED_TAG`,e),E=(e,t)=>e.map(e=>e(t)).join(``),D=(e,t)=>(e=>(n,r)=>(r=e(n),n[y]?.push(r),t(r??``)))(O(e[1],e[4],b())),O=(t,n,r)=>{let i;try{i=e(t,f)}catch(e){w(e,n,r)}for(let e of i.names)m.includes(e)||h.add(e);for(let e of i.functions)g.add(e);return e=>{try{return i(e)}catch(e){w(e,n,r,i.isDiagnostic)}}},k=e=>{let t=A([`#elif`,`#else`,`/if`]),n=p[1],r=[];return n.startsWith(`#elif `)?r=[k(O(n.slice(6),p[4]+6,b()))]:n===`#else`?(r=A([`/if`]),p[1]===`/if`||T(p)):n!==`/if`&&T(p),n=>E(e(n)?t:r,n)},A=e=>{let t=[];for(let n;n=u[d++];){let a=n[1];if(!n[0])t.push((e=>()=>e)(a));else if(n[0]===1)t.push(D(n,String));else if(e.includes(a.split(` `)[0]))return p=n,t;else if(a[0]!==`!`)if(a.startsWith(`#if `))v.push(x(`if`,n)),t.push(k(O(a.slice(4),n[4]+4,b()))),v.pop();else if(/^#each(?:\s|$)/.test(a)){v.push(x(`each`,n));let e=/^#each ([\s\S]+) as ((\w+)(?:\s*,\s*(\w+))?)$/.exec(a);e||C(`Bad {{`+a+`}}`,`SJABLOON_EACH_SYNTAX`,n);let r=e[3],o=e[4],s=n[4]+a.length-e[2].length;if(i.test(r)&&C(`Bad {{`+a+`}}`,`SJABLOON_BLOCKED_BINDING`,n,s,s+r.length),o&&i.test(o)){let e=n[4]+a.length-o.length;C(`Bad {{`+a+`}}`,`SJABLOON_BLOCKED_BINDING`,n,e,e+o.length)}let c=O(e[1],n[4]+6,b()),l=m.length;m.push(r),o&&m.push(o),m.push(`loop`);let u=A([`#else`,`/each`]);m.length=l;let d=[];p[1]===`#else`?(d=A([`/each`]),p[1]===`/each`||T(p)):p[1]!==`/each`&&T(p),v.pop(),t.push(e=>{let t=c(e),n=Array.isArray(t),i=n?t.slice():t&&typeof t==`object`?Object.keys(t).map(e=>[t[e],e]):[];return i.length?i.map((t,a)=>{let s=n?t:t[0],c=n?a:t[1],l=Object.create(e);return l[r]=s,o&&(l[o]=c),l[`@`]=s,l.loop={index:a+1,index0:a,first:!a,last:a===i.length-1,length:i.length},E(u,l)}).join(``):E(d,e)})}else/^#(?:if|elif|else)(?:\s|$)/.test(a)||a[0]===`/`?T(n):a[0]===`#`?C(`Unknown {{`+a+`}}`,`SJABLOON_UNKNOWN_BLOCK`,n):t.push(D(n,r))}return e.length&&C(`Missing {{`+e[e.length-1]+`}}`,`SJABLOON_UNCLOSED_BLOCK`),t};function j(e,t){f=t,m=[`$`,`@`],h=new Set,g=new Set,_=String(e),v=[],u=l(_),d=0;let n;try{n=A([])}catch(e){throw e instanceof RangeError&&C(`Template too deeply nested`,`SJABLOON_TOO_DEEP`),e}let r=(e,t,r)=>{e||={};let i=Object.create(e);return i.$=t?t.root:e,t?`item`in t&&(i[`@`]=t.item):i[`@`]=e,i[y]=r,E(n,i)},i=(e,t)=>r(e,t);return i.withRaw=(e,t,n=[])=>({text:r(e,t,n),raws:n}),i.names=Array.from(h),i.functions=Array.from(g),i}function M(e,t,n){return j(e,n)(t)}export{c as isDiagnostic,M as render,j as template};
package/index.d.ts CHANGED
@@ -44,9 +44,16 @@ export function isDiagnostic(error: unknown): error is SjabloonDiagnostic;
44
44
  * `root` and `@` becomes `item` (two distinct objects). Omit `item` to leave
45
45
  * `@` unbound, so reading `@.x` throws through xprsn's guard.
46
46
  *
47
+ * The renderer also exposes `withRaw(values, scope)`: one render, both channels.
48
+ * It returns `{ text, raws }` — the rendered string plus each interpolation's
49
+ * pre-escape, pre-stringify value (`{{ }}` and `{{{ }}}` alike, nullish
50
+ * included), in render order: loop bodies push once per iteration, untaken
51
+ * branches push nothing. Block expressions (`#if` conditions, `#each`
52
+ * collections) are never captured.
53
+ *
47
54
  * @param {string} str The template, e.g. `'Hello {{ user.name }}!'`.
48
55
  * @param {Record<string, Function>} [funcs] Functions callable inside expressions.
49
- * @returns {{(values?: Record<string, any>, scope?: { root?: any, item?: any }): string, names: string[], functions: string[]}} Renderer for the compiled template.
56
+ * @returns {{(values?: Record<string, any>, scope?: { root?: any, item?: any }): string, withRaw: (values?: Record<string, any>, scope?: { root?: any, item?: any }) => { text: string, raws: unknown[] }, names: string[], functions: string[]}} Renderer for the compiled template.
50
57
  * @throws {SyntaxError} On malformed tags, unclosed blocks, or bad expressions.
51
58
  */
52
59
  export function template(str: string, funcs?: Record<string, Function>): {
@@ -54,6 +61,13 @@ export function template(str: string, funcs?: Record<string, Function>): {
54
61
  root?: any;
55
62
  item?: any;
56
63
  }): string;
64
+ withRaw(values?: Record<string, any>, scope?: {
65
+ root?: any;
66
+ item?: any;
67
+ }): {
68
+ text: string;
69
+ raws: unknown[];
70
+ };
57
71
  names: string[];
58
72
  functions: string[];
59
73
  };
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "sjabloon",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Tiny, CSP-safe template engine for JavaScript, powered by xprsn expressions. No eval, no new Function.",
5
- "repository": "robinvdvleuten/sjabloon",
6
- "license": "MIT",
5
+ "repository": "getquario/sjabloon",
6
+ "license": "Apache-2.0",
7
7
  "author": {
8
8
  "name": "Robin van der Vleuten",
9
9
  "email": "robin@webstronauts.com",
@@ -21,6 +21,9 @@
21
21
  "require": "./dist/index.cjs"
22
22
  }
23
23
  },
24
+ "engines": {
25
+ "node": ">=22.0.0"
26
+ },
24
27
  "files": [
25
28
  "dist",
26
29
  "src",
@@ -29,16 +32,18 @@
29
32
  "size-limit": [
30
33
  {
31
34
  "path": "dist/index.js",
32
- "limit": "1.7 kB"
35
+ "limit": "1.76 kB"
33
36
  },
34
37
  {
35
38
  "path": "dist/index.cjs",
36
- "limit": "1.7 kB"
39
+ "limit": "1.78 kB"
37
40
  }
38
41
  ],
39
42
  "scripts": {
40
43
  "bench": "node --disallow-code-generation-from-strings bench/index.js",
44
+ "bench:comparison": "npm run build && npm --prefix bench/comparison run bench",
41
45
  "build": "tsdown",
46
+ "check": "run-s build size test fuzz:regression test:browser",
42
47
  "fuzz": "npm run fuzz:prepare && run-s fuzz:compile fuzz:render fuzz:structured",
43
48
  "fuzz:prepare": "node -e \"for (const x of ['compile','render','structured']) require('fs').mkdirSync('.fuzz-corpus/'+x,{recursive:true})\"",
44
49
  "fuzz:compile": "NODE_OPTIONS=--disallow-code-generation-from-strings jazzer fuzz/compile.fuzz.js -i src/ --customHooks fuzz/hooks.js --disableBugDetectors='command-injection|path-traversal|ssrf' --sync .fuzz-corpus/compile fuzz/corpus/compile -- -max_total_time=60 -use_value_profile=1 -dict=fuzz/sjabloon.dict -artifact_prefix=fuzz/",
@@ -50,8 +55,10 @@
50
55
  "fuzz:regression:structured": "NODE_OPTIONS=--disallow-code-generation-from-strings jazzer fuzz/structured.fuzz.js -i src/ --customHooks fuzz/hooks.js --disableBugDetectors='command-injection|path-traversal|ssrf' --sync --mode=regression fuzz/corpus/structured -- -artifact_prefix=fuzz/",
51
56
  "prepublishOnly": "npm run build",
52
57
  "size": "size-limit",
53
- "test": "node --disallow-code-generation-from-strings --test --test-concurrency=1 test/*.test.js && npm run typecheck",
54
- "typecheck": "tsc --noEmit --strict test/types.check.ts"
58
+ "test": "run-s test:unit test:types",
59
+ "test:unit": "node --disallow-code-generation-from-strings --test --test-concurrency=1 test/*.test.js",
60
+ "test:browser": "npm run build && playwright install chromium && node test/browser/harness.js",
61
+ "test:types": "tsc"
55
62
  },
56
63
  "keywords": [
57
64
  "template",
@@ -68,6 +75,7 @@
68
75
  "@jazzer.js/core": "^4.0.0",
69
76
  "@size-limit/file": "^12.1.0",
70
77
  "npm-run-all": "^4.1.5",
78
+ "playwright": "^1.61.1",
71
79
  "size-limit": "^12.1.0",
72
80
  "tsdown": "^0.22.12",
73
81
  "typescript": "^7.0.2"
package/src/index.js CHANGED
@@ -40,7 +40,7 @@ let lex = s => {
40
40
  const r = b > p && s[b - 1] === '-';
41
41
  const q = r ? b - 1 : b, whole = s.slice(p, q), body = whole.trim();
42
42
  const start = p + whole.length - whole.trimStart().length, end = b + 2 + raw;
43
- const t = [raw ? 1 : 2, body, a, end, p, q, start, start + body.length, l, r];
43
+ const t = [raw ? 1 : 2, body, a, end, start];
44
44
  const prev = out.at(-1);
45
45
  if (l && prev?.[0] === 0 && prev[1]) prev[1] = prev[1].trimEnd();
46
46
  out.push(t);
@@ -54,8 +54,19 @@ let lex = s => {
54
54
  // `nms` collects free variables, `fnms` the registry functions called.
55
55
  let toks, i, fns, last, bound, nms, fnms, src, blocks;
56
56
 
57
+ // The opt-in raw-value collector rides the render's root scope under a
58
+ // symbol: invisible to expressions, inherited by `#each` child scopes, and
59
+ // naturally per render, so re-entrant renders each collect into their own.
60
+ const RAWS = Symbol();
61
+
57
62
  let snap = () => Object.freeze(blocks.slice());
58
- let opener = (type, t) => Object.freeze({ type, start: t[2], end: t[3] });
63
+ // Block nesting is capped so a pathological template fails as a deterministic
64
+ // SyntaxError at the offending opener, far below the native stack limit.
65
+ const DEPTH = 256;
66
+ let opener = (type, t) => {
67
+ blocks.length < DEPTH || fault('Template too deeply nested', 'SJABLOON_TOO_DEEP', t);
68
+ return Object.freeze({ type, start: t[2], end: t[3] });
69
+ };
59
70
  let attach = (e, context) => {
60
71
  Object.defineProperty(e, 'blocks', { value: context, enumerable: true });
61
72
  mark(e);
@@ -80,8 +91,9 @@ let unexpected = t => fault('Unexpected {{' + t[1] + '}}', 'SJABLOON_UNEXPECTED_
80
91
  let run = (nodes, v) => nodes.map(n => n(v)).join('');
81
92
 
82
93
  // A leaf interpolation node: compile `src`, render nullish as '', apply `wrap`
83
- // (`esc` for `{{ }}`, `String` for the raw `{{{ }}}` form).
84
- let interp = (t, wrap) => (e => v => wrap(e(v) ?? ''))(cp(t[1], t[6], snap()));
94
+ // (`esc` for `{{ }}`, `String` for the raw `{{{ }}}` form). The pre-stringify
95
+ // result feeds the opt-in `raws` collector; block expressions never do.
96
+ let interp = (t, wrap) => (e => (v, x) => (x = e(v), v[RAWS]?.push(x), wrap(x ?? '')))(cp(t[1], t[4], snap()));
85
97
 
86
98
  // Compile one expression and collect its free variables (minus the loop
87
99
  // variables currently in scope, which belong to the template) and the registry
@@ -109,7 +121,7 @@ let branch = cond => {
109
121
  const then = parse(['#elif', '#else', '/if']);
110
122
  const tag = last[1];
111
123
  let els = [];
112
- if (tag.startsWith('#elif ')) els = [branch(cp(tag.slice(6), last[6] + 6, snap()))];
124
+ if (tag.startsWith('#elif ')) els = [branch(cp(tag.slice(6), last[4] + 6, snap()))];
113
125
  else if (tag === '#else') {
114
126
  els = parse(['/if']);
115
127
  last[1] === '/if' || unexpected(last);
@@ -132,19 +144,19 @@ let parse = stops => {
132
144
  // comment
133
145
  } else if (tag.startsWith('#if ')) {
134
146
  blocks.push(opener('if', t));
135
- nodes.push(branch(cp(tag.slice(4), t[6] + 4, snap())));
147
+ nodes.push(branch(cp(tag.slice(4), t[4] + 4, snap())));
136
148
  blocks.pop();
137
149
  } else if (/^#each(?:\s|$)/.test(tag)) {
138
150
  blocks.push(opener('each', t));
139
151
  const m = /^#each ([\s\S]+) as ((\w+)(?:\s*,\s*(\w+))?)$/.exec(tag);
140
152
  m || fault('Bad {{' + tag + '}}', 'SJABLOON_EACH_SYNTAX', t);
141
- const name = m[3], idx = m[4], at = t[6] + tag.length - m[2].length;
153
+ const name = m[3], idx = m[4], at = t[4] + tag.length - m[2].length;
142
154
  if (BLOCKED.test(name)) fault('Bad {{' + tag + '}}', 'SJABLOON_BLOCKED_BINDING', t, at, at + name.length);
143
155
  if (idx && BLOCKED.test(idx)) {
144
- const p = t[6] + tag.length - idx.length;
156
+ const p = t[4] + tag.length - idx.length;
145
157
  fault('Bad {{' + tag + '}}', 'SJABLOON_BLOCKED_BINDING', t, p, p + idx.length);
146
158
  }
147
- const list = cp(m[1], t[6] + 6, snap());
159
+ const list = cp(m[1], t[4] + 6, snap());
148
160
  // `name`, `idx`, and `loop` are engine-bound inside the body, so
149
161
  // exclude them from names there and restore outer bindings after.
150
162
  const mark = bound.length;
@@ -207,9 +219,16 @@ let parse = stops => {
207
219
  * `root` and `@` becomes `item` (two distinct objects). Omit `item` to leave
208
220
  * `@` unbound, so reading `@.x` throws through xprsn's guard.
209
221
  *
222
+ * The renderer also exposes `withRaw(values, scope)`: one render, both channels.
223
+ * It returns `{ text, raws }` — the rendered string plus each interpolation's
224
+ * pre-escape, pre-stringify value (`{{ }}` and `{{{ }}}` alike, nullish
225
+ * included), in render order: loop bodies push once per iteration, untaken
226
+ * branches push nothing. Block expressions (`#if` conditions, `#each`
227
+ * collections) are never captured.
228
+ *
210
229
  * @param {string} str The template, e.g. `'Hello {{ user.name }}!'`.
211
230
  * @param {Record<string, Function>} [funcs] Functions callable inside expressions.
212
- * @returns {{(values?: Record<string, any>, scope?: { root?: any, item?: any }): string, names: string[], functions: string[]}} Renderer for the compiled template.
231
+ * @returns {{(values?: Record<string, any>, scope?: { root?: any, item?: any }): string, withRaw: (values?: Record<string, any>, scope?: { root?: any, item?: any }) => { text: string, raws: unknown[] }, names: string[], functions: string[]}} Renderer for the compiled template.
213
232
  * @throws {SyntaxError} On malformed tags, unclosed blocks, or bad expressions.
214
233
  */
215
234
  export function template(str, funcs) {
@@ -223,21 +242,35 @@ export function template(str, funcs) {
223
242
  blocks = [];
224
243
  toks = lex(src);
225
244
  i = 0;
226
- const nodes = parse([]);
245
+ // Deeply nested blocks overflow the recursive-descent parser; surface that
246
+ // as a SyntaxError so malformed input keeps its documented compile-time
247
+ // contract (mirroring xprsn's XPRSN_TOO_DEEP for expressions).
248
+ let nodes;
249
+ try {
250
+ nodes = parse([]);
251
+ } catch (x) {
252
+ // An empty span at the end, like an unclosed block.
253
+ if (x instanceof RangeError) fault('Template too deeply nested', 'SJABLOON_TOO_DEEP');
254
+ throw x;
255
+ }
227
256
  // Wrap the values in a root scope carrying the anchors, without mutating
228
257
  // what the caller passed: by default `$` and `@` both point at the root.
229
258
  // An embedder can override the anchors with a `{ root, item }` second arg:
230
259
  // `$` = root, `@` = item (distinct objects). Omitting `item` leaves `@`
231
260
  // unbound, so `@.x` throws through xprsn's guard — a group-header band that
232
261
  // has no current row wants exactly that.
233
- const f = (v, o) => {
262
+ const g = (v, o, w) => {
234
263
  v = v || {};
235
264
  const r = Object.create(v);
236
265
  r['$'] = o ? o.root : v;
237
266
  if (!o) r['@'] = v;
238
267
  else if ('item' in o) r['@'] = o.item;
268
+ r[RAWS] = w;
239
269
  return run(nodes, r);
240
270
  };
271
+ const f = (v, o) => g(v, o);
272
+ // One render, both channels: the rendered string plus the ordered raws.
273
+ f.withRaw = (v, o, w = []) => ({ text: g(v, o, w), raws: w });
241
274
  // Array.from, not a spread: the bundler's transpile turns `[...set]` into
242
275
  // `[].concat(set)`, which wraps the Set instead of unpacking it.
243
276
  f.names = Array.from(nms);