mancha 0.5.2 → 0.5.4
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/browser.js +10 -23
- package/dist/core.d.ts +14 -3
- package/dist/core.js +122 -98
- package/dist/gulp.js +6 -15
- package/dist/index.js +2 -13
- package/dist/interfaces.d.ts +1 -3
- package/dist/iterator.d.ts +1 -0
- package/dist/iterator.js +14 -0
- package/dist/mancha.js +1 -1
- package/dist/plugins.d.ts +1 -13
- package/dist/plugins.js +119 -206
- package/dist/reactive.d.ts +21 -17
- package/dist/reactive.js +97 -107
- package/gulpfile.js +1 -12
- package/package.json +5 -9
- package/tsconfig.json +13 -0
- package/webpack.config.js +0 -2
- package/yarn-error.log +4103 -0
package/dist/browser.js
CHANGED
|
@@ -1,21 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
|
-
var _a, _b, _c, _d;
|
|
12
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
3
|
const core_1 = require("./core");
|
|
14
4
|
class RendererImpl extends core_1.IRenderer {
|
|
15
|
-
|
|
16
|
-
super(...arguments);
|
|
17
|
-
this.dirpath = (0, core_1.dirname)(self.location.href);
|
|
18
|
-
}
|
|
5
|
+
dirpath = (0, core_1.dirname)(self.location.href);
|
|
19
6
|
parseHTML(content, params = { root: false }) {
|
|
20
7
|
if (params.root) {
|
|
21
8
|
return new DOMParser().parseFromString(content, "text/html");
|
|
@@ -36,15 +23,15 @@ class RendererImpl extends core_1.IRenderer {
|
|
|
36
23
|
}
|
|
37
24
|
const Mancha = new RendererImpl();
|
|
38
25
|
self["Mancha"] = Mancha;
|
|
39
|
-
const currentScript =
|
|
40
|
-
if (
|
|
41
|
-
Mancha.update(
|
|
42
|
-
const debug = currentScript
|
|
43
|
-
const cachePolicy = currentScript
|
|
44
|
-
const targets =
|
|
45
|
-
targets.map((target) =>
|
|
26
|
+
const currentScript = self.document?.currentScript;
|
|
27
|
+
if (self.document?.currentScript?.hasAttribute("init")) {
|
|
28
|
+
Mancha.update({ ...currentScript?.dataset });
|
|
29
|
+
const debug = currentScript?.hasAttribute("debug");
|
|
30
|
+
const cachePolicy = currentScript?.getAttribute("cache");
|
|
31
|
+
const targets = currentScript?.getAttribute("target")?.split(",") || ["body"];
|
|
32
|
+
targets.map(async (target) => {
|
|
46
33
|
const fragment = self.document.querySelector(target);
|
|
47
|
-
|
|
48
|
-
})
|
|
34
|
+
await Mancha.debug(debug).mount(fragment, { cache: cachePolicy });
|
|
35
|
+
});
|
|
49
36
|
}
|
|
50
37
|
exports.default = Mancha;
|
package/dist/core.d.ts
CHANGED
|
@@ -1,26 +1,37 @@
|
|
|
1
1
|
import { ReactiveProxyStore } from "./reactive";
|
|
2
2
|
import { ParserParams, RenderParams } from "./interfaces";
|
|
3
|
+
export type EvalListener = (result: any, dependencies: string[]) => any;
|
|
3
4
|
export declare function traverse(root: Node | DocumentFragment | Document, skip?: Set<Node>): Generator<ChildNode>;
|
|
4
5
|
export declare function dirname(fpath: string): string;
|
|
5
6
|
export declare function isRelativePath(fpath: string): boolean;
|
|
6
|
-
export declare function
|
|
7
|
+
export declare function makeEvalFunction(code: string, args?: string[]): Function;
|
|
8
|
+
export declare function safeEval(context: any, code: string, args?: {
|
|
7
9
|
[key: string]: any;
|
|
8
10
|
}): Promise<any>;
|
|
9
11
|
export declare abstract class IRenderer extends ReactiveProxyStore {
|
|
12
|
+
protected debugging: boolean;
|
|
10
13
|
protected readonly dirpath: string;
|
|
14
|
+
protected readonly evalkeys: string[];
|
|
15
|
+
protected readonly expressionCache: Map<string, Function>;
|
|
16
|
+
protected readonly evalCallbacks: Map<string, EvalListener[]>;
|
|
11
17
|
readonly skipNodes: Set<Node>;
|
|
12
18
|
abstract parseHTML(content: string, params?: ParserParams): DocumentFragment;
|
|
13
19
|
abstract serializeHTML(root: DocumentFragment | Node): string;
|
|
20
|
+
debug(flag: boolean): this;
|
|
14
21
|
fetchRemote(fpath: string, params?: RenderParams): Promise<string>;
|
|
15
22
|
fetchLocal(fpath: string, params?: RenderParams): Promise<string>;
|
|
16
23
|
preprocessString(content: string, params?: RenderParams & ParserParams): Promise<DocumentFragment>;
|
|
17
24
|
preprocessLocal(fpath: string, params?: RenderParams & ParserParams): Promise<DocumentFragment>;
|
|
18
25
|
preprocessRemote(fpath: string, params?: RenderParams & ParserParams): Promise<DocumentFragment>;
|
|
19
26
|
clone(): IRenderer;
|
|
20
|
-
log(
|
|
27
|
+
log(...args: any[]): void;
|
|
28
|
+
private cachedExpressionFunction;
|
|
21
29
|
eval(expr: string, args?: {
|
|
22
30
|
[key: string]: any;
|
|
23
|
-
}
|
|
31
|
+
}): Promise<[any, string[]]>;
|
|
32
|
+
watchExpr(expr: string, args: {
|
|
33
|
+
[key: string]: any;
|
|
34
|
+
}, callback: EvalListener): Promise<void>;
|
|
24
35
|
preprocessNode(root: Document | DocumentFragment | Node, params?: RenderParams): Promise<void>;
|
|
25
36
|
renderNode(root: Document | DocumentFragment | Node, params?: RenderParams): Promise<void>;
|
|
26
37
|
mount(root: Document | DocumentFragment | Node, params?: RenderParams): Promise<void>;
|
package/dist/core.js
CHANGED
|
@@ -1,15 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.IRenderer = exports.safeEval = exports.isRelativePath = exports.dirname = exports.traverse = void 0;
|
|
3
|
+
exports.IRenderer = exports.safeEval = exports.makeEvalFunction = exports.isRelativePath = exports.dirname = exports.traverse = void 0;
|
|
13
4
|
const reactive_1 = require("./reactive");
|
|
14
5
|
const iterator_1 = require("./iterator");
|
|
15
6
|
const plugins_1 = require("./plugins");
|
|
@@ -48,116 +39,149 @@ function isRelativePath(fpath) {
|
|
|
48
39
|
!fpath.startsWith("data:"));
|
|
49
40
|
}
|
|
50
41
|
exports.isRelativePath = isRelativePath;
|
|
51
|
-
function
|
|
42
|
+
function makeEvalFunction(code, args = []) {
|
|
43
|
+
return new Function(...args, `with (this) { return (async () => (${code}))(); }`);
|
|
44
|
+
}
|
|
45
|
+
exports.makeEvalFunction = makeEvalFunction;
|
|
46
|
+
function safeEval(context, code, args = {}) {
|
|
52
47
|
const inner = `with (this) { return (async () => (${code}))(); }`;
|
|
53
48
|
return new Function(...Object.keys(args), inner).call(context, ...Object.values(args));
|
|
54
49
|
}
|
|
55
50
|
exports.safeEval = safeEval;
|
|
56
51
|
class IRenderer extends reactive_1.ReactiveProxyStore {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
});
|
|
52
|
+
debugging = false;
|
|
53
|
+
dirpath = "";
|
|
54
|
+
evalkeys = ["$elem", "$event"];
|
|
55
|
+
expressionCache = new Map();
|
|
56
|
+
evalCallbacks = new Map();
|
|
57
|
+
skipNodes = new Set();
|
|
58
|
+
debug(flag) {
|
|
59
|
+
this.debugging = flag;
|
|
60
|
+
return this;
|
|
67
61
|
}
|
|
68
|
-
|
|
69
|
-
return
|
|
70
|
-
return this.fetchRemote(fpath, params);
|
|
71
|
-
});
|
|
62
|
+
async fetchRemote(fpath, params) {
|
|
63
|
+
return fetch(fpath, { cache: params?.cache ?? "default" }).then((res) => res.text());
|
|
72
64
|
}
|
|
73
|
-
|
|
74
|
-
return
|
|
75
|
-
this.log(params, "Preprocessing string content with params:\n", params);
|
|
76
|
-
const fragment = this.parseHTML(content, params);
|
|
77
|
-
yield this.preprocessNode(fragment, params);
|
|
78
|
-
return fragment;
|
|
79
|
-
});
|
|
65
|
+
async fetchLocal(fpath, params) {
|
|
66
|
+
return this.fetchRemote(fpath, params);
|
|
80
67
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
68
|
+
async preprocessString(content, params) {
|
|
69
|
+
this.log("Preprocessing string content with params:\n", params);
|
|
70
|
+
const fragment = this.parseHTML(content, params);
|
|
71
|
+
await this.preprocessNode(fragment, params);
|
|
72
|
+
return fragment;
|
|
73
|
+
}
|
|
74
|
+
async preprocessLocal(fpath, params) {
|
|
75
|
+
const content = await this.fetchLocal(fpath, params);
|
|
76
|
+
return this.preprocessString(content, {
|
|
77
|
+
...params,
|
|
78
|
+
dirpath: dirname(fpath),
|
|
79
|
+
root: params?.root ?? !fpath.endsWith(".tpl.html"),
|
|
86
80
|
});
|
|
87
81
|
}
|
|
88
|
-
preprocessRemote(fpath, params) {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
82
|
+
async preprocessRemote(fpath, params) {
|
|
83
|
+
const cache = params?.cache || "default";
|
|
84
|
+
const content = await fetch(fpath, { cache }).then((res) => res.text());
|
|
85
|
+
return this.preprocessString(content, {
|
|
86
|
+
...params,
|
|
87
|
+
dirpath: dirname(fpath),
|
|
88
|
+
root: params?.root ?? !fpath.endsWith(".tpl.html"),
|
|
94
89
|
});
|
|
95
90
|
}
|
|
96
91
|
clone() {
|
|
97
92
|
return new this.constructor(Object.fromEntries(this.store.entries()));
|
|
98
93
|
}
|
|
99
|
-
log(
|
|
100
|
-
if (
|
|
94
|
+
log(...args) {
|
|
95
|
+
if (this.debugging)
|
|
101
96
|
console.debug(...args);
|
|
102
97
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
return result;
|
|
109
|
-
});
|
|
98
|
+
cachedExpressionFunction(expr) {
|
|
99
|
+
if (!this.expressionCache.has(expr)) {
|
|
100
|
+
this.expressionCache.set(expr, makeEvalFunction(expr, this.evalkeys));
|
|
101
|
+
}
|
|
102
|
+
return this.expressionCache.get(expr);
|
|
110
103
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
yield plugins_1.rebaseRelativePaths.call(this, node, params);
|
|
120
|
-
}));
|
|
121
|
-
// Wait for all the rendering operations to complete.
|
|
122
|
-
yield Promise.all(promises.generator());
|
|
104
|
+
async eval(expr, args = {}) {
|
|
105
|
+
const fn = this.cachedExpressionFunction(expr);
|
|
106
|
+
const vals = this.evalkeys.map((key) => args[key]);
|
|
107
|
+
if (Object.keys(args).some((key) => !this.evalkeys.includes(key))) {
|
|
108
|
+
throw new Error(`Invalid argument key, must be one of: ${this.evalkeys.join(", ")}`);
|
|
109
|
+
}
|
|
110
|
+
const [result, dependencies] = await this.trace(async function () {
|
|
111
|
+
return fn.call(this, ...vals);
|
|
123
112
|
});
|
|
113
|
+
this.log(`eval \`${expr}\` => `, result, `[ ${dependencies.join(", ")} ]`);
|
|
114
|
+
return [result, dependencies];
|
|
124
115
|
}
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
// Replace all the {{ variables }} in the text.
|
|
150
|
-
yield plugins_1.resolveTextNodeExpressions.call(this, node, params);
|
|
151
|
-
}
|
|
152
|
-
});
|
|
116
|
+
watchExpr(expr, args, callback) {
|
|
117
|
+
// Early exit: this eval has already been registered, we just need to add our callback.
|
|
118
|
+
if (this.evalCallbacks.has(expr)) {
|
|
119
|
+
this.evalCallbacks.get(expr)?.push(callback);
|
|
120
|
+
// Trigger the eval manually upon registration, to ensure the callback is called immediately.
|
|
121
|
+
return this.eval(expr, args).then(([result, dependencies]) => callback(result, dependencies));
|
|
122
|
+
}
|
|
123
|
+
// Otherwise, register the callback provided.
|
|
124
|
+
this.evalCallbacks.set(expr, [callback]);
|
|
125
|
+
// Keep track of dependencies each evaluation.
|
|
126
|
+
const prevdeps = [];
|
|
127
|
+
const inner = async () => {
|
|
128
|
+
// Evaluate the expression first.
|
|
129
|
+
const [result, dependencies] = await this.eval(expr, args);
|
|
130
|
+
// Trigger all registered callbacks.
|
|
131
|
+
const callbacks = this.evalCallbacks.get(expr) || [];
|
|
132
|
+
await Promise.all(callbacks.map((x) => x(result, dependencies)));
|
|
133
|
+
// Watch the dependencies for changes.
|
|
134
|
+
if (prevdeps.length > 0)
|
|
135
|
+
this.unwatch(prevdeps, inner);
|
|
136
|
+
prevdeps.splice(0, prevdeps.length, ...dependencies);
|
|
137
|
+
this.watch(dependencies, inner);
|
|
138
|
+
};
|
|
139
|
+
return inner();
|
|
153
140
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
//
|
|
159
|
-
|
|
141
|
+
async preprocessNode(root, params) {
|
|
142
|
+
params = Object.assign({ dirpath: this.dirpath, maxdepth: 10 }, params);
|
|
143
|
+
const promises = new iterator_1.Iterator(traverse(root, this.skipNodes)).map(async (node) => {
|
|
144
|
+
this.log("Preprocessing node:\n", node);
|
|
145
|
+
// Resolve all the includes in the node.
|
|
146
|
+
await plugins_1.RendererPlugins.resolveIncludes.call(this, node, params);
|
|
147
|
+
// Resolve all the relative paths in the node.
|
|
148
|
+
await plugins_1.RendererPlugins.rebaseRelativePaths.call(this, node, params);
|
|
160
149
|
});
|
|
150
|
+
// Wait for all the rendering operations to complete.
|
|
151
|
+
await Promise.all(promises.generator());
|
|
152
|
+
}
|
|
153
|
+
async renderNode(root, params) {
|
|
154
|
+
// Iterate over all the nodes and apply appropriate handlers.
|
|
155
|
+
// Do these steps one at a time to avoid any potential race conditions.
|
|
156
|
+
for (const node of traverse(root, this.skipNodes)) {
|
|
157
|
+
this.log("Rendering node:\n", node);
|
|
158
|
+
// Resolve the :data attribute in the node.
|
|
159
|
+
await plugins_1.RendererPlugins.resolveDataAttribute.call(this, node, params);
|
|
160
|
+
// Resolve the :for attribute in the node.
|
|
161
|
+
await plugins_1.RendererPlugins.resolveForAttribute.call(this, node, params);
|
|
162
|
+
// Resolve the $html attribute in the node.
|
|
163
|
+
await plugins_1.RendererPlugins.resolveHtmlAttribute.call(this, node, params);
|
|
164
|
+
// Resolve the :show attribute in the node.
|
|
165
|
+
await plugins_1.RendererPlugins.resolveShowAttribute.call(this, node, params);
|
|
166
|
+
// Resolve the @watch attribute in the node.
|
|
167
|
+
await plugins_1.RendererPlugins.resolveWatchAttribute.call(this, node, params);
|
|
168
|
+
// Resolve the :bind attribute in the node.
|
|
169
|
+
await plugins_1.RendererPlugins.resolveBindAttribute.call(this, node, params);
|
|
170
|
+
// Resolve all $attributes in the node.
|
|
171
|
+
await plugins_1.RendererPlugins.resolvePropAttributes.call(this, node, params);
|
|
172
|
+
// Resolve all :attributes in the node.
|
|
173
|
+
await plugins_1.RendererPlugins.resolveAttrAttributes.call(this, node, params);
|
|
174
|
+
// Resolve all @attributes in the node.
|
|
175
|
+
await plugins_1.RendererPlugins.resolveEventAttributes.call(this, node, params);
|
|
176
|
+
// Replace all the {{ variables }} in the text.
|
|
177
|
+
await plugins_1.RendererPlugins.resolveTextNodeExpressions.call(this, node, params);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
async mount(root, params) {
|
|
181
|
+
// Preprocess all the elements recursively first.
|
|
182
|
+
await this.preprocessNode(root, params);
|
|
183
|
+
// Now that the DOM is complete, render all the nodes.
|
|
184
|
+
await this.renderNode(root, params);
|
|
161
185
|
}
|
|
162
186
|
}
|
|
163
187
|
exports.IRenderer = IRenderer;
|
package/dist/gulp.js
CHANGED
|
@@ -1,13 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
3
|
const path = require("path");
|
|
13
4
|
const stream = require("stream");
|
|
@@ -38,12 +29,12 @@ function mancha(context = {}, wwwroot = process.cwd()) {
|
|
|
38
29
|
const chunk = file.contents.toString(encoding);
|
|
39
30
|
renderer
|
|
40
31
|
.preprocessString(chunk, { dirpath, root: !file.path.endsWith(".tpl.html") })
|
|
41
|
-
.then((fragment) =>
|
|
42
|
-
|
|
32
|
+
.then(async (fragment) => {
|
|
33
|
+
await renderer.renderNode(fragment);
|
|
43
34
|
const content = renderer.serializeHTML(fragment);
|
|
44
35
|
file.contents = Buffer.from(content, encoding);
|
|
45
36
|
callback(null, file);
|
|
46
|
-
})
|
|
37
|
+
})
|
|
47
38
|
.catch(catcher);
|
|
48
39
|
}
|
|
49
40
|
else if (file.isStream()) {
|
|
@@ -60,8 +51,8 @@ function mancha(context = {}, wwwroot = process.cwd()) {
|
|
|
60
51
|
.on("end", () => {
|
|
61
52
|
renderer
|
|
62
53
|
.preprocessString(docstr, { dirpath, root: !file.path.endsWith(".tpl.html") })
|
|
63
|
-
.then((document) =>
|
|
64
|
-
|
|
54
|
+
.then(async (document) => {
|
|
55
|
+
await renderer.renderNode(document);
|
|
65
56
|
const content = renderer.serializeHTML(document);
|
|
66
57
|
const readable = new stream.Readable();
|
|
67
58
|
readable._read = function () { };
|
|
@@ -69,7 +60,7 @@ function mancha(context = {}, wwwroot = process.cwd()) {
|
|
|
69
60
|
readable.push(null);
|
|
70
61
|
file.contents = readable;
|
|
71
62
|
callback(null, file);
|
|
72
|
-
})
|
|
63
|
+
})
|
|
73
64
|
.catch(catcher);
|
|
74
65
|
});
|
|
75
66
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,23 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
3
|
exports.Mancha = exports.RendererImpl = void 0;
|
|
13
4
|
const fs = require("fs/promises");
|
|
14
5
|
const worker_1 = require("./worker");
|
|
15
6
|
/** The Node Mancha renderer is just like the worker renderer, but it also uses the filesystem. */
|
|
16
7
|
class RendererImpl extends worker_1.RendererImpl {
|
|
17
|
-
fetchLocal(fpath, params) {
|
|
18
|
-
return
|
|
19
|
-
return fs.readFile(fpath, { encoding: (params === null || params === void 0 ? void 0 : params.encoding) || "utf8" });
|
|
20
|
-
});
|
|
8
|
+
async fetchLocal(fpath, params) {
|
|
9
|
+
return fs.readFile(fpath, { encoding: params?.encoding || "utf8" });
|
|
21
10
|
}
|
|
22
11
|
}
|
|
23
12
|
exports.RendererImpl = RendererImpl;
|
package/dist/interfaces.d.ts
CHANGED
|
@@ -14,7 +14,5 @@ export interface RenderParams {
|
|
|
14
14
|
maxdepth?: number;
|
|
15
15
|
/** Cache policy used when resolving remote paths. */
|
|
16
16
|
cache?: RequestCache | null;
|
|
17
|
-
/** Whether to print debug information. */
|
|
18
|
-
debug?: boolean;
|
|
19
17
|
}
|
|
20
|
-
export type RendererPlugin = (this: IRenderer, node: ChildNode, params
|
|
18
|
+
export type RendererPlugin = (this: IRenderer, node: ChildNode, params?: RenderParams) => Promise<void>;
|
package/dist/iterator.d.ts
CHANGED
|
@@ -7,4 +7,5 @@ export declare class Iterator<T> {
|
|
|
7
7
|
generator(): Iterable<T>;
|
|
8
8
|
static filterGenerator<T>(fn: (val: T) => boolean, iter: Iterable<T>): Iterable<T>;
|
|
9
9
|
static mapGenerator<T, S>(fn: (val: T) => S, iter: Iterable<T>): Iterable<S>;
|
|
10
|
+
static equals<T>(a: Iterable<T>, b: Iterable<T>): boolean;
|
|
10
11
|
}
|
package/dist/iterator.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.Iterator = void 0;
|
|
4
4
|
class Iterator {
|
|
5
|
+
iterable;
|
|
5
6
|
constructor(iter) {
|
|
6
7
|
this.iterable = iter;
|
|
7
8
|
}
|
|
@@ -30,5 +31,18 @@ class Iterator {
|
|
|
30
31
|
yield fn(val);
|
|
31
32
|
}
|
|
32
33
|
}
|
|
34
|
+
static equals(a, b) {
|
|
35
|
+
const aIter = a[Symbol.iterator]();
|
|
36
|
+
const bIter = b[Symbol.iterator]();
|
|
37
|
+
let aVal = aIter.next();
|
|
38
|
+
let bVal = bIter.next();
|
|
39
|
+
while (!aVal.done && !bVal.done) {
|
|
40
|
+
if (aVal.value !== bVal.value)
|
|
41
|
+
return false;
|
|
42
|
+
aVal = aIter.next();
|
|
43
|
+
bVal = bIter.next();
|
|
44
|
+
}
|
|
45
|
+
return aVal.done === bVal.done;
|
|
46
|
+
}
|
|
33
47
|
}
|
|
34
48
|
exports.Iterator = Iterator;
|
package/dist/mancha.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{"use strict";var t={885:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.attributeNameToCamelCase=void 0,e.attributeNameToCamelCase=function(t){return t.replace(/-./g,(t=>t[1].toUpperCase()))}},246:function(t,e,i){var r,o,s,n,a=this&&this.__awaiter||function(t,e,i,r){return new(i||(i=Promise))((function(o,s){function n(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,a)}l((r=r.apply(t,e||[])).next())}))};Object.defineProperty(e,"__esModule",{value:!0});const l=i(283);class c extends l.IRenderer{constructor(){super(...arguments),this.dirpath=(0,l.dirname)(self.location.href)}parseHTML(t,e={root:!1}){if(e.root)return(new DOMParser).parseFromString(t,"text/html");{const e=document.createRange();return e.selectNodeContents(document.body),e.createContextualFragment(t)}}serializeHTML(t){return(new XMLSerializer).serializeToString(t).replace(/\s?xmlns="[^"]+"/gm,"")}preprocessLocal(t,e){return this.preprocessRemote(t,e)}}const h=new c;self.Mancha=h;const u=null===(r=self.document)||void 0===r?void 0:r.currentScript;if(null===(s=null===(o=self.document)||void 0===o?void 0:o.currentScript)||void 0===s?void 0:s.hasAttribute("init")){h.update(Object.assign({},null==u?void 0:u.dataset));const t=null==u?void 0:u.hasAttribute("debug"),e=null==u?void 0:u.getAttribute("cache");((null===(n=null==u?void 0:u.getAttribute("target"))||void 0===n?void 0:n.split(","))||["body"]).map((i=>a(void 0,void 0,void 0,(function*(){const r=self.document.querySelector(i);yield h.mount(r,{cache:e,debug:t})}))))}e.default=h},283:function(t,e,i){var r=this&&this.__awaiter||function(t,e,i,r){return new(i||(i=Promise))((function(o,s){function n(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,a)}l((r=r.apply(t,e||[])).next())}))};Object.defineProperty(e,"__esModule",{value:!0}),e.IRenderer=e.safeEval=e.isRelativePath=e.dirname=e.traverse=void 0;const o=i(63),s=i(150),n=i(230);function*a(t,e=new Set){const i=new Set,r=Array.from(t.childNodes).filter((t=>!e.has(t)));for(yield t;r.length;){const t=r.pop();i.has(t)||(i.add(t),yield t),t.childNodes&&Array.from(t.childNodes).filter((t=>!e.has(t))).forEach((t=>r.push(t)))}}function l(t){return t.includes("/")?t.split("/").slice(0,-1).join("/"):""}function c(t,e,i={}){const r=`with (this) { return (async () => (${t}))(); }`;return new Function(...Object.keys(i),r).call(e,...Object.values(i))}e.traverse=a,e.dirname=l,e.isRelativePath=function(t){return!(t.includes("://")||t.startsWith("/")||t.startsWith("#")||t.startsWith("data:"))},e.safeEval=c;class h extends o.ReactiveProxyStore{constructor(){super(...arguments),this.dirpath="",this.skipNodes=new Set}fetchRemote(t,e){return r(this,void 0,void 0,(function*(){var i;return fetch(t,{cache:null!==(i=null==e?void 0:e.cache)&&void 0!==i?i:"default"}).then((t=>t.text()))}))}fetchLocal(t,e){return r(this,void 0,void 0,(function*(){return this.fetchRemote(t,e)}))}preprocessString(t,e){return r(this,void 0,void 0,(function*(){this.log(e,"Preprocessing string content with params:\n",e);const i=this.parseHTML(t,e);return yield this.preprocessNode(i,e),i}))}preprocessLocal(t,e){return r(this,void 0,void 0,(function*(){var i;const r=yield this.fetchLocal(t,e);return this.preprocessString(r,Object.assign(Object.assign({},e),{dirpath:l(t),root:null!==(i=null==e?void 0:e.root)&&void 0!==i?i:!t.endsWith(".tpl.html")}))}))}preprocessRemote(t,e){return r(this,void 0,void 0,(function*(){var i;const r=(null==e?void 0:e.cache)||"default",o=yield fetch(t,{cache:r}).then((t=>t.text()));return this.preprocessString(o,Object.assign(Object.assign({},e),{dirpath:l(t),root:null!==(i=null==e?void 0:e.root)&&void 0!==i?i:!t.endsWith(".tpl.html")}))}))}clone(){return new this.constructor(Object.fromEntries(this.store.entries()))}log(t,...e){(null==t?void 0:t.debug)&&console.debug(...e)}eval(t){return r(this,arguments,void 0,(function*(t,e={},i){const r=(0,o.proxify)(this),s=yield c(t,r,Object.assign({},e));return this.log(i,`eval \`${t}\` => `,s),s}))}preprocessNode(t,e){return r(this,void 0,void 0,(function*(){e=Object.assign({dirpath:this.dirpath,maxdepth:10},e);const i=new s.Iterator(a(t,this.skipNodes)).map((t=>r(this,void 0,void 0,(function*(){this.log(e,"Preprocessing node:\n",t),yield n.resolveIncludes.call(this,t,e),yield n.rebaseRelativePaths.call(this,t,e)}))));yield Promise.all(i.generator())}))}renderNode(t,e){return r(this,void 0,void 0,(function*(){for(const i of a(t,this.skipNodes))this.log(e,"Rendering node:\n",i),yield n.resolveDataAttribute.call(this,i,e),yield n.resolveForAttribute.call(this,i,e),yield n.resolveHtmlAttribute.call(this,i,e),yield n.resolveShowAttribute.call(this,i,e),yield n.resolveWatchAttribute.call(this,i,e),yield n.resolveBindAttribute.call(this,i,e),yield n.resolvePropAttributes.call(this,i,e),yield n.resolveAttrAttributes.call(this,i,e),yield n.resolveEventAttributes.call(this,i,e),yield n.resolveTextNodeExpressions.call(this,i,e)}))}mount(t,e){return r(this,void 0,void 0,(function*(){yield this.preprocessNode(t,e),yield this.renderNode(t,e)}))}}e.IRenderer=h},150:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Iterator=void 0;class i{constructor(t){this.iterable=t}filter(t){return new i(i.filterGenerator(t,this.iterable))}map(t){return new i(i.mapGenerator(t,this.iterable))}array(){return Array.from(this.iterable)}*generator(){for(const t of this.iterable)yield t}static*filterGenerator(t,e){for(const i of e)t(i)&&(yield i)}static*mapGenerator(t,e){for(const i of e)yield t(i)}}e.Iterator=i},230:function(t,e,i){var r=this&&this.__awaiter||function(t,e,i,r){return new(i||(i=Promise))((function(o,s){function n(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,a)}l((r=r.apply(t,e||[])).next())}))};Object.defineProperty(e,"__esModule",{value:!0}),e.resolveShowAttribute=e.resolveBindAttribute=e.resolveForAttribute=e.resolveEventAttributes=e.resolveAttrAttributes=e.resolvePropAttributes=e.resolveHtmlAttribute=e.resolveWatchAttribute=e.resolveDataAttribute=e.resolveTextNodeExpressions=e.rebaseRelativePaths=e.resolveIncludes=void 0;const o=i(885),s=i(283),n=new Set([":bind",":bind-events",":data",":for",":show","@watch","$html"]),a={$text:"$text-content"};e.resolveIncludes=function(t,e){return r(this,void 0,void 0,(function*(){var i,r,o,s;const n=t;if("include"!==(null===(i=n.tagName)||void 0===i?void 0:i.toLocaleLowerCase()))return;this.log(e,"<include> tag found in:\n",t),this.log(e,"<include> params:",e);const a=null===(r=n.getAttribute)||void 0===r?void 0:r.call(n,"src");if(!a)throw new Error(`"src" attribute missing from ${t}.`);const l=e=>{t.replaceWith(...Array.from(e.childNodes))},c=Object.assign(Object.assign({},e),{root:!1,maxdepth:e.maxdepth-1});if(0===c.maxdepth)throw new Error("Maximum recursion depth reached.");if(a.includes("://")||a.startsWith("//"))this.log(e,"Including remote file from absolute path:",a),yield this.preprocessRemote(a,c).then(l);else if((null===(o=e.dirpath)||void 0===o?void 0:o.includes("://"))||(null===(s=e.dirpath)||void 0===s?void 0:s.startsWith("//"))){const t=e.dirpath&&"."!==e.dirpath?`${e.dirpath}/${a}`:a;this.log(e,"Including remote file from relative path:",t),yield this.preprocessRemote(t,c).then(l)}else if("/"===a.charAt(0))this.log(e,"Including local file from absolute path:",a),yield this.preprocessLocal(a,c).then(l);else{const t=e.dirpath&&"."!==e.dirpath?`${e.dirpath}/${a}`:a;this.log(e,"Including local file from relative path:",t),yield this.preprocessLocal(t,c).then(l)}}))},e.rebaseRelativePaths=function(t,e){return r(this,void 0,void 0,(function*(){var i,r,o,n,a,l,c;const h=t,u=null===(i=h.tagName)||void 0===i?void 0:i.toLowerCase();if(!e.dirpath)return;const d=null===(o=(r=t).getAttribute)||void 0===o?void 0:o.call(r,"src"),v=null===(a=(n=t).getAttribute)||void 0===a?void 0:a.call(n,"href"),f=null===(c=(l=t).getAttribute)||void 0===c?void 0:c.call(l,"data"),p=d||v||f;p&&(p&&(0,s.isRelativePath)(p)&&this.log(e,"Rebasing relative path as:",e.dirpath,"/",p),"img"===u&&d&&(0,s.isRelativePath)(d)?h.src=`${e.dirpath}/${d}`:"a"===u&&v&&(0,s.isRelativePath)(v)||"link"===u&&v&&(0,s.isRelativePath)(v)?h.href=`${e.dirpath}/${v}`:"script"===u&&d&&(0,s.isRelativePath)(d)||"source"===u&&d&&(0,s.isRelativePath)(d)||"audio"===u&&d&&(0,s.isRelativePath)(d)||"video"===u&&d&&(0,s.isRelativePath)(d)||"track"===u&&d&&(0,s.isRelativePath)(d)||"iframe"===u&&d&&(0,s.isRelativePath)(d)?h.src=`${e.dirpath}/${d}`:"object"===u&&f&&(0,s.isRelativePath)(f)?h.data=`${e.dirpath}/${f}`:"input"===u&&d&&(0,s.isRelativePath)(d)?h.src=`${e.dirpath}/${d}`:("area"===u&&v&&(0,s.isRelativePath)(v)||"base"===u&&v&&(0,s.isRelativePath)(v))&&(h.href=`${e.dirpath}/${v}`))}))},e.resolveTextNodeExpressions=function(t,e){return r(this,void 0,void 0,(function*(){if(3!==t.nodeType)return;const i=t.nodeValue||"",o=new RegExp(/{{ ([^}]+) }}/gm),s=Array.from(i.matchAll(o)).map((t=>t[1])),n=()=>r(this,void 0,void 0,(function*(){let r=i;for(const i of s){const o=yield this.eval(i,{$elem:t},e);r=r.replace(`{{ ${i} }}`,String(o))}t.nodeValue=r})),[a,l]=yield this.trace(n);this.log(e,i,"=>",a),this.watch(l,n)}))},e.resolveDataAttribute=function(t,e){return r(this,void 0,void 0,(function*(){var i;if(this.skipNodes.has(t))return;const r=t,o=null===(i=r.getAttribute)||void 0===i?void 0:i.call(r,":data");if(o){this.log(e,":data attribute found in:\n",t),r.removeAttribute(":data");const i=yield this.eval(o,{$elem:t},e);this.log(e,":data",o,"=>",i),yield this.update(i)}}))},e.resolveWatchAttribute=function(t,e){return r(this,void 0,void 0,(function*(){var i;if(this.skipNodes.has(t))return;const r=t,o=null===(i=r.getAttribute)||void 0===i?void 0:i.call(r,"@watch");if(o){this.log(e,"@watch attribute found in:\n",t),r.removeAttribute("@watch");const i=()=>this.eval(o,{$elem:t},e),[s,n]=yield this.trace(i);this.log(e,"@watch",o,"=>",s),this.watch(n,i)}}))},e.resolveHtmlAttribute=function(t,e){return r(this,void 0,void 0,(function*(){var i;if(this.skipNodes.has(t))return;const o=t,s=null===(i=o.getAttribute)||void 0===i?void 0:i.call(o,"$html");if(s){this.log(e,"$html attribute found in:\n",t),o.removeAttribute("$html");const i=this.clone(),n=()=>r(this,void 0,void 0,(function*(){const r=yield this.eval(s,{$elem:t},e),n=yield i.preprocessString(r,e);yield i.renderNode(n,e),o.replaceChildren(n)})),[a,l]=yield this.trace(n);this.log(e,"$html",s,"=>",a),this.watch(l,n)}}))},e.resolvePropAttributes=function(t,e){return r(this,void 0,void 0,(function*(){if(this.skipNodes.has(t))return;const i=t;for(const s of Array.from(i.attributes||[]))if(s.name.startsWith("$")&&!n.has(s.name)){this.log(e,s.name,"attribute found in:\n",t),i.removeAttribute(s.name);const n=(a[s.name]||s.name).slice(1),l=()=>this.eval(s.value,{$elem:t},e),[c,h]=yield this.trace(l);this.log(e,s.name,s.value,"=>",c,`[${h}]`);const u=(0,o.attributeNameToCamelCase)(n);this.watch(h,(()=>r(this,void 0,void 0,(function*(){return t[u]=yield l()})))),t[u]=c}}))},e.resolveAttrAttributes=function(t,e){return r(this,void 0,void 0,(function*(){if(this.skipNodes.has(t))return;const i=t;for(const o of Array.from(i.attributes||[]))if(o.name.startsWith(":")&&!n.has(o.name)){this.log(e,o.name,"attribute found in:\n",t),i.removeAttribute(o.name);const s=(a[o.name]||o.name).slice(1),n=()=>this.eval(o.value,{$elem:t},e),[l,c]=yield this.trace(n);this.log(e,o.name,o.value,"=>",l,`[${c}]`),this.watch(c,(()=>r(this,void 0,void 0,(function*(){return i.setAttribute(s,yield n())})))),i.setAttribute(s,l)}}))},e.resolveEventAttributes=function(t,e){return r(this,void 0,void 0,(function*(){var i;if(this.skipNodes.has(t))return;const r=t;for(const o of Array.from(r.attributes||[]))o.name.startsWith("@")&&!n.has(o.name)&&(this.log(e,o.name,"attribute found in:\n",t),r.removeAttribute(o.name),null===(i=t.addEventListener)||void 0===i||i.call(t,o.name.substring(1),(i=>this.eval(o.value,{$elem:t,$event:i},e))))}))},e.resolveForAttribute=function(t,e){return r(this,void 0,void 0,(function*(){var i;if(this.skipNodes.has(t))return;const o=t,n=null===(i=o.getAttribute)||void 0===i?void 0:i.call(o,":for");if(n){this.log(e,":for attribute found in:\n",t),o.removeAttribute(":for");for(const e of(0,s.traverse)(t,this.skipNodes))this.skipNodes.add(e);const i=t.parentNode,a=t.ownerDocument.createElement("template");i.insertBefore(a,t),a.append(t),this.log(e,":for template:\n",a);const l=n.split(" in ",2);if(2!==l.length)throw new Error(`Invalid :for format: \`${n}\`. Expected "{key} in {expression}".`);let c=[],h=[];const[u,d]=l;try{[c,h]=yield this.trace((()=>this.eval(d,{$elem:t},e))),this.log(e,d,"=>",c,`[${h}]`)}catch(t){return void console.error(t)}const v=[],f=o=>r(this,void 0,void 0,(function*(){if(this.log(e,":for list items:",o),Array.isArray(o))return this.lock=this.lock.then((()=>new Promise((s=>r(this,void 0,void 0,(function*(){v.splice(0,v.length).forEach((t=>{i.removeChild(t),this.skipNodes.delete(t)}));for(const r of o.slice(0).reverse()){const o=this.clone();yield o.set(u,r);const s=t.cloneNode(!0);i.insertBefore(s,a.nextSibling),v.push(s),this.skipNodes.add(s),yield o.mount(s,e),this.log(e,"Rendered list child:\n",s)}s()})))))),this.lock;console.error(`Expression did not yield a list: \`${d}\` => \`${o}\``)}));return this.watch(h,(()=>r(this,void 0,void 0,(function*(){return f(yield this.eval(d,{$elem:t},e))})))),f(c)}}))},e.resolveBindAttribute=function(t,e){return r(this,void 0,void 0,(function*(){var i,r,o;if(this.skipNodes.has(t))return;const s=t,n=null===(i=s.getAttribute)||void 0===i?void 0:i.call(s,":bind");if(n){this.log(e,":bind attribute found in:\n",t);const i=["change","input"],a=(null===(o=null===(r=s.getAttribute)||void 0===r?void 0:r.call(s,":bind-events"))||void 0===o?void 0:o.split(","))||i;s.removeAttribute(":bind"),s.removeAttribute(":bind-events");const l="checkbox"===s.getAttribute("type")?"checked":"value";this.has(n)||(yield this.set(n,s[l])),s[l]=this.get(n);for(const e of a)t.addEventListener(e,(()=>this.set(n,s[l])));this.watch([n],(()=>s[l]=this.get(n)))}}))},e.resolveShowAttribute=function(t,e){return r(this,void 0,void 0,(function*(){var i;if(this.skipNodes.has(t))return;const o=t,s=null===(i=o.getAttribute)||void 0===i?void 0:i.call(o,":show");if(s){this.log(e,":show attribute found in:\n",t),o.removeAttribute(":show");const i=()=>this.eval(s,{$elem:t},e),[n,a]=yield this.trace(i);this.log(e,":show",s,"=>",n,`[${a}]`);const l="none"===o.style.display?"":o.style.display;n||(o.style.display="none"),this.watch(a,(()=>r(this,void 0,void 0,(function*(){o.style.display=(yield i())?l:"none"}))))}}))}},63:function(t,e){var i=this&&this.__awaiter||function(t,e,i,r){return new(i||(i=Promise))((function(o,s){function n(t){try{l(r.next(t))}catch(t){s(t)}}function a(t){try{l(r.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,a)}l((r=r.apply(t,e||[])).next())}))};Object.defineProperty(e,"__esModule",{value:!0}),e.proxify=e.ReactiveProxyStore=e.InertProxy=e.ReactiveProxy=e.proxifyObject=e.REACTIVE_DEBOUNCE_MILLIS=void 0;class r{constructor(){this.timeout=null}debounce(t,e){return new Promise(((i,r)=>{this.timeout&&clearTimeout(this.timeout),this.timeout=setTimeout((()=>{try{i(e())}catch(t){r(t)}}),t)}))}}function o(t,e,i=!0){if(null==t||function(t){return t instanceof s||t.__is_proxy__}(t))return t;if(i)for(const i in t)t.hasOwnProperty(i)&&"object"==typeof t[i]&&null!=t[i]&&(t[i]=o(t[i],e));return new Proxy(t,{deleteProperty:(t,i)=>i in t&&(delete t[i],e(),!0),set:(t,r,s,n)=>{i&&"object"==typeof s&&(s=o(s,e));const a=Reflect.set(t,r,s,n);return e(),a},get:(t,e,i)=>"__is_proxy__"===e||Reflect.get(t,e,i)})}e.REACTIVE_DEBOUNCE_MILLIS=25,e.proxifyObject=o;class s extends r{constructor(t=null,...e){super(),this.value=null,this.listeners=[],this.set(t),e.forEach((t=>this.watch(t)))}static from(t,...e){return t instanceof s?(e.forEach(t.watch),t):new s(t,...e)}get(){return this.value}set(t){return i(this,void 0,void 0,(function*(){if(this.value!==t){const e=this.value;null!=t&&"object"==typeof t&&(t=o(t,(()=>this.trigger()))),this.value=t,yield this.trigger(e)}}))}watch(t){this.listeners.push(t)}unwatch(t){this.listeners=this.listeners.filter((e=>e!==t))}trigger(){return i(this,arguments,void 0,(function*(t=null){yield this.debounce(e.REACTIVE_DEBOUNCE_MILLIS,(()=>Promise.all(this.listeners.map((e=>e(this.value,t))))))}))}}e.ReactiveProxy=s;class n extends s{static from(t,...e){return t instanceof s?t:new n(t,...e)}watch(t){}trigger(t){return Promise.resolve()}}function a(t){const e=Array.from(t.entries()).map((([t])=>t)),i=Object.fromEntries(e.map((t=>[t,void 0])));return new Proxy(Object.assign({},t,i),{get:(e,i,r)=>"string"==typeof i&&t.has(i)?t.get(i):Reflect.get(t,i,r),set:(e,i,r,o)=>("string"!=typeof i||i in t?Reflect.set(t,i,r,o):t.set(i,r),!0)})}e.InertProxy=n,e.ReactiveProxyStore=class extends r{wrapFnValue(t){return t&&"function"==typeof t?(...e)=>t.call(a(this),...e):t}constructor(t){super(),this.store=new Map,this.tracing=!1,this.traced=new Set,this.lock=Promise.resolve();for(const[e,i]of Object.entries(t||{}))this.store.set(e,s.from(this.wrapFnValue(i)))}get $(){return a(this)}entries(){return this.store.entries()}get(t){var e;return this.tracing&&this.traced.add(t),null===(e=this.store.get(t))||void 0===e?void 0:e.get()}set(t,e){return i(this,void 0,void 0,(function*(){this.store.has(t)?yield this.store.get(t).set(this.wrapFnValue(e)):this.store.set(t,s.from(this.wrapFnValue(e)))}))}del(t){return this.store.delete(t)}has(t){return this.store.has(t)}update(t){return i(this,void 0,void 0,(function*(){yield Promise.all(Object.entries(t).map((([t,e])=>this.set(t,e))))}))}watch(t,e){(t=Array.isArray(t)?t:[t]).forEach((i=>this.store.get(i).watch((()=>e(...t.map((t=>this.store.get(t).get())))))))}trigger(t){return i(this,void 0,void 0,(function*(){t=Array.isArray(t)?t:[t],yield Promise.all(t.map((t=>this.store.get(t).trigger())))}))}trace(t){return i(this,void 0,void 0,(function*(){yield this.lock;const e=new Promise(((e,r)=>i(this,void 0,void 0,(function*(){this.traced.clear(),this.tracing=!0;try{const i=yield t(),r=Array.from(this.traced);e([i,r])}catch(t){r(t)}finally{this.tracing=!1,this.traced.clear()}}))));return this.lock=e.then((()=>{})),e}))}computed(t,e){return i(this,void 0,void 0,(function*(){const[r,o]=yield this.trace((()=>e.call(a(this))));this.watch(o,(()=>i(this,void 0,void 0,(function*(){return this.set(t,yield e.call(a(this)))})))),this.set(t,r)}))}},e.proxify=a}},e={};!function i(r){var o=e[r];if(void 0!==o)return o.exports;var s=e[r]={exports:{}};return t[r].call(s.exports,s,s.exports,i),s.exports}(246)})();
|
|
1
|
+
(()=>{"use strict";var e={885:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.attributeNameToCamelCase=void 0,t.attributeNameToCamelCase=function(e){return e.replace(/-./g,(e=>e[1].toUpperCase()))}},283:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IRenderer=t.safeEval=t.makeEvalFunction=t.isRelativePath=t.dirname=t.traverse=void 0;const r=s(63),i=s(150),a=s(230);function*n(e,t=new Set){const s=new Set,r=Array.from(e.childNodes).filter((e=>!t.has(e)));for(yield e;r.length;){const e=r.pop();s.has(e)||(s.add(e),yield e),e.childNodes&&Array.from(e.childNodes).filter((e=>!t.has(e))).forEach((e=>r.push(e)))}}function o(e){return e.includes("/")?e.split("/").slice(0,-1).join("/"):""}function c(e,t=[]){return new Function(...t,`with (this) { return (async () => (${e}))(); }`)}t.traverse=n,t.dirname=o,t.isRelativePath=function(e){return!(e.includes("://")||e.startsWith("/")||e.startsWith("#")||e.startsWith("data:"))},t.makeEvalFunction=c,t.safeEval=function(e,t,s={}){const r=`with (this) { return (async () => (${t}))(); }`;return new Function(...Object.keys(s),r).call(e,...Object.values(s))};class l extends r.ReactiveProxyStore{debugging=!1;dirpath="";evalkeys=["$elem","$event"];expressionCache=new Map;evalCallbacks=new Map;skipNodes=new Set;debug(e){return this.debugging=e,this}async fetchRemote(e,t){return fetch(e,{cache:t?.cache??"default"}).then((e=>e.text()))}async fetchLocal(e,t){return this.fetchRemote(e,t)}async preprocessString(e,t){this.log("Preprocessing string content with params:\n",t);const s=this.parseHTML(e,t);return await this.preprocessNode(s,t),s}async preprocessLocal(e,t){const s=await this.fetchLocal(e,t);return this.preprocessString(s,{...t,dirpath:o(e),root:t?.root??!e.endsWith(".tpl.html")})}async preprocessRemote(e,t){const s=t?.cache||"default",r=await fetch(e,{cache:s}).then((e=>e.text()));return this.preprocessString(r,{...t,dirpath:o(e),root:t?.root??!e.endsWith(".tpl.html")})}clone(){return new this.constructor(Object.fromEntries(this.store.entries()))}log(...e){this.debugging&&console.debug(...e)}cachedExpressionFunction(e){return this.expressionCache.has(e)||this.expressionCache.set(e,c(e,this.evalkeys)),this.expressionCache.get(e)}async eval(e,t={}){const s=this.cachedExpressionFunction(e),r=this.evalkeys.map((e=>t[e]));if(Object.keys(t).some((e=>!this.evalkeys.includes(e))))throw new Error(`Invalid argument key, must be one of: ${this.evalkeys.join(", ")}`);const[i,a]=await this.trace((async function(){return s.call(this,...r)}));return this.log(`eval \`${e}\` => `,i,`[ ${a.join(", ")} ]`),[i,a]}watchExpr(e,t,s){if(this.evalCallbacks.has(e))return this.evalCallbacks.get(e)?.push(s),this.eval(e,t).then((([e,t])=>s(e,t)));this.evalCallbacks.set(e,[s]);const r=[],i=async()=>{const[s,a]=await this.eval(e,t),n=this.evalCallbacks.get(e)||[];await Promise.all(n.map((e=>e(s,a)))),r.length>0&&this.unwatch(r,i),r.splice(0,r.length,...a),this.watch(a,i)};return i()}async preprocessNode(e,t){t=Object.assign({dirpath:this.dirpath,maxdepth:10},t);const s=new i.Iterator(n(e,this.skipNodes)).map((async e=>{this.log("Preprocessing node:\n",e),await a.RendererPlugins.resolveIncludes.call(this,e,t),await a.RendererPlugins.rebaseRelativePaths.call(this,e,t)}));await Promise.all(s.generator())}async renderNode(e,t){for(const s of n(e,this.skipNodes))this.log("Rendering node:\n",s),await a.RendererPlugins.resolveDataAttribute.call(this,s,t),await a.RendererPlugins.resolveForAttribute.call(this,s,t),await a.RendererPlugins.resolveHtmlAttribute.call(this,s,t),await a.RendererPlugins.resolveShowAttribute.call(this,s,t),await a.RendererPlugins.resolveWatchAttribute.call(this,s,t),await a.RendererPlugins.resolveBindAttribute.call(this,s,t),await a.RendererPlugins.resolvePropAttributes.call(this,s,t),await a.RendererPlugins.resolveAttrAttributes.call(this,s,t),await a.RendererPlugins.resolveEventAttributes.call(this,s,t),await a.RendererPlugins.resolveTextNodeExpressions.call(this,s,t)}async mount(e,t){await this.preprocessNode(e,t),await this.renderNode(e,t)}}t.IRenderer=l},150:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Iterator=void 0;class s{iterable;constructor(e){this.iterable=e}filter(e){return new s(s.filterGenerator(e,this.iterable))}map(e){return new s(s.mapGenerator(e,this.iterable))}array(){return Array.from(this.iterable)}*generator(){for(const e of this.iterable)yield e}static*filterGenerator(e,t){for(const s of t)e(s)&&(yield s)}static*mapGenerator(e,t){for(const s of t)yield e(s)}static equals(e,t){const s=e[Symbol.iterator](),r=t[Symbol.iterator]();let i=s.next(),a=r.next();for(;!i.done&&!a.done;){if(i.value!==a.value)return!1;i=s.next(),a=r.next()}return i.done===a.done}}t.Iterator=s},230:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RendererPlugins=void 0;const r=s(885),i=s(283),a=new Set([":bind",":bind-events",":data",":for",":show","@watch","$html"]),n={$text:"$text-content"};var o;!function(e){e.resolveIncludes=async function(e,t){const s=e;if("include"!==s.tagName?.toLocaleLowerCase())return;this.log("<include> tag found in:\n",e),this.log("<include> params:",t);const r=s.getAttribute?.("src");if(!r)throw new Error(`"src" attribute missing from ${e}.`);const i=t=>{e.replaceWith(...Array.from(t.childNodes))},a={...t,root:!1,maxdepth:t?.maxdepth-1};if(0===a.maxdepth)throw new Error("Maximum recursion depth reached.");if(r.includes("://")||r.startsWith("//"))this.log("Including remote file from absolute path:",r),await this.preprocessRemote(r,a).then(i);else if(t?.dirpath?.includes("://")||t?.dirpath?.startsWith("//")){const e=t.dirpath&&"."!==t.dirpath?`${t.dirpath}/${r}`:r;this.log("Including remote file from relative path:",e),await this.preprocessRemote(e,a).then(i)}else if("/"===r.charAt(0))this.log("Including local file from absolute path:",r),await this.preprocessLocal(r,a).then(i);else{const e=t?.dirpath&&"."!==t?.dirpath?`${t?.dirpath}/${r}`:r;this.log("Including local file from relative path:",e),await this.preprocessLocal(e,a).then(i)}},e.rebaseRelativePaths=async function(e,t){const s=e,r=s.tagName?.toLowerCase();if(!t?.dirpath)return;const a=e.getAttribute?.("src"),n=e.getAttribute?.("href"),o=e.getAttribute?.("data"),c=a||n||o;c&&(c&&(0,i.isRelativePath)(c)&&this.log("Rebasing relative path as:",t.dirpath,"/",c),"img"===r&&a&&(0,i.isRelativePath)(a)?s.src=`${t.dirpath}/${a}`:"a"===r&&n&&(0,i.isRelativePath)(n)||"link"===r&&n&&(0,i.isRelativePath)(n)?s.href=`${t.dirpath}/${n}`:"script"===r&&a&&(0,i.isRelativePath)(a)||"source"===r&&a&&(0,i.isRelativePath)(a)||"audio"===r&&a&&(0,i.isRelativePath)(a)||"video"===r&&a&&(0,i.isRelativePath)(a)||"track"===r&&a&&(0,i.isRelativePath)(a)||"iframe"===r&&a&&(0,i.isRelativePath)(a)?s.src=`${t.dirpath}/${a}`:"object"===r&&o&&(0,i.isRelativePath)(o)?s.data=`${t.dirpath}/${o}`:"input"===r&&a&&(0,i.isRelativePath)(a)?s.src=`${t.dirpath}/${a}`:("area"===r&&n&&(0,i.isRelativePath)(n)||"base"===r&&n&&(0,i.isRelativePath)(n))&&(s.href=`${t.dirpath}/${n}`))},e.resolveTextNodeExpressions=async function(e,t){if(3!==e.nodeType)return;const s=e.nodeValue||"";this.log("Processing node content value:\n",s);const r=new RegExp(/{{ ([^}]+) }}/gm),i=Array.from(s.matchAll(r)).map((e=>e[1])),a=async()=>{let t=s;for(const s of i){const[r]=await this.eval(s,{$elem:e});t=t.replace(`{{ ${s} }}`,String(r))}e.nodeValue=t};await Promise.all(i.map((t=>this.watchExpr(t,{$elem:e},a))))},e.resolveDataAttribute=async function(e,t){if(this.skipNodes.has(e))return;const s=e,r=s.getAttribute?.(":data");if(r){this.log(":data attribute found in:\n",e),s.removeAttribute(":data");const[t]=await this.eval(r,{$elem:e});await this.update(t)}},e.resolveWatchAttribute=async function(e,t){if(this.skipNodes.has(e))return;const s=e,r=s.getAttribute?.("@watch");r&&(this.log("@watch attribute found in:\n",e),s.removeAttribute("@watch"),await this.watchExpr(r,{$elem:e},(()=>{})))},e.resolveHtmlAttribute=async function(e,t){if(this.skipNodes.has(e))return;const s=e,r=s.getAttribute?.("$html");if(r){this.log("$html attribute found in:\n",e),s.removeAttribute("$html");const i=this.clone();await this.watchExpr(r,{$elem:e},(async e=>{const r=await i.preprocessString(e,t);await i.renderNode(r,t),s.replaceChildren(r)}))}},e.resolvePropAttributes=async function(e,t){if(this.skipNodes.has(e))return;const s=e;for(const t of Array.from(s.attributes||[]))if(t.name.startsWith("$")&&!a.has(t.name)){this.log(t.name,"attribute found in:\n",e),s.removeAttribute(t.name);const i=(n[t.name]||t.name).slice(1),a=(0,r.attributeNameToCamelCase)(i);await this.watchExpr(t.value,{$elem:e},(t=>e[a]=t))}},e.resolveAttrAttributes=async function(e,t){if(this.skipNodes.has(e))return;const s=e;for(const t of Array.from(s.attributes||[]))if(t.name.startsWith(":")&&!a.has(t.name)){this.log(t.name,"attribute found in:\n",e),s.removeAttribute(t.name);const r=(n[t.name]||t.name).slice(1);await this.watchExpr(t.value,{$elem:e},(e=>s.setAttribute(r,e)))}},e.resolveEventAttributes=async function(e,t){if(this.skipNodes.has(e))return;const s=e;for(const t of Array.from(s.attributes||[]))t.name.startsWith("@")&&!a.has(t.name)&&(this.log(t.name,"attribute found in:\n",e),s.removeAttribute(t.name),e.addEventListener?.(t.name.substring(1),(s=>{this.eval(t.value,{$elem:e,$event:s})})))},e.resolveForAttribute=async function(e,t){if(this.skipNodes.has(e))return;const s=e,r=s.getAttribute?.(":for")?.trim();if(r){this.log(":for attribute found in:\n",e),s.removeAttribute(":for");for(const t of(0,i.traverse)(e,this.skipNodes))this.skipNodes.add(t);const a=e.parentNode,n=e.ownerDocument.createElement("template");a.insertBefore(n,e),n.append(e),this.log(":for template:\n",n);const o=r.split(" in ",2);if(2!==o.length)throw new Error(`Invalid :for format: \`${r}\`. Expected "{key} in {expression}".`);const c=[],[l,h]=o;await this.watchExpr(h,{$elem:e},(s=>(this.log(":for list items:",s),this.lock=this.lock.then((()=>new Promise((async r=>{if(c.splice(0,c.length).forEach((e=>{a.removeChild(e),this.skipNodes.delete(e)})),!Array.isArray(s))return console.error(`Expression did not yield a list: \`${h}\` => \`${s}\``),r();for(const r of s.slice(0).reverse()){const s=this.clone();await s.set(l,r);const i=e.cloneNode(!0);a.insertBefore(i,n.nextSibling),c.push(i),this.skipNodes.add(i),await s.mount(i,t),this.log("Rendered list child:\n",i,i.outerHTML)}r()})))),this.lock)))}},e.resolveBindAttribute=async function(e,t){if(this.skipNodes.has(e))return;const s=e,r=s.getAttribute?.(":bind");if(r){this.log(":bind attribute found in:\n",e);const t=["change","input"],i=s.getAttribute?.(":bind-events")?.split(",")||t;s.removeAttribute(":bind"),s.removeAttribute(":bind-events");const a="checkbox"===s.getAttribute("type")?"checked":"value",n=`$elem.${a} = ${r}`;await this.watchExpr(n,{$elem:e},(e=>s[a]=e));const o=`${r} = $elem.${a}`;for(const t of i)e.addEventListener(t,(()=>this.eval(o,{$elem:e})))}},e.resolveShowAttribute=async function(e,t){if(this.skipNodes.has(e))return;const s=e,r=s.getAttribute?.(":show");if(r){this.log(":show attribute found in:\n",e),s.removeAttribute(":show");const t="none"===s.style.display?"":s.style.display;await this.watchExpr(r,{$elem:e},(e=>{s.style.display=e?t:"none"}))}}}(o||(t.RendererPlugins=o={}))},63:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.proxifyStore=t.ReactiveProxyStore=t.InertProxy=t.ReactiveProxy=t.proxifyObject=t.REACTIVE_DEBOUNCE_MILLIS=void 0;class s{timeouts=new Map;debounce(e,t){return new Promise(((s,r)=>{const i=this.timeouts.get(t);i&&clearTimeout(i),this.timeouts.set(t,setTimeout((()=>{try{s(t()),this.timeouts.delete(t)}catch(e){r(e)}}),e))}))}}function r(e,t,s=!0){if(null==e||function(e){return e instanceof i||e.__is_proxy__}(e))return e;if(s)for(const s in e)e.hasOwnProperty(s)&&"object"==typeof e[s]&&null!=e[s]&&(e[s]=r(e[s],t));return new Proxy(e,{deleteProperty:(e,s)=>s in e&&(delete e[s],t(),!0),set:(e,i,a,n)=>{s&&"object"==typeof a&&(a=r(a,t));const o=Reflect.set(e,i,a,n);return t(),o},get:(e,t,s)=>"__is_proxy__"===t||Reflect.get(e,t,s)})}t.REACTIVE_DEBOUNCE_MILLIS=10,t.proxifyObject=r;class i extends s{value=null;listeners=[];constructor(e=null,...t){super(),this.value=this.wrapObjValue(e),t.forEach((e=>this.watch(e)))}static from(e,...t){return e instanceof i?(t.forEach(e.watch),e):new i(e,...t)}wrapObjValue(e){return null===e||"object"!=typeof e?e:r(e,(()=>this.trigger()))}get(){return this.value}async set(e){if(this.value!==e){const t=this.value;this.value=this.wrapObjValue(e),await this.trigger(t)}}watch(e){this.listeners.push(e)}unwatch(e){this.listeners=this.listeners.filter((t=>t!==e))}trigger(e=null){const s=this.listeners.slice();return this.debounce(t.REACTIVE_DEBOUNCE_MILLIS,(()=>Promise.all(s.map((t=>t(this.value,e)))).then((()=>{}))))}}t.ReactiveProxy=i;class a extends i{static from(e,...t){return e instanceof i?e:new a(e,...t)}watch(e){}trigger(e){return Promise.resolve()}}function n(e,t=(()=>{})){const s=Array.from(e.entries()).map((([e])=>e)),r=Object.fromEntries(s.map((e=>[e,void 0])));return new Proxy(Object.assign({},e,r),{get:(s,r,i)=>"string"==typeof r&&e.has(r)?(t("get",r),e.get(r)):"get"===r?s=>(t("get",s),e.get(s)):Reflect.get(e,r,i),set:(s,r,i,a)=>("string"!=typeof r||r in e?Reflect.set(e,r,i,a):(t("set",r,i),e.set(r,i)),!0)})}t.InertProxy=a,t.ReactiveProxyStore=class extends s{store=new Map;debouncedListeners=new Map;lock=Promise.resolve();constructor(e){super();for(const[t,s]of Object.entries(e||{}))this.store.set(t,i.from(this.wrapFnValue(s)))}wrapFnValue(e){return e&&"function"==typeof e?(...t)=>e.call(n(this),...t):e}get $(){return n(this)}entries(){return this.store.entries()}get(e){return this.store.get(e)?.get()}async set(e,t){this.store.has(e)?await this.store.get(e).set(this.wrapFnValue(t)):this.store.set(e,i.from(this.wrapFnValue(t)))}del(e){return this.store.delete(e)}has(e){return this.store.has(e)}async update(e){await Promise.all(Object.entries(e).map((([e,t])=>this.set(e,t))))}watch(e,s){e=Array.isArray(e)?e:[e];const r=()=>s(...e.map((e=>this.store.get(e).get()))),i=()=>this.debounce(t.REACTIVE_DEBOUNCE_MILLIS,r);e.forEach((e=>this.store.get(e).watch(i))),this.debouncedListeners.set(s,i)}unwatch(e,t){(e=Array.isArray(e)?e:[e]).forEach((e=>this.store.get(e).unwatch(this.debouncedListeners.get(t)))),this.debouncedListeners.delete(t)}async trigger(e){e=Array.isArray(e)?e:[e],await Promise.all(e.map((e=>this.store.get(e).trigger())))}async trace(e){const t=new Set,s=n(this,((e,s)=>{"get"===e&&t.add(s)}));return[await e.call(s),Array.from(t)]}async computed(e,t){const[s,r]=await this.trace(t);this.watch(r,(async()=>this.set(e,await t.call(n(this))))),this.set(e,s)}},t.proxifyStore=n}},t={};function s(r){var i=t[r];if(void 0!==i)return i.exports;var a=t[r]={exports:{}};return e[r](a,a.exports,s),a.exports}(()=>{const e=s(283);class t extends e.IRenderer{dirpath=(0,e.dirname)(self.location.href);parseHTML(e,t={root:!1}){if(t.root)return(new DOMParser).parseFromString(e,"text/html");{const t=document.createRange();return t.selectNodeContents(document.body),t.createContextualFragment(e)}}serializeHTML(e){return(new XMLSerializer).serializeToString(e).replace(/\s?xmlns="[^"]+"/gm,"")}preprocessLocal(e,t){return this.preprocessRemote(e,t)}}const r=new t;self.Mancha=r;const i=self.document?.currentScript;if(self.document?.currentScript?.hasAttribute("init")){r.update({...i?.dataset});const e=i?.hasAttribute("debug"),t=i?.getAttribute("cache");(i?.getAttribute("target")?.split(",")||["body"]).map((async s=>{const i=self.document.querySelector(s);await r.debug(e).mount(i,{cache:t})}))}})()})();
|
package/dist/plugins.d.ts
CHANGED
|
@@ -1,13 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export declare const resolveIncludes: RendererPlugin;
|
|
3
|
-
export declare const rebaseRelativePaths: RendererPlugin;
|
|
4
|
-
export declare const resolveTextNodeExpressions: RendererPlugin;
|
|
5
|
-
export declare const resolveDataAttribute: RendererPlugin;
|
|
6
|
-
export declare const resolveWatchAttribute: RendererPlugin;
|
|
7
|
-
export declare const resolveHtmlAttribute: RendererPlugin;
|
|
8
|
-
export declare const resolvePropAttributes: RendererPlugin;
|
|
9
|
-
export declare const resolveAttrAttributes: RendererPlugin;
|
|
10
|
-
export declare const resolveEventAttributes: RendererPlugin;
|
|
11
|
-
export declare const resolveForAttribute: RendererPlugin;
|
|
12
|
-
export declare const resolveBindAttribute: RendererPlugin;
|
|
13
|
-
export declare const resolveShowAttribute: RendererPlugin;
|
|
1
|
+
export {};
|