sjabloon 0.4.1 → 0.5.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/README.md +16 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/index.d.ts +68 -40
- package/package.json +9 -8
- package/src/index.js +117 -62
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# sjabloon
|
|
2
2
|
|
|
3
|
-
A tiny, CSP-safe template engine for JavaScript. **~1.
|
|
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
|
[](https://www.npmjs.com/package/sjabloon)
|
|
6
6
|
[](https://github.com/robinvdvleuten/sjabloon/actions/workflows/test.yml)
|
|
@@ -59,6 +59,21 @@ tpl.functions; // => ['fmt']
|
|
|
59
59
|
|
|
60
60
|
Shorthand for `template(str, functions)(values)`.
|
|
61
61
|
|
|
62
|
+
### Error diagnostics
|
|
63
|
+
|
|
64
|
+
Sjabloon errors keep their native `SyntaxError` or `TypeError` class and expose:
|
|
65
|
+
|
|
66
|
+
- `code`: a stable `SJABLOON_*` parser category or the original `XPRSN_*` expression category;
|
|
67
|
+
- `start`: a zero-based offset in the original template;
|
|
68
|
+
- `end`: the exclusive template offset;
|
|
69
|
+
- `blocks`: a frozen, outermost-first array of `{ type, start, end }` opener spans.
|
|
70
|
+
|
|
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.
|
|
72
|
+
|
|
73
|
+
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
|
+
|
|
75
|
+
Use `isDiagnostic(error)` when a host needs to distinguish those errors. It returns `true` only for errors produced or translated by the same sjabloon module instance. Copying a documented `code`, `start`, `end`, and `blocks` onto another error does not authenticate it. A diagnostic from another installed copy or module instance also returns `false`.
|
|
76
|
+
|
|
62
77
|
## Syntax
|
|
63
78
|
|
|
64
79
|
| Tag | Meaning |
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("xprsn");const t={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},n=e=>String(e).replace(/[&<>"']/g,e=>t[e]),r=/^(?:__proto__|constructor|prototype)$/,i=
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("xprsn");const t={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},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;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{compile as e}from"xprsn";const
|
|
1
|
+
import{compile as e,isDiagnostic as t}from"xprsn";const n={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},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};
|
package/index.d.ts
CHANGED
|
@@ -1,40 +1,68 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
|
|
40
|
-
|
|
1
|
+
import type { XprsnErrorCode } from 'xprsn';
|
|
2
|
+
|
|
3
|
+
export type SjabloonErrorCode =
|
|
4
|
+
| XprsnErrorCode
|
|
5
|
+
| 'SJABLOON_EACH_SYNTAX'
|
|
6
|
+
| 'SJABLOON_BLOCKED_BINDING'
|
|
7
|
+
| 'SJABLOON_UNEXPECTED_TAG'
|
|
8
|
+
| 'SJABLOON_UNKNOWN_BLOCK'
|
|
9
|
+
| 'SJABLOON_UNCLOSED_BLOCK';
|
|
10
|
+
|
|
11
|
+
export interface SjabloonBlock {
|
|
12
|
+
readonly type: 'if' | 'each';
|
|
13
|
+
readonly start: number;
|
|
14
|
+
readonly end: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface SjabloonDiagnostic extends Error {
|
|
18
|
+
readonly code: SjabloonErrorCode;
|
|
19
|
+
readonly start: number;
|
|
20
|
+
readonly end: number;
|
|
21
|
+
readonly blocks: readonly SjabloonBlock[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Check whether an error was produced or translated by this sjabloon module instance.
|
|
26
|
+
*/
|
|
27
|
+
export function isDiagnostic(error: unknown): error is SjabloonDiagnostic;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Compile a template once, render it many times.
|
|
31
|
+
*
|
|
32
|
+
* The returned renderer exposes `names`: the variables the template reads
|
|
33
|
+
* from your values, deduplicated. Loop variables the template introduces are
|
|
34
|
+
* not included. It also exposes `functions`: the registry functions the
|
|
35
|
+
* template calls, deduplicated.
|
|
36
|
+
*
|
|
37
|
+
* Two anchors are always in scope: `$` is the root values, and `@` is the
|
|
38
|
+
* current `#each` item (the root outside any loop). They let a nested loop
|
|
39
|
+
* reach the root (`$.company`) or the current item (`@.total`) explicitly,
|
|
40
|
+
* past any shadowing. Neither counts as a `name`.
|
|
41
|
+
*
|
|
42
|
+
* An embedder with its own scope model can override the anchors per render by
|
|
43
|
+
* passing `{ root, item }` as the renderer's second argument: `$` becomes
|
|
44
|
+
* `root` and `@` becomes `item` (two distinct objects). Omit `item` to leave
|
|
45
|
+
* `@` unbound, so reading `@.x` throws through xprsn's guard.
|
|
46
|
+
*
|
|
47
|
+
* @param {string} str The template, e.g. `'Hello {{ user.name }}!'`.
|
|
48
|
+
* @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.
|
|
50
|
+
* @throws {SyntaxError} On malformed tags, unclosed blocks, or bad expressions.
|
|
51
|
+
*/
|
|
52
|
+
export function template(str: string, funcs?: Record<string, Function>): {
|
|
53
|
+
(values?: Record<string, any>, scope?: {
|
|
54
|
+
root?: any;
|
|
55
|
+
item?: any;
|
|
56
|
+
}): string;
|
|
57
|
+
names: string[];
|
|
58
|
+
functions: string[];
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Compile and render a template in one go.
|
|
62
|
+
*
|
|
63
|
+
* @param {string} str The template to render.
|
|
64
|
+
* @param {Record<string, any>} [values] Variables available to the template.
|
|
65
|
+
* @param {Record<string, Function>} [funcs] Functions callable inside expressions.
|
|
66
|
+
* @returns {string} The rendered output.
|
|
67
|
+
*/
|
|
68
|
+
export function render(str: string, values?: Record<string, any>, funcs?: Record<string, Function>): string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sjabloon",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Tiny, CSP-safe template engine for JavaScript, powered by xprsn expressions. No eval, no new Function.",
|
|
5
5
|
"repository": "robinvdvleuten/sjabloon",
|
|
6
6
|
"license": "MIT",
|
|
@@ -29,15 +29,15 @@
|
|
|
29
29
|
"size-limit": [
|
|
30
30
|
{
|
|
31
31
|
"path": "dist/index.js",
|
|
32
|
-
"limit": "1.
|
|
32
|
+
"limit": "1.7 kB"
|
|
33
33
|
},
|
|
34
34
|
{
|
|
35
35
|
"path": "dist/index.cjs",
|
|
36
|
-
"limit": "1.
|
|
36
|
+
"limit": "1.7 kB"
|
|
37
37
|
}
|
|
38
38
|
],
|
|
39
39
|
"scripts": {
|
|
40
|
-
"bench": "node bench/index.js",
|
|
40
|
+
"bench": "node --disallow-code-generation-from-strings bench/index.js",
|
|
41
41
|
"build": "tsdown",
|
|
42
42
|
"fuzz": "npm run fuzz:prepare && run-s fuzz:compile fuzz:render fuzz:structured",
|
|
43
43
|
"fuzz:prepare": "node -e \"for (const x of ['compile','render','structured']) require('fs').mkdirSync('.fuzz-corpus/'+x,{recursive:true})\"",
|
|
@@ -50,7 +50,8 @@
|
|
|
50
50
|
"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
51
|
"prepublishOnly": "npm run build",
|
|
52
52
|
"size": "size-limit",
|
|
53
|
-
"test": "node --disallow-code-generation-from-strings
|
|
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"
|
|
54
55
|
},
|
|
55
56
|
"keywords": [
|
|
56
57
|
"template",
|
|
@@ -60,7 +61,7 @@
|
|
|
60
61
|
"handlebars"
|
|
61
62
|
],
|
|
62
63
|
"dependencies": {
|
|
63
|
-
"xprsn": "^0.
|
|
64
|
+
"xprsn": "^0.8.0"
|
|
64
65
|
},
|
|
65
66
|
"devDependencies": {
|
|
66
67
|
"@jazzer.js/bug-detectors": "^4.0.0",
|
|
@@ -68,7 +69,7 @@
|
|
|
68
69
|
"@size-limit/file": "^12.1.0",
|
|
69
70
|
"npm-run-all": "^4.1.5",
|
|
70
71
|
"size-limit": "^12.1.0",
|
|
71
|
-
"
|
|
72
|
-
"
|
|
72
|
+
"tsdown": "^0.22.12",
|
|
73
|
+
"typescript": "^7.0.2"
|
|
73
74
|
}
|
|
74
75
|
}
|
package/src/index.js
CHANGED
|
@@ -3,16 +3,22 @@
|
|
|
3
3
|
* Templates compile to a composition of closures; template text is never
|
|
4
4
|
* turned into JavaScript, so strict CSP is satisfied.
|
|
5
5
|
*/
|
|
6
|
-
import { compile } from 'xprsn';
|
|
6
|
+
import { compile, isDiagnostic as isXprsnDiagnostic } from 'xprsn';
|
|
7
7
|
|
|
8
8
|
const ESC = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
|
9
9
|
const esc = s => String(s).replace(/[&<>"']/g, c => ESC[c]);
|
|
10
10
|
const BLOCKED = /^(?:__proto__|constructor|prototype)$/;
|
|
11
|
+
const DIAGNOSTICS = new WeakSet();
|
|
12
|
+
const mark = DIAGNOSTICS.add.bind(DIAGNOSTICS);
|
|
13
|
+
const owns = DIAGNOSTICS.has.bind(DIAGNOSTICS);
|
|
11
14
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
15
|
+
/**
|
|
16
|
+
* Check whether an error was produced or translated by sjabloon.
|
|
17
|
+
*
|
|
18
|
+
* @param {unknown} error Any thrown value.
|
|
19
|
+
* @returns {boolean} Whether `error` is an authentic sjabloon diagnostic.
|
|
20
|
+
*/
|
|
21
|
+
export const isDiagnostic = error => owns(error);
|
|
16
22
|
|
|
17
23
|
// Linear scan into text/tag/raw tokens. Dashes hug braces (`{{- x -}}` trims;
|
|
18
24
|
// `{{ -x }}` stays unary minus). Prefer {{{ }}} over {{ }}. `triple` latches
|
|
@@ -21,98 +27,148 @@ let lex = s => {
|
|
|
21
27
|
const out = [];
|
|
22
28
|
for (let i = 0, triple = 1; i < s.length; ) {
|
|
23
29
|
const a = s.indexOf('{{', i);
|
|
24
|
-
if (a < 0) { out.push(
|
|
25
|
-
if (a > i) out.push(
|
|
26
|
-
let raw = s
|
|
30
|
+
if (a < 0) { out.push([0, s.slice(i)]); break; }
|
|
31
|
+
if (a > i) out.push([0, s.slice(i, a)]);
|
|
32
|
+
let raw = s[a + 2] === '{', p = a + 2 + raw, l = s[p] === '-', b = -1;
|
|
27
33
|
if (l) p++;
|
|
28
34
|
if (raw && triple) { b = s.indexOf('}}}', p); if (b < 0) triple = 0; }
|
|
29
35
|
if (b < 0) {
|
|
30
|
-
if (raw) { raw = !1; p = a + 2; l = s
|
|
36
|
+
if (raw) { raw = !1; p = a + 2; l = s[p] === '-'; if (l) p++; }
|
|
31
37
|
b = s.indexOf('}}', p);
|
|
32
38
|
}
|
|
33
|
-
if (b < 0) { out.push(
|
|
34
|
-
const r = b > p && s
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
t
|
|
39
|
+
if (b < 0) { out.push([0, s.slice(a)]); break; }
|
|
40
|
+
const r = b > p && s[b - 1] === '-';
|
|
41
|
+
const q = r ? b - 1 : b, whole = s.slice(p, q), body = whole.trim();
|
|
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];
|
|
44
|
+
const prev = out.at(-1);
|
|
45
|
+
if (l && prev?.[0] === 0 && prev[1]) prev[1] = prev[1].trimEnd();
|
|
38
46
|
out.push(t);
|
|
39
|
-
i =
|
|
47
|
+
i = end;
|
|
48
|
+
if (r) while (/\s/.test(s[i])) i++;
|
|
40
49
|
}
|
|
41
50
|
return out;
|
|
42
51
|
};
|
|
43
52
|
|
|
44
53
|
// Shared parser state; parsing is synchronous so this is safe.
|
|
45
54
|
// `nms` collects free variables, `fnms` the registry functions called.
|
|
46
|
-
let toks, i, fns, last, bound, nms, fnms;
|
|
55
|
+
let toks, i, fns, last, bound, nms, fnms, src, blocks;
|
|
47
56
|
|
|
48
|
-
let
|
|
57
|
+
let snap = () => Object.freeze(blocks.slice());
|
|
58
|
+
let opener = (type, t) => Object.freeze({ type, start: t[2], end: t[3] });
|
|
59
|
+
let attach = (e, context) => {
|
|
60
|
+
Object.defineProperty(e, 'blocks', { value: context, enumerable: true });
|
|
61
|
+
mark(e);
|
|
62
|
+
return e;
|
|
63
|
+
};
|
|
64
|
+
let fault = (msg, code, t, start = t?.[2] ?? src.length, end = t?.[3] ?? src.length) => {
|
|
65
|
+
const e = SyntaxError(msg);
|
|
66
|
+
e.code = code;
|
|
67
|
+
e.start = start;
|
|
68
|
+
e.end = end;
|
|
69
|
+
throw attach(e, snap());
|
|
70
|
+
};
|
|
71
|
+
let translated = (e, start, context, owns = isXprsnDiagnostic) => {
|
|
72
|
+
if (!owns(e)) throw e;
|
|
73
|
+
e.start += start;
|
|
74
|
+
e.end += start;
|
|
75
|
+
throw attach(e, context);
|
|
76
|
+
};
|
|
77
|
+
let unexpected = t => fault('Unexpected {{' + t[1] + '}}', 'SJABLOON_UNEXPECTED_TAG', t);
|
|
49
78
|
|
|
50
79
|
// Render a list of nodes against a scope.
|
|
51
80
|
let run = (nodes, v) => nodes.map(n => n(v)).join('');
|
|
52
81
|
|
|
53
82
|
// A leaf interpolation node: compile `src`, render nullish as '', apply `wrap`
|
|
54
83
|
// (`esc` for `{{ }}`, `String` for the raw `{{{ }}}` form).
|
|
55
|
-
let interp = (
|
|
56
|
-
|
|
57
|
-
// Bind `names` for a block body; returns a restore that unbinds only the names
|
|
58
|
-
// this block introduced, leaving an outer scope's bindings in place.
|
|
59
|
-
let scope = (...names) => {
|
|
60
|
-
const fresh = names.filter(n => n && !bound.has(n));
|
|
61
|
-
fresh.forEach(n => bound.add(n));
|
|
62
|
-
return () => fresh.forEach(n => bound.delete(n));
|
|
63
|
-
};
|
|
84
|
+
let interp = (t, wrap) => (e => v => wrap(e(v) ?? ''))(cp(t[1], t[6], snap()));
|
|
64
85
|
|
|
65
86
|
// Compile one expression and collect its free variables (minus the loop
|
|
66
87
|
// variables currently in scope, which belong to the template) and the registry
|
|
67
88
|
// functions it calls.
|
|
68
|
-
let cp = s => {
|
|
69
|
-
|
|
70
|
-
|
|
89
|
+
let cp = (s, start, context) => {
|
|
90
|
+
let e;
|
|
91
|
+
try {
|
|
92
|
+
e = compile(s, fns);
|
|
93
|
+
} catch (x) {
|
|
94
|
+
translated(x, start, context);
|
|
95
|
+
}
|
|
96
|
+
for (const n of e.names) bound.includes(n) || nms.add(n);
|
|
71
97
|
for (const fn of e.functions) fnms.add(fn);
|
|
72
|
-
return
|
|
98
|
+
return v => {
|
|
99
|
+
try {
|
|
100
|
+
return e(v);
|
|
101
|
+
} catch (x) {
|
|
102
|
+
translated(x, start, context, e.isDiagnostic);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
73
105
|
};
|
|
74
106
|
|
|
75
107
|
// One `#if`/`#elif` link: parse its branch, then recurse on the chain tail.
|
|
76
108
|
let branch = cond => {
|
|
77
109
|
const then = parse(['#elif', '#else', '/if']);
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
110
|
+
const tag = last[1];
|
|
111
|
+
let els = [];
|
|
112
|
+
if (tag.startsWith('#elif ')) els = [branch(cp(tag.slice(6), last[6] + 6, snap()))];
|
|
113
|
+
else if (tag === '#else') {
|
|
114
|
+
els = parse(['/if']);
|
|
115
|
+
last[1] === '/if' || unexpected(last);
|
|
116
|
+
} else if (tag !== '/if') unexpected(last);
|
|
81
117
|
return v => run(cond(v) ? then : els, v);
|
|
82
118
|
};
|
|
83
119
|
|
|
84
120
|
let parse = stops => {
|
|
85
121
|
const nodes = [];
|
|
86
122
|
for (let t; (t = toks[i++]); ) {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
123
|
+
const tag = t[1];
|
|
124
|
+
if (!t[0]) {
|
|
125
|
+
nodes.push((s => () => s)(tag));
|
|
126
|
+
} else if (t[0] === 1) {
|
|
127
|
+
nodes.push(interp(t, String));
|
|
128
|
+
} else if (stops.includes(tag.split(' ')[0])) {
|
|
129
|
+
last = t;
|
|
93
130
|
return nodes;
|
|
94
|
-
} else if (
|
|
131
|
+
} else if (tag[0] === '!') {
|
|
95
132
|
// comment
|
|
96
|
-
} else if (
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
133
|
+
} else if (tag.startsWith('#if ')) {
|
|
134
|
+
blocks.push(opener('if', t));
|
|
135
|
+
nodes.push(branch(cp(tag.slice(4), t[6] + 4, snap())));
|
|
136
|
+
blocks.pop();
|
|
137
|
+
} else if (/^#each(?:\s|$)/.test(tag)) {
|
|
138
|
+
blocks.push(opener('each', t));
|
|
139
|
+
const m = /^#each ([\s\S]+) as ((\w+)(?:\s*,\s*(\w+))?)$/.exec(tag);
|
|
140
|
+
m || fault('Bad {{' + tag + '}}', 'SJABLOON_EACH_SYNTAX', t);
|
|
141
|
+
const name = m[3], idx = m[4], at = t[6] + tag.length - m[2].length;
|
|
142
|
+
if (BLOCKED.test(name)) fault('Bad {{' + tag + '}}', 'SJABLOON_BLOCKED_BINDING', t, at, at + name.length);
|
|
143
|
+
if (idx && BLOCKED.test(idx)) {
|
|
144
|
+
const p = t[6] + tag.length - idx.length;
|
|
145
|
+
fault('Bad {{' + tag + '}}', 'SJABLOON_BLOCKED_BINDING', t, p, p + idx.length);
|
|
146
|
+
}
|
|
147
|
+
const list = cp(m[1], t[6] + 6, snap());
|
|
102
148
|
// `name`, `idx`, and `loop` are engine-bound inside the body, so
|
|
103
149
|
// exclude them from names there and restore outer bindings after.
|
|
104
|
-
const
|
|
150
|
+
const mark = bound.length;
|
|
151
|
+
bound.push(name);
|
|
152
|
+
if (idx) bound.push(idx);
|
|
153
|
+
bound.push('loop');
|
|
105
154
|
const body = parse(['#else', '/each']);
|
|
106
|
-
|
|
107
|
-
|
|
155
|
+
bound.length = mark;
|
|
156
|
+
let empty = [];
|
|
157
|
+
if (last[1] === '#else') {
|
|
158
|
+
empty = parse(['/each']);
|
|
159
|
+
last[1] === '/each' || unexpected(last);
|
|
160
|
+
} else if (last[1] !== '/each') unexpected(last);
|
|
161
|
+
blocks.pop();
|
|
108
162
|
// Child scopes inherit the parent via the prototype chain, so outer
|
|
109
163
|
// variables stay visible inside the loop body. `@` re-points to the
|
|
110
164
|
// current item at each level, `$` (root) rides the chain, and `loop`
|
|
111
165
|
// carries the iteration metadata (index/first/last/length).
|
|
112
166
|
nodes.push(v => {
|
|
113
|
-
const
|
|
167
|
+
const lv = list(v), arr = Array.isArray(lv);
|
|
168
|
+
const ps = arr ? lv.slice() : lv && typeof lv === 'object' ? Object.keys(lv).map(k => [lv[k], k]) : [];
|
|
114
169
|
if (!ps.length) return run(empty, v);
|
|
115
|
-
return ps.map((
|
|
170
|
+
return ps.map((x, j) => {
|
|
171
|
+
const item = arr ? x : x[0], key = arr ? j : x[1];
|
|
116
172
|
const s = Object.create(v);
|
|
117
173
|
s[name] = item;
|
|
118
174
|
if (idx) s[idx] = key;
|
|
@@ -121,13 +177,15 @@ let parse = stops => {
|
|
|
121
177
|
return run(body, s);
|
|
122
178
|
}).join('');
|
|
123
179
|
});
|
|
124
|
-
} else if (
|
|
125
|
-
|
|
180
|
+
} else if (/^#(?:if|elif|else)(?:\s|$)/.test(tag) || tag[0] === '/') {
|
|
181
|
+
unexpected(t);
|
|
182
|
+
} else if (tag[0] === '#') {
|
|
183
|
+
fault('Unknown {{' + tag + '}}', 'SJABLOON_UNKNOWN_BLOCK', t);
|
|
126
184
|
} else {
|
|
127
|
-
nodes.push(interp(t
|
|
185
|
+
nodes.push(interp(t, esc));
|
|
128
186
|
}
|
|
129
187
|
}
|
|
130
|
-
stops.length &&
|
|
188
|
+
stops.length && fault('Missing {{' + stops[stops.length - 1] + '}}', 'SJABLOON_UNCLOSED_BLOCK');
|
|
131
189
|
return nodes;
|
|
132
190
|
};
|
|
133
191
|
|
|
@@ -158,15 +216,12 @@ export function template(str, funcs) {
|
|
|
158
216
|
fns = funcs;
|
|
159
217
|
// `$` (root) and `@` (current item) are engine-bound anchors, always in
|
|
160
218
|
// scope, so they never count as caller-supplied `names`.
|
|
161
|
-
bound =
|
|
219
|
+
bound = ['$', '@'];
|
|
162
220
|
nms = new Set();
|
|
163
221
|
fnms = new Set();
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
toks
|
|
167
|
-
if (t.l && toks[k - 1]?.text) toks[k - 1].text = toks[k - 1].text.trimEnd();
|
|
168
|
-
if (t.r && toks[k + 1]?.text) toks[k + 1].text = toks[k + 1].text.trimStart();
|
|
169
|
-
});
|
|
222
|
+
src = String(str);
|
|
223
|
+
blocks = [];
|
|
224
|
+
toks = lex(src);
|
|
170
225
|
i = 0;
|
|
171
226
|
const nodes = parse([]);
|
|
172
227
|
// Wrap the values in a root scope carrying the anchors, without mutating
|