janja 3.0.0 → 4.0.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/dist/index.cjs +99 -49
- package/dist/index.d.ts +9 -2
- package/dist/index.esm.js +99 -50
- package/dist/index.js +99 -49
- package/dist/index.min.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1580,6 +1580,10 @@ class Parser extends Tokenizer {
|
|
|
1580
1580
|
}
|
|
1581
1581
|
|
|
1582
1582
|
const fingerprints = new WeakMap();
|
|
1583
|
+
// How deep includes may nest while rendering. Only templates that include
|
|
1584
|
+
// themselves get anywhere near it; the limit turns a cycle that never ends
|
|
1585
|
+
// into an error instead of a stack overflow.
|
|
1586
|
+
const MAX_INCLUDE_DEPTH = 100;
|
|
1583
1587
|
// Directives whose body is still the template's own top-level output
|
|
1584
1588
|
const transparent = new Set(['IF', 'FOR']);
|
|
1585
1589
|
// The template itself is the key: one string that is hashed once, and two
|
|
@@ -1720,9 +1724,9 @@ class Compiler extends Context {
|
|
|
1720
1724
|
await this.parseTemplates();
|
|
1721
1725
|
if (this.isRoot) {
|
|
1722
1726
|
if (this.partials.size) {
|
|
1723
|
-
this.pushRaw(null, 'const p={');
|
|
1727
|
+
this.pushRaw(null, 'let d_=0;', 'const p={');
|
|
1724
1728
|
for (const [path, code] of this.partials) {
|
|
1725
|
-
this.pushRaw(null, `${JSON.stringify(path)}:async()=>{`, code, '},');
|
|
1729
|
+
this.pushRaw(null, `${JSON.stringify(path)}:async()=>{`, `if(d_>=${MAX_INCLUDE_DEPTH})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(path)} are nested too deeply`)});`, 'd_++;', 'try{return await(async()=>{', code, '})();}finally{d_--;}', '},');
|
|
1726
1730
|
}
|
|
1727
1731
|
this.pushRaw(null, '};');
|
|
1728
1732
|
}
|
|
@@ -1799,6 +1803,10 @@ class Compiler extends Context {
|
|
|
1799
1803
|
throw new CompileError(`Failed to load template from "${path}"`, this.template, node.loc);
|
|
1800
1804
|
}
|
|
1801
1805
|
this.sources.set(path, template ?? '');
|
|
1806
|
+
// Reserved before compiling, so that a template that includes itself,
|
|
1807
|
+
// directly or through others, refers to the partial being compiled
|
|
1808
|
+
// instead of compiling it again without end
|
|
1809
|
+
this.partials.set(path, '');
|
|
1802
1810
|
if (template) {
|
|
1803
1811
|
await this.compilePartial(path, node, template);
|
|
1804
1812
|
}
|
|
@@ -1888,37 +1896,21 @@ class Compiler extends Context {
|
|
|
1888
1896
|
}
|
|
1889
1897
|
}
|
|
1890
1898
|
|
|
1899
|
+
const special = /[&<>"']/;
|
|
1900
|
+
const specials = /[&<>"']/g;
|
|
1901
|
+
const entities = {
|
|
1902
|
+
'&': '&',
|
|
1903
|
+
'"': '"',
|
|
1904
|
+
"'": ''',
|
|
1905
|
+
'<': '<',
|
|
1906
|
+
'>': '>',
|
|
1907
|
+
};
|
|
1908
|
+
const entity = (char) => entities[char];
|
|
1891
1909
|
function escape(v) {
|
|
1892
1910
|
const str = typeof v === 'string' ? v : `${v}`;
|
|
1893
|
-
//
|
|
1894
|
-
//
|
|
1895
|
-
|
|
1896
|
-
let last = 0;
|
|
1897
|
-
for (let i = 0; i < str.length; i++) {
|
|
1898
|
-
let entity;
|
|
1899
|
-
switch (str.charCodeAt(i)) {
|
|
1900
|
-
case 38:
|
|
1901
|
-
entity = '&';
|
|
1902
|
-
break;
|
|
1903
|
-
case 34:
|
|
1904
|
-
entity = '"';
|
|
1905
|
-
break;
|
|
1906
|
-
case 39:
|
|
1907
|
-
entity = ''';
|
|
1908
|
-
break;
|
|
1909
|
-
case 60:
|
|
1910
|
-
entity = '<';
|
|
1911
|
-
break;
|
|
1912
|
-
case 62:
|
|
1913
|
-
entity = '>';
|
|
1914
|
-
break;
|
|
1915
|
-
default:
|
|
1916
|
-
continue;
|
|
1917
|
-
}
|
|
1918
|
-
result += str.slice(last, i) + entity;
|
|
1919
|
-
last = i + 1;
|
|
1920
|
-
}
|
|
1921
|
-
return last === 0 ? str : result + str.slice(last);
|
|
1911
|
+
// Most values contain nothing to escape; they are returned as they are,
|
|
1912
|
+
// without allocating
|
|
1913
|
+
return special.test(str) ? str.replace(specials, entity) : str;
|
|
1922
1914
|
}
|
|
1923
1915
|
|
|
1924
1916
|
class Safe extends String {
|
|
@@ -2458,6 +2450,10 @@ const expTokenOperators$1 = {
|
|
|
2458
2450
|
IF: '',
|
|
2459
2451
|
ELSE: '',
|
|
2460
2452
|
};
|
|
2453
|
+
// Names every object inherits (`toString`, `valueOf`, ...). The context is a
|
|
2454
|
+
// plain object, so these are only read from it when it has them itself;
|
|
2455
|
+
// otherwise a name nobody defined would resolve to a built-in function.
|
|
2456
|
+
const inherited = new Set(Object.getOwnPropertyNames(Object.prototype));
|
|
2461
2457
|
class ExpCompiler {
|
|
2462
2458
|
constructor() {
|
|
2463
2459
|
Object.defineProperty(this, "context", {
|
|
@@ -2520,15 +2516,38 @@ class ExpCompiler {
|
|
|
2520
2516
|
return `!${this.compileExp(argument)}`;
|
|
2521
2517
|
}
|
|
2522
2518
|
compileId({ value, path, args }) {
|
|
2523
|
-
let s =
|
|
2519
|
+
let s = inherited.has(value)
|
|
2520
|
+
? `(Object.hasOwn(${this.context},"${value}")?${this.context}.${value}:undefined)`
|
|
2521
|
+
: `${this.context}.${value}`;
|
|
2524
2522
|
if (path) {
|
|
2525
2523
|
s += path.map((p) => `.${p.value}`).join('');
|
|
2526
2524
|
}
|
|
2527
2525
|
if (args) {
|
|
2528
|
-
s += `(${
|
|
2526
|
+
s += `(${this.compileArgs(args).join(',')})`;
|
|
2529
2527
|
}
|
|
2530
2528
|
return s;
|
|
2531
2529
|
}
|
|
2530
|
+
/**
|
|
2531
|
+
* Positional arguments in the order they are written, followed by one
|
|
2532
|
+
* object holding the named ones: `f(1, a=2, b=3)` calls `f(1, {a:2,b:3})`.
|
|
2533
|
+
*/
|
|
2534
|
+
compileArgs(args) {
|
|
2535
|
+
const positional = [];
|
|
2536
|
+
const named = [];
|
|
2537
|
+
for (const arg of args) {
|
|
2538
|
+
if (arg.type === 'ASSIGN') {
|
|
2539
|
+
const { left, right } = arg;
|
|
2540
|
+
named.push(`${left.value}:${this.compileExp(right)}`);
|
|
2541
|
+
}
|
|
2542
|
+
else {
|
|
2543
|
+
positional.push(this.compileExp(arg));
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
if (named.length) {
|
|
2547
|
+
positional.push(`{${named.join(',')}}`);
|
|
2548
|
+
}
|
|
2549
|
+
return positional;
|
|
2550
|
+
}
|
|
2532
2551
|
compileLit({ value }) {
|
|
2533
2552
|
if (value === undefined) {
|
|
2534
2553
|
return 'undefined';
|
|
@@ -2545,7 +2564,7 @@ class ExpCompiler {
|
|
|
2545
2564
|
}
|
|
2546
2565
|
compilePipe({ left, right }) {
|
|
2547
2566
|
const { value: name, args = [] } = right;
|
|
2548
|
-
const call = `(${this.filters}.${name}||${UNKNOWN_FILTER}("${name}")).call(${[this.context, this.compileExp(left), ...
|
|
2567
|
+
const call = `(${this.filters}.${name}||${UNKNOWN_FILTER}("${name}")).call(${[this.context, this.compileExp(left), ...this.compileArgs(args)].join(',')})`;
|
|
2549
2568
|
// Awaiting a plain value still costs a trip through the microtask queue,
|
|
2550
2569
|
// so only promises returned by async filters are awaited
|
|
2551
2570
|
return `(${RESULT}=${call},${RESULT} instanceof Promise?await ${RESULT}:${RESULT})`;
|
|
@@ -2570,9 +2589,9 @@ class ExpCompiler {
|
|
|
2570
2589
|
}
|
|
2571
2590
|
|
|
2572
2591
|
async function compileCall({ val, body, loc }, compiler) {
|
|
2573
|
-
compiler.pushRaw(loc, `await ${new ExpCompiler().compile(val, compiler.context)}(async()=>{
|
|
2592
|
+
compiler.pushRaw(loc, `s+=await ${new ExpCompiler().compile(val, compiler.context)}(async()=>{`, 'let s="";');
|
|
2574
2593
|
await compiler.compileNodes(body);
|
|
2575
|
-
compiler.pushRaw(null, '});');
|
|
2594
|
+
compiler.pushRaw(null, 'return s;', '})??"";');
|
|
2576
2595
|
}
|
|
2577
2596
|
const compilers$c = {
|
|
2578
2597
|
CALL: compileCall,
|
|
@@ -2769,8 +2788,14 @@ function hasAssignment(exp, seen = new Set()) {
|
|
|
2769
2788
|
return false;
|
|
2770
2789
|
}
|
|
2771
2790
|
seen.add(exp);
|
|
2772
|
-
|
|
2773
|
-
|
|
2791
|
+
if (exp.type === 'ASSIGN') {
|
|
2792
|
+
return true;
|
|
2793
|
+
}
|
|
2794
|
+
return Object.entries(exp).some(([key, value]) =>
|
|
2795
|
+
// `f(name=value)` passes a named argument; only its value matters
|
|
2796
|
+
key === 'args' && Array.isArray(value)
|
|
2797
|
+
? value.some((arg) => hasAssignment(arg.type === 'ASSIGN' ? arg.right : arg, seen))
|
|
2798
|
+
: hasAssignment(value, seen));
|
|
2774
2799
|
}
|
|
2775
2800
|
/**
|
|
2776
2801
|
* Whether nothing in `nodes` can write to, or keep a reference to, the
|
|
@@ -3345,15 +3370,18 @@ const plugin$7 = {
|
|
|
3345
3370
|
async function compileMacro({ val: { value, args }, loc, body }, compiler) {
|
|
3346
3371
|
const { context } = compiler;
|
|
3347
3372
|
const expCompiler = new ExpCompiler();
|
|
3348
|
-
compiler.pushRaw(loc,
|
|
3373
|
+
compiler.pushRaw(loc,
|
|
3374
|
+
// A macro collects its own output and returns it, so that it ends up
|
|
3375
|
+
// where the macro is called rather than where it was defined
|
|
3376
|
+
`${context}.${value}=(...a_)=>async(_c)=>{`, 'let s="";', `const ${compiler.in()}={`, `...${context},`, ...(args ?? []).map((el, i) => el.type === 'ASSIGN'
|
|
3349
3377
|
? `${el.left.value}:a_[${i}]===undefined?${expCompiler.compile(el.right)}:a_[${i}],`
|
|
3350
3378
|
: `${el.value}:a_[${i}],`), '};');
|
|
3351
3379
|
await compiler.compileNodes(body);
|
|
3352
3380
|
compiler.out();
|
|
3353
|
-
compiler.pushRaw(null, '};');
|
|
3381
|
+
compiler.pushRaw(null, 'return s;', '};');
|
|
3354
3382
|
}
|
|
3355
3383
|
function compileCaller({ loc }, compiler) {
|
|
3356
|
-
compiler.pushRaw(loc, 'await _c?.();');
|
|
3384
|
+
compiler.pushRaw(loc, 's+=await _c?.()??"";');
|
|
3357
3385
|
}
|
|
3358
3386
|
const compilers$6 = {
|
|
3359
3387
|
MACRO: compileMacro,
|
|
@@ -4068,6 +4096,14 @@ class Renderer {
|
|
|
4068
4096
|
writable: true,
|
|
4069
4097
|
value: void 0
|
|
4070
4098
|
});
|
|
4099
|
+
// Compilations in progress, so that renders of the same template that
|
|
4100
|
+
// start together share one instead of each compiling it
|
|
4101
|
+
Object.defineProperty(this, "compiling", {
|
|
4102
|
+
enumerable: true,
|
|
4103
|
+
configurable: true,
|
|
4104
|
+
writable: true,
|
|
4105
|
+
value: new Map()
|
|
4106
|
+
});
|
|
4071
4107
|
this.options = mergeOptions(renderOptions, {
|
|
4072
4108
|
filters,
|
|
4073
4109
|
plugins,
|
|
@@ -4076,6 +4112,11 @@ class Renderer {
|
|
|
4076
4112
|
const escapeValue = this.options.security?.deepEscape ? deepEscape : escape;
|
|
4077
4113
|
const { autoEscape } = this.options;
|
|
4078
4114
|
this.escape = (v) => {
|
|
4115
|
+
// Strings are by far the most common value, so they are handled before
|
|
4116
|
+
// anything else is checked
|
|
4117
|
+
if (typeof v === 'string') {
|
|
4118
|
+
return autoEscape ? escape(v) : v;
|
|
4119
|
+
}
|
|
4079
4120
|
if (v === null || v === undefined) {
|
|
4080
4121
|
return '';
|
|
4081
4122
|
}
|
|
@@ -4110,13 +4151,13 @@ class Renderer {
|
|
|
4110
4151
|
return '';
|
|
4111
4152
|
}
|
|
4112
4153
|
}
|
|
4113
|
-
|
|
4154
|
+
let compiler;
|
|
4114
4155
|
try {
|
|
4115
|
-
await
|
|
4156
|
+
compiler = await this.compile(template);
|
|
4116
4157
|
return await this.run(compiler.script, globals);
|
|
4117
4158
|
}
|
|
4118
4159
|
catch (error) {
|
|
4119
|
-
this.options.debug(this.wrapError(error, template, compiler));
|
|
4160
|
+
this.options.debug(this.wrapError(error, template, compiler ?? new SourceMap()));
|
|
4120
4161
|
}
|
|
4121
4162
|
return '';
|
|
4122
4163
|
}
|
|
@@ -4161,12 +4202,12 @@ class Renderer {
|
|
|
4161
4202
|
});
|
|
4162
4203
|
}
|
|
4163
4204
|
};
|
|
4164
|
-
|
|
4205
|
+
let compiler;
|
|
4165
4206
|
// Not awaited: `start` returns right away and chunks are enqueued as
|
|
4166
4207
|
// they are produced
|
|
4167
4208
|
void (async () => {
|
|
4168
4209
|
try {
|
|
4169
|
-
await
|
|
4210
|
+
compiler = await this.compile(template, true);
|
|
4170
4211
|
const rest = await this.run(compiler.script, globals, write);
|
|
4171
4212
|
if (rest && !cancelled) {
|
|
4172
4213
|
controller.enqueue(rest);
|
|
@@ -4178,7 +4219,7 @@ class Renderer {
|
|
|
4178
4219
|
return;
|
|
4179
4220
|
}
|
|
4180
4221
|
try {
|
|
4181
|
-
this.options.debug(this.wrapError(error, template, compiler));
|
|
4222
|
+
this.options.debug(this.wrapError(error, template, compiler ?? new SourceMap()));
|
|
4182
4223
|
controller.close();
|
|
4183
4224
|
}
|
|
4184
4225
|
catch (reported) {
|
|
@@ -4197,8 +4238,16 @@ class Renderer {
|
|
|
4197
4238
|
},
|
|
4198
4239
|
});
|
|
4199
4240
|
}
|
|
4200
|
-
|
|
4201
|
-
|
|
4241
|
+
compile(template, stream = false) {
|
|
4242
|
+
const key = templateCacheKey(template, stream);
|
|
4243
|
+
let compiling = this.compiling.get(key);
|
|
4244
|
+
if (!compiling) {
|
|
4245
|
+
compiling = new Compiler(this.options, this.cache, this.options.cache?.revalidate ?? true, stream)
|
|
4246
|
+
.compile(template)
|
|
4247
|
+
.finally(() => this.compiling.delete(key));
|
|
4248
|
+
this.compiling.set(key, compiling);
|
|
4249
|
+
}
|
|
4250
|
+
return compiling;
|
|
4202
4251
|
}
|
|
4203
4252
|
wrapError(error, template, sourceMap) {
|
|
4204
4253
|
if (error?.name === 'CompileError') {
|
|
@@ -5433,6 +5482,7 @@ exports.ExpError = ExpError;
|
|
|
5433
5482
|
exports.ExpParser = ExpParser;
|
|
5434
5483
|
exports.ExpTokenizer = ExpTokenizer;
|
|
5435
5484
|
exports.I18n = I18n;
|
|
5485
|
+
exports.MAX_INCLUDE_DEPTH = MAX_INCLUDE_DEPTH;
|
|
5436
5486
|
exports.MixinRegistry = MixinRegistry;
|
|
5437
5487
|
exports.Parser = Parser;
|
|
5438
5488
|
exports.RenderError = RenderError;
|
package/dist/index.d.ts
CHANGED
|
@@ -172,6 +172,7 @@ interface CompiledTemplate {
|
|
|
172
172
|
sources: Map<string, string>;
|
|
173
173
|
fingerprint: string;
|
|
174
174
|
}
|
|
175
|
+
declare const MAX_INCLUDE_DEPTH = 100;
|
|
175
176
|
declare function templateCacheKey(template: string, stream?: boolean): string;
|
|
176
177
|
declare function optionsFingerprint(options: Required<CompilerOptions>): string;
|
|
177
178
|
declare class Compiler extends Context {
|
|
@@ -599,6 +600,7 @@ declare class Renderer {
|
|
|
599
600
|
private sandbox?;
|
|
600
601
|
private filters;
|
|
601
602
|
private escape;
|
|
603
|
+
private compiling;
|
|
602
604
|
constructor(options?: RendererOptions);
|
|
603
605
|
render(template: string, globals: ObjectType): Promise<string>;
|
|
604
606
|
/**
|
|
@@ -616,7 +618,7 @@ declare class Renderer {
|
|
|
616
618
|
* parts of the template and between the iterations of top-level loops.
|
|
617
619
|
*/
|
|
618
620
|
renderStream(template: string, globals?: ObjectType): ReadableStream<string>;
|
|
619
|
-
private
|
|
621
|
+
private compile;
|
|
620
622
|
private wrapError;
|
|
621
623
|
private run;
|
|
622
624
|
renderFile(filepath: string, globals: ObjectType): Promise<string>;
|
|
@@ -641,6 +643,11 @@ declare class ExpCompiler {
|
|
|
641
643
|
private compileExp;
|
|
642
644
|
private compileNot;
|
|
643
645
|
private compileId;
|
|
646
|
+
/**
|
|
647
|
+
* Positional arguments in the order they are written, followed by one
|
|
648
|
+
* object holding the named ones: `f(1, a=2, b=3)` calls `f(1, {a:2,b:3})`.
|
|
649
|
+
*/
|
|
650
|
+
private compileArgs;
|
|
644
651
|
private compileLit;
|
|
645
652
|
private compileSeq;
|
|
646
653
|
private compilePipe;
|
|
@@ -1021,5 +1028,5 @@ declare function renderCompiled(script: Script, data?: ObjectType, options?: Ren
|
|
|
1021
1028
|
*/
|
|
1022
1029
|
declare function renderStream(template: string, data?: ObjectType, options?: RendererOptions): ReadableStream<string>;
|
|
1023
1030
|
|
|
1024
|
-
export { CompileError, Compiler, ErrorRecovery, ExpCompiler, ExpError, ExpParser, ExpTokenizer, I18n, MixinRegistry, Parser, RenderError, Renderer, RootNode, Safe, TemplatePipeline, TemplateValidator, TokenType, Tokenizer, Traversal, analyzeTemplate, applyMixin, applyMixins, applyWhitespaceControl, baseOptions, compilerOptions, composeLayout, composeTemplates, composeTemplatesWithData, composeWithSlots, createErrorRecovery, createFileLoader, createMixin, defaultErrorHandler, defaultWhitespaceOptions, defineFilters, definePlugin, expTokenTypes, extendTemplateWithMixin, filters, formatTemplate, generateDeclarations, generateSourceMap, getWhitespaceCompilerOptions, getWhitespaceRendererOptions, globalMixinRegistry, i18n, isForbiddenIdentifier, mergeOptions, mergeWhitespaceOptions, optionsFingerprint, parserOptions, precompile, precompileTemplate, render, renderCompiled, renderFile, renderOptions, renderStream, templateCacheKey, validateTemplate };
|
|
1031
|
+
export { CompileError, Compiler, ErrorRecovery, ExpCompiler, ExpError, ExpParser, ExpTokenizer, I18n, MAX_INCLUDE_DEPTH, MixinRegistry, Parser, RenderError, Renderer, RootNode, Safe, TemplatePipeline, TemplateValidator, TokenType, Tokenizer, Traversal, analyzeTemplate, applyMixin, applyMixins, applyWhitespaceControl, baseOptions, compilerOptions, composeLayout, composeTemplates, composeTemplatesWithData, composeWithSlots, createErrorRecovery, createFileLoader, createMixin, defaultErrorHandler, defaultWhitespaceOptions, defineFilters, definePlugin, expTokenTypes, extendTemplateWithMixin, filters, formatTemplate, generateDeclarations, generateSourceMap, getWhitespaceCompilerOptions, getWhitespaceRendererOptions, globalMixinRegistry, i18n, isForbiddenIdentifier, mergeOptions, mergeWhitespaceOptions, optionsFingerprint, parserOptions, precompile, precompileTemplate, render, renderCompiled, renderFile, renderOptions, renderStream, templateCacheKey, validateTemplate };
|
|
1025
1032
|
export type { BaseOptions, BinaryExp, BinaryExpTokenType, BinaryExpType, CacheOptions, Checker, CommentToken, CompiledTemplate, CompilerFn, CompilerMap, CompilerOptions, CompositionOptions, DirectiveExpression, DirectiveToken, ErrorContext, ErrorRecoveryOptions, Exp, ExpBase, ExpToken, ExpTokenType, ExpType, FileLoaderOptions, Filter, Filters, FormatOptions, FormatterFn, FormatterMap, FormatterOptions, I18nOptions, IdExp, IfExp, LitExp, Loc, MaybePromise, MixinDefinition, MixinOptions, NotExp, ObjectType, OutputToken, ParserFn, ParserMap, ParserOptions, Plugin, PluralRules, Pos, PrecompileOptions, PrecompileResult, Primitive, RendererOptions, Script, SeqExp, SourceMapOptions, SourceMapV3, Strip, SyntaxNode, TemplateAnalysis, TernaryExpTokenType, TernaryExpType, TextToken, Token, TokenBase, TranslationDict, UnaryExpTokenType, UnaryExpType, ValidationError, ValidationResult, WhitespaceOptions };
|
package/dist/index.esm.js
CHANGED
|
@@ -1578,6 +1578,10 @@ class Parser extends Tokenizer {
|
|
|
1578
1578
|
}
|
|
1579
1579
|
|
|
1580
1580
|
const fingerprints = new WeakMap();
|
|
1581
|
+
// How deep includes may nest while rendering. Only templates that include
|
|
1582
|
+
// themselves get anywhere near it; the limit turns a cycle that never ends
|
|
1583
|
+
// into an error instead of a stack overflow.
|
|
1584
|
+
const MAX_INCLUDE_DEPTH = 100;
|
|
1581
1585
|
// Directives whose body is still the template's own top-level output
|
|
1582
1586
|
const transparent = new Set(['IF', 'FOR']);
|
|
1583
1587
|
// The template itself is the key: one string that is hashed once, and two
|
|
@@ -1718,9 +1722,9 @@ class Compiler extends Context {
|
|
|
1718
1722
|
await this.parseTemplates();
|
|
1719
1723
|
if (this.isRoot) {
|
|
1720
1724
|
if (this.partials.size) {
|
|
1721
|
-
this.pushRaw(null, 'const p={');
|
|
1725
|
+
this.pushRaw(null, 'let d_=0;', 'const p={');
|
|
1722
1726
|
for (const [path, code] of this.partials) {
|
|
1723
|
-
this.pushRaw(null, `${JSON.stringify(path)}:async()=>{`, code, '},');
|
|
1727
|
+
this.pushRaw(null, `${JSON.stringify(path)}:async()=>{`, `if(d_>=${MAX_INCLUDE_DEPTH})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(path)} are nested too deeply`)});`, 'd_++;', 'try{return await(async()=>{', code, '})();}finally{d_--;}', '},');
|
|
1724
1728
|
}
|
|
1725
1729
|
this.pushRaw(null, '};');
|
|
1726
1730
|
}
|
|
@@ -1797,6 +1801,10 @@ class Compiler extends Context {
|
|
|
1797
1801
|
throw new CompileError(`Failed to load template from "${path}"`, this.template, node.loc);
|
|
1798
1802
|
}
|
|
1799
1803
|
this.sources.set(path, template ?? '');
|
|
1804
|
+
// Reserved before compiling, so that a template that includes itself,
|
|
1805
|
+
// directly or through others, refers to the partial being compiled
|
|
1806
|
+
// instead of compiling it again without end
|
|
1807
|
+
this.partials.set(path, '');
|
|
1800
1808
|
if (template) {
|
|
1801
1809
|
await this.compilePartial(path, node, template);
|
|
1802
1810
|
}
|
|
@@ -1886,37 +1894,21 @@ class Compiler extends Context {
|
|
|
1886
1894
|
}
|
|
1887
1895
|
}
|
|
1888
1896
|
|
|
1897
|
+
const special = /[&<>"']/;
|
|
1898
|
+
const specials = /[&<>"']/g;
|
|
1899
|
+
const entities = {
|
|
1900
|
+
'&': '&',
|
|
1901
|
+
'"': '"',
|
|
1902
|
+
"'": ''',
|
|
1903
|
+
'<': '<',
|
|
1904
|
+
'>': '>',
|
|
1905
|
+
};
|
|
1906
|
+
const entity = (char) => entities[char];
|
|
1889
1907
|
function escape(v) {
|
|
1890
1908
|
const str = typeof v === 'string' ? v : `${v}`;
|
|
1891
|
-
//
|
|
1892
|
-
//
|
|
1893
|
-
|
|
1894
|
-
let last = 0;
|
|
1895
|
-
for (let i = 0; i < str.length; i++) {
|
|
1896
|
-
let entity;
|
|
1897
|
-
switch (str.charCodeAt(i)) {
|
|
1898
|
-
case 38:
|
|
1899
|
-
entity = '&';
|
|
1900
|
-
break;
|
|
1901
|
-
case 34:
|
|
1902
|
-
entity = '"';
|
|
1903
|
-
break;
|
|
1904
|
-
case 39:
|
|
1905
|
-
entity = ''';
|
|
1906
|
-
break;
|
|
1907
|
-
case 60:
|
|
1908
|
-
entity = '<';
|
|
1909
|
-
break;
|
|
1910
|
-
case 62:
|
|
1911
|
-
entity = '>';
|
|
1912
|
-
break;
|
|
1913
|
-
default:
|
|
1914
|
-
continue;
|
|
1915
|
-
}
|
|
1916
|
-
result += str.slice(last, i) + entity;
|
|
1917
|
-
last = i + 1;
|
|
1918
|
-
}
|
|
1919
|
-
return last === 0 ? str : result + str.slice(last);
|
|
1909
|
+
// Most values contain nothing to escape; they are returned as they are,
|
|
1910
|
+
// without allocating
|
|
1911
|
+
return special.test(str) ? str.replace(specials, entity) : str;
|
|
1920
1912
|
}
|
|
1921
1913
|
|
|
1922
1914
|
class Safe extends String {
|
|
@@ -2456,6 +2448,10 @@ const expTokenOperators$1 = {
|
|
|
2456
2448
|
IF: '',
|
|
2457
2449
|
ELSE: '',
|
|
2458
2450
|
};
|
|
2451
|
+
// Names every object inherits (`toString`, `valueOf`, ...). The context is a
|
|
2452
|
+
// plain object, so these are only read from it when it has them itself;
|
|
2453
|
+
// otherwise a name nobody defined would resolve to a built-in function.
|
|
2454
|
+
const inherited = new Set(Object.getOwnPropertyNames(Object.prototype));
|
|
2459
2455
|
class ExpCompiler {
|
|
2460
2456
|
constructor() {
|
|
2461
2457
|
Object.defineProperty(this, "context", {
|
|
@@ -2518,15 +2514,38 @@ class ExpCompiler {
|
|
|
2518
2514
|
return `!${this.compileExp(argument)}`;
|
|
2519
2515
|
}
|
|
2520
2516
|
compileId({ value, path, args }) {
|
|
2521
|
-
let s =
|
|
2517
|
+
let s = inherited.has(value)
|
|
2518
|
+
? `(Object.hasOwn(${this.context},"${value}")?${this.context}.${value}:undefined)`
|
|
2519
|
+
: `${this.context}.${value}`;
|
|
2522
2520
|
if (path) {
|
|
2523
2521
|
s += path.map((p) => `.${p.value}`).join('');
|
|
2524
2522
|
}
|
|
2525
2523
|
if (args) {
|
|
2526
|
-
s += `(${
|
|
2524
|
+
s += `(${this.compileArgs(args).join(',')})`;
|
|
2527
2525
|
}
|
|
2528
2526
|
return s;
|
|
2529
2527
|
}
|
|
2528
|
+
/**
|
|
2529
|
+
* Positional arguments in the order they are written, followed by one
|
|
2530
|
+
* object holding the named ones: `f(1, a=2, b=3)` calls `f(1, {a:2,b:3})`.
|
|
2531
|
+
*/
|
|
2532
|
+
compileArgs(args) {
|
|
2533
|
+
const positional = [];
|
|
2534
|
+
const named = [];
|
|
2535
|
+
for (const arg of args) {
|
|
2536
|
+
if (arg.type === 'ASSIGN') {
|
|
2537
|
+
const { left, right } = arg;
|
|
2538
|
+
named.push(`${left.value}:${this.compileExp(right)}`);
|
|
2539
|
+
}
|
|
2540
|
+
else {
|
|
2541
|
+
positional.push(this.compileExp(arg));
|
|
2542
|
+
}
|
|
2543
|
+
}
|
|
2544
|
+
if (named.length) {
|
|
2545
|
+
positional.push(`{${named.join(',')}}`);
|
|
2546
|
+
}
|
|
2547
|
+
return positional;
|
|
2548
|
+
}
|
|
2530
2549
|
compileLit({ value }) {
|
|
2531
2550
|
if (value === undefined) {
|
|
2532
2551
|
return 'undefined';
|
|
@@ -2543,7 +2562,7 @@ class ExpCompiler {
|
|
|
2543
2562
|
}
|
|
2544
2563
|
compilePipe({ left, right }) {
|
|
2545
2564
|
const { value: name, args = [] } = right;
|
|
2546
|
-
const call = `(${this.filters}.${name}||${UNKNOWN_FILTER}("${name}")).call(${[this.context, this.compileExp(left), ...
|
|
2565
|
+
const call = `(${this.filters}.${name}||${UNKNOWN_FILTER}("${name}")).call(${[this.context, this.compileExp(left), ...this.compileArgs(args)].join(',')})`;
|
|
2547
2566
|
// Awaiting a plain value still costs a trip through the microtask queue,
|
|
2548
2567
|
// so only promises returned by async filters are awaited
|
|
2549
2568
|
return `(${RESULT}=${call},${RESULT} instanceof Promise?await ${RESULT}:${RESULT})`;
|
|
@@ -2568,9 +2587,9 @@ class ExpCompiler {
|
|
|
2568
2587
|
}
|
|
2569
2588
|
|
|
2570
2589
|
async function compileCall({ val, body, loc }, compiler) {
|
|
2571
|
-
compiler.pushRaw(loc, `await ${new ExpCompiler().compile(val, compiler.context)}(async()=>{
|
|
2590
|
+
compiler.pushRaw(loc, `s+=await ${new ExpCompiler().compile(val, compiler.context)}(async()=>{`, 'let s="";');
|
|
2572
2591
|
await compiler.compileNodes(body);
|
|
2573
|
-
compiler.pushRaw(null, '});');
|
|
2592
|
+
compiler.pushRaw(null, 'return s;', '})??"";');
|
|
2574
2593
|
}
|
|
2575
2594
|
const compilers$c = {
|
|
2576
2595
|
CALL: compileCall,
|
|
@@ -2767,8 +2786,14 @@ function hasAssignment(exp, seen = new Set()) {
|
|
|
2767
2786
|
return false;
|
|
2768
2787
|
}
|
|
2769
2788
|
seen.add(exp);
|
|
2770
|
-
|
|
2771
|
-
|
|
2789
|
+
if (exp.type === 'ASSIGN') {
|
|
2790
|
+
return true;
|
|
2791
|
+
}
|
|
2792
|
+
return Object.entries(exp).some(([key, value]) =>
|
|
2793
|
+
// `f(name=value)` passes a named argument; only its value matters
|
|
2794
|
+
key === 'args' && Array.isArray(value)
|
|
2795
|
+
? value.some((arg) => hasAssignment(arg.type === 'ASSIGN' ? arg.right : arg, seen))
|
|
2796
|
+
: hasAssignment(value, seen));
|
|
2772
2797
|
}
|
|
2773
2798
|
/**
|
|
2774
2799
|
* Whether nothing in `nodes` can write to, or keep a reference to, the
|
|
@@ -3343,15 +3368,18 @@ const plugin$7 = {
|
|
|
3343
3368
|
async function compileMacro({ val: { value, args }, loc, body }, compiler) {
|
|
3344
3369
|
const { context } = compiler;
|
|
3345
3370
|
const expCompiler = new ExpCompiler();
|
|
3346
|
-
compiler.pushRaw(loc,
|
|
3371
|
+
compiler.pushRaw(loc,
|
|
3372
|
+
// A macro collects its own output and returns it, so that it ends up
|
|
3373
|
+
// where the macro is called rather than where it was defined
|
|
3374
|
+
`${context}.${value}=(...a_)=>async(_c)=>{`, 'let s="";', `const ${compiler.in()}={`, `...${context},`, ...(args ?? []).map((el, i) => el.type === 'ASSIGN'
|
|
3347
3375
|
? `${el.left.value}:a_[${i}]===undefined?${expCompiler.compile(el.right)}:a_[${i}],`
|
|
3348
3376
|
: `${el.value}:a_[${i}],`), '};');
|
|
3349
3377
|
await compiler.compileNodes(body);
|
|
3350
3378
|
compiler.out();
|
|
3351
|
-
compiler.pushRaw(null, '};');
|
|
3379
|
+
compiler.pushRaw(null, 'return s;', '};');
|
|
3352
3380
|
}
|
|
3353
3381
|
function compileCaller({ loc }, compiler) {
|
|
3354
|
-
compiler.pushRaw(loc, 'await _c?.();');
|
|
3382
|
+
compiler.pushRaw(loc, 's+=await _c?.()??"";');
|
|
3355
3383
|
}
|
|
3356
3384
|
const compilers$6 = {
|
|
3357
3385
|
MACRO: compileMacro,
|
|
@@ -4066,6 +4094,14 @@ class Renderer {
|
|
|
4066
4094
|
writable: true,
|
|
4067
4095
|
value: void 0
|
|
4068
4096
|
});
|
|
4097
|
+
// Compilations in progress, so that renders of the same template that
|
|
4098
|
+
// start together share one instead of each compiling it
|
|
4099
|
+
Object.defineProperty(this, "compiling", {
|
|
4100
|
+
enumerable: true,
|
|
4101
|
+
configurable: true,
|
|
4102
|
+
writable: true,
|
|
4103
|
+
value: new Map()
|
|
4104
|
+
});
|
|
4069
4105
|
this.options = mergeOptions(renderOptions, {
|
|
4070
4106
|
filters,
|
|
4071
4107
|
plugins,
|
|
@@ -4074,6 +4110,11 @@ class Renderer {
|
|
|
4074
4110
|
const escapeValue = this.options.security?.deepEscape ? deepEscape : escape;
|
|
4075
4111
|
const { autoEscape } = this.options;
|
|
4076
4112
|
this.escape = (v) => {
|
|
4113
|
+
// Strings are by far the most common value, so they are handled before
|
|
4114
|
+
// anything else is checked
|
|
4115
|
+
if (typeof v === 'string') {
|
|
4116
|
+
return autoEscape ? escape(v) : v;
|
|
4117
|
+
}
|
|
4077
4118
|
if (v === null || v === undefined) {
|
|
4078
4119
|
return '';
|
|
4079
4120
|
}
|
|
@@ -4108,13 +4149,13 @@ class Renderer {
|
|
|
4108
4149
|
return '';
|
|
4109
4150
|
}
|
|
4110
4151
|
}
|
|
4111
|
-
|
|
4152
|
+
let compiler;
|
|
4112
4153
|
try {
|
|
4113
|
-
await
|
|
4154
|
+
compiler = await this.compile(template);
|
|
4114
4155
|
return await this.run(compiler.script, globals);
|
|
4115
4156
|
}
|
|
4116
4157
|
catch (error) {
|
|
4117
|
-
this.options.debug(this.wrapError(error, template, compiler));
|
|
4158
|
+
this.options.debug(this.wrapError(error, template, compiler ?? new SourceMap()));
|
|
4118
4159
|
}
|
|
4119
4160
|
return '';
|
|
4120
4161
|
}
|
|
@@ -4159,12 +4200,12 @@ class Renderer {
|
|
|
4159
4200
|
});
|
|
4160
4201
|
}
|
|
4161
4202
|
};
|
|
4162
|
-
|
|
4203
|
+
let compiler;
|
|
4163
4204
|
// Not awaited: `start` returns right away and chunks are enqueued as
|
|
4164
4205
|
// they are produced
|
|
4165
4206
|
void (async () => {
|
|
4166
4207
|
try {
|
|
4167
|
-
await
|
|
4208
|
+
compiler = await this.compile(template, true);
|
|
4168
4209
|
const rest = await this.run(compiler.script, globals, write);
|
|
4169
4210
|
if (rest && !cancelled) {
|
|
4170
4211
|
controller.enqueue(rest);
|
|
@@ -4176,7 +4217,7 @@ class Renderer {
|
|
|
4176
4217
|
return;
|
|
4177
4218
|
}
|
|
4178
4219
|
try {
|
|
4179
|
-
this.options.debug(this.wrapError(error, template, compiler));
|
|
4220
|
+
this.options.debug(this.wrapError(error, template, compiler ?? new SourceMap()));
|
|
4180
4221
|
controller.close();
|
|
4181
4222
|
}
|
|
4182
4223
|
catch (reported) {
|
|
@@ -4195,8 +4236,16 @@ class Renderer {
|
|
|
4195
4236
|
},
|
|
4196
4237
|
});
|
|
4197
4238
|
}
|
|
4198
|
-
|
|
4199
|
-
|
|
4239
|
+
compile(template, stream = false) {
|
|
4240
|
+
const key = templateCacheKey(template, stream);
|
|
4241
|
+
let compiling = this.compiling.get(key);
|
|
4242
|
+
if (!compiling) {
|
|
4243
|
+
compiling = new Compiler(this.options, this.cache, this.options.cache?.revalidate ?? true, stream)
|
|
4244
|
+
.compile(template)
|
|
4245
|
+
.finally(() => this.compiling.delete(key));
|
|
4246
|
+
this.compiling.set(key, compiling);
|
|
4247
|
+
}
|
|
4248
|
+
return compiling;
|
|
4200
4249
|
}
|
|
4201
4250
|
wrapError(error, template, sourceMap) {
|
|
4202
4251
|
if (error?.name === 'CompileError') {
|
|
@@ -5423,4 +5472,4 @@ function renderStream(template, data = {}, options) {
|
|
|
5423
5472
|
return getRenderer(options).renderStream(template, data);
|
|
5424
5473
|
}
|
|
5425
5474
|
|
|
5426
|
-
export { CompileError, Compiler, ErrorRecovery, ExpCompiler, ExpError, ExpParser, ExpTokenizer, I18n, MixinRegistry, Parser, RenderError, Renderer, RootNode, Safe, TemplatePipeline, TemplateValidator, TokenType, Tokenizer, Traversal, analyzeTemplate, applyMixin, applyMixins, applyWhitespaceControl, baseOptions, compilerOptions, composeLayout, composeTemplates, composeTemplatesWithData, composeWithSlots, createErrorRecovery, createFileLoader, createMixin, defaultErrorHandler, defaultWhitespaceOptions, defineFilters, definePlugin, expTokenTypes, extendTemplateWithMixin, filters, formatTemplate, generateDeclarations, generateSourceMap, getWhitespaceCompilerOptions, getWhitespaceRendererOptions, globalMixinRegistry, i18n, isForbiddenIdentifier, mergeOptions, mergeWhitespaceOptions, optionsFingerprint, parserOptions, precompile, precompileTemplate, render, renderCompiled, renderFile, renderOptions, renderStream, templateCacheKey, validateTemplate };
|
|
5475
|
+
export { CompileError, Compiler, ErrorRecovery, ExpCompiler, ExpError, ExpParser, ExpTokenizer, I18n, MAX_INCLUDE_DEPTH, MixinRegistry, Parser, RenderError, Renderer, RootNode, Safe, TemplatePipeline, TemplateValidator, TokenType, Tokenizer, Traversal, analyzeTemplate, applyMixin, applyMixins, applyWhitespaceControl, baseOptions, compilerOptions, composeLayout, composeTemplates, composeTemplatesWithData, composeWithSlots, createErrorRecovery, createFileLoader, createMixin, defaultErrorHandler, defaultWhitespaceOptions, defineFilters, definePlugin, expTokenTypes, extendTemplateWithMixin, filters, formatTemplate, generateDeclarations, generateSourceMap, getWhitespaceCompilerOptions, getWhitespaceRendererOptions, globalMixinRegistry, i18n, isForbiddenIdentifier, mergeOptions, mergeWhitespaceOptions, optionsFingerprint, parserOptions, precompile, precompileTemplate, render, renderCompiled, renderFile, renderOptions, renderStream, templateCacheKey, validateTemplate };
|