mancha 0.4.1 → 0.5.1

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.
@@ -0,0 +1,3 @@
1
+ {
2
+ "recommendations": ["github.copilot"]
3
+ }
@@ -0,0 +1,44 @@
1
+ {
2
+ // Use IntelliSense to learn about possible attributes.
3
+ // Hover to view descriptions of existing attributes.
4
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
+ "version": "0.2.0",
6
+ "configurations": [
7
+ {
8
+ "name": "Mocha All",
9
+ "type": "node",
10
+ "request": "launch",
11
+ "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
12
+ "args": [
13
+ "-r",
14
+ "ts-node/register",
15
+ "--no-timeouts",
16
+ "--colors",
17
+ "${workspaceFolder}/dist/**/*.test.ts"
18
+ ],
19
+ "console": "integratedTerminal",
20
+ "internalConsoleOptions": "neverOpen",
21
+ "skipFiles": [
22
+ "<node_internals>/**/*.js"
23
+ ]
24
+ },
25
+ {
26
+ "name": "Mocha Current File",
27
+ "type": "node",
28
+ "request": "launch",
29
+ "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
30
+ "args": [
31
+ "-r",
32
+ "ts-node/register",
33
+ "--no-timeouts",
34
+ "--colors",
35
+ "${file}"
36
+ ],
37
+ "console": "integratedTerminal",
38
+ "internalConsoleOptions": "neverOpen",
39
+ "skipFiles": [
40
+ "<node_internals>/**/*.js"
41
+ ]
42
+ }
43
+ ]
44
+ }
package/README.md CHANGED
@@ -39,7 +39,7 @@ index.html:
39
39
 
40
40
  ```html
41
41
  <div>
42
- <include src="./hello-world.html" data-name="World"></include>
42
+ <include src="./hello-name.html" data-name="World"></include>
43
43
  </div>
44
44
  ```
45
45
 
@@ -133,7 +133,7 @@ will need to be separately hosted by a static server, although you can also gene
133
133
  containing HTML on demand.
134
134
 
135
135
  ```js
136
- import { renderRemotePath } from "mancha/dist/web"
136
+ import { renderRemotePath } from "mancha/dist/core"
137
137
 
138
138
  const VARS = {...};
139
139
  const HTML_ROOT = "https://example.com/html";
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Converts from an attribute name to camelCase, e.g. `foo-bar` becomes `fooBar`.
3
+ * @param name attribute name
4
+ * @returns camel-cased attribute name
5
+ */
6
+ export declare function attributeNameToCamelCase(name: string): string;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.attributeNameToCamelCase = void 0;
4
+ /**
5
+ * Converts from an attribute name to camelCase, e.g. `foo-bar` becomes `fooBar`.
6
+ * @param name attribute name
7
+ * @returns camel-cased attribute name
8
+ */
9
+ function attributeNameToCamelCase(name) {
10
+ return name.replace(/-./g, (c) => c[1].toUpperCase());
11
+ }
12
+ exports.attributeNameToCamelCase = attributeNameToCamelCase;
package/dist/browser.d.ts CHANGED
@@ -1,2 +1,10 @@
1
- import * as Mancha from "./web.js";
1
+ import { IRenderer } from "./core";
2
+ import { ParserParams, RenderParams } from "./interfaces";
3
+ declare class RendererImpl extends IRenderer {
4
+ protected readonly dirpath: string;
5
+ parseHTML(content: string, params?: ParserParams): DocumentFragment;
6
+ serializeHTML(root: Node | DocumentFragment): string;
7
+ preprocessLocal(fpath: string, params?: RenderParams & ParserParams): Promise<DocumentFragment>;
8
+ }
9
+ declare const Mancha: RendererImpl;
2
10
  export default Mancha;
package/dist/browser.js CHANGED
@@ -10,21 +10,41 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  var _a, _b, _c, _d;
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- const Mancha = require("./web.js");
13
+ const core_1 = require("./core");
14
+ class RendererImpl extends core_1.IRenderer {
15
+ constructor() {
16
+ super(...arguments);
17
+ this.dirpath = (0, core_1.dirname)(self.location.href);
18
+ }
19
+ parseHTML(content, params = { root: false }) {
20
+ if (params.root) {
21
+ return new DOMParser().parseFromString(content, "text/html");
22
+ }
23
+ else {
24
+ const range = document.createRange();
25
+ range.selectNodeContents(document.body);
26
+ return range.createContextualFragment(content);
27
+ }
28
+ }
29
+ serializeHTML(root) {
30
+ return new XMLSerializer().serializeToString(root).replace(/\s?xmlns="[^"]+"/gm, "");
31
+ }
32
+ preprocessLocal(fpath, params) {
33
+ // In the browser, "local" paths (i.e., relative) can still be fetched.
34
+ return this.preprocessRemote(fpath, params);
35
+ }
36
+ }
37
+ const Mancha = new RendererImpl();
14
38
  self["Mancha"] = Mancha;
15
- if ((_b = (_a = self.document) === null || _a === void 0 ? void 0 : _a.currentScript) === null || _b === void 0 ? void 0 : _b.hasAttribute("init")) {
16
- const vars = Mancha.datasetAttributes(self.document.currentScript.attributes);
17
- const attributes = Array.from(((_c = self.document.currentScript) === null || _c === void 0 ? void 0 : _c.attributes) || []).reduce((dict, attr) => Object.assign(dict, { [attr.name]: attr.value }), {});
18
- const targets = ((_d = attributes["target"]) === null || _d === void 0 ? void 0 : _d.split(",")) || ["body"];
19
- const renderings = targets.map((target) => __awaiter(void 0, void 0, void 0, function* () {
20
- const node = self.document[target];
21
- node.innerHTML = yield Mancha.renderContent(node.innerHTML, vars);
39
+ const currentScript = (_a = self.document) === null || _a === void 0 ? void 0 : _a.currentScript;
40
+ if ((_c = (_b = self.document) === null || _b === void 0 ? void 0 : _b.currentScript) === null || _c === void 0 ? void 0 : _c.hasAttribute("init")) {
41
+ Mancha.update(Object.assign({}, currentScript === null || currentScript === void 0 ? void 0 : currentScript.dataset));
42
+ const debug = currentScript === null || currentScript === void 0 ? void 0 : currentScript.hasAttribute("debug");
43
+ const cachePolicy = currentScript === null || currentScript === void 0 ? void 0 : currentScript.getAttribute("cache");
44
+ const targets = ((_d = currentScript === null || currentScript === void 0 ? void 0 : currentScript.getAttribute("target")) === null || _d === void 0 ? void 0 : _d.split(",")) || ["body"];
45
+ targets.map((target) => __awaiter(void 0, void 0, void 0, function* () {
46
+ const fragment = self.document.querySelector(target);
47
+ yield Mancha.mount(fragment, { cache: cachePolicy, debug });
22
48
  }));
23
- Promise.all(renderings).then(() => {
24
- if (attributes["onrender"]) {
25
- eval(attributes["onrender"]);
26
- }
27
- dispatchEvent(new Event("mancha-render", { bubbles: true }));
28
- });
29
49
  }
30
50
  exports.default = Mancha;
package/dist/cli.js CHANGED
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  const yargs_1 = require("yargs");
5
5
  const helpers_1 = require("yargs/helpers");
6
- const Mancha = require("./index.js");
6
+ const index_1 = require("./index");
7
7
  const fs = require("fs/promises");
8
8
  const args = (0, yargs_1.default)((0, helpers_1.hideBin)(process.argv))
9
9
  .describe("input", "Input HMTL file to render")
@@ -11,11 +11,11 @@ const args = (0, yargs_1.default)((0, helpers_1.hideBin)(process.argv))
11
11
  .describe("vars", "JSON-formatted variables")
12
12
  .demand(["input"])
13
13
  .parse();
14
- Mancha.renderLocalPath(args["input"], JSON.parse(args.vars || "{}")).then((result) => {
14
+ index_1.Mancha.preprocessLocal(args["input"], JSON.parse(args.vars || "{}")).then((result) => {
15
15
  if (!args.output || args.output === "-") {
16
16
  console.log(result + "\n");
17
17
  }
18
18
  else {
19
- return fs.writeFile(args.output, result);
19
+ return fs.writeFile(args.output, index_1.Mancha.serializeHTML(result));
20
20
  }
21
21
  });
package/dist/core.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { ReactiveProxyStore } from "./reactive";
2
+ import { ParserParams, RenderParams } from "./interfaces";
3
+ export declare function traverse(root: Node | DocumentFragment | Document, skip?: Set<Node>): Generator<ChildNode>;
4
+ export declare function dirname(fpath: string): string;
5
+ export declare function isRelativePath(fpath: string): boolean;
6
+ export declare function safeEval(code: string, context: any, args?: {
7
+ [key: string]: any;
8
+ }): Promise<any>;
9
+ export declare abstract class IRenderer extends ReactiveProxyStore {
10
+ protected readonly dirpath: string;
11
+ readonly skipNodes: Set<Node>;
12
+ abstract parseHTML(content: string, params?: ParserParams): DocumentFragment;
13
+ abstract serializeHTML(root: DocumentFragment | Node): string;
14
+ fetchRemote(fpath: string, params?: RenderParams): Promise<string>;
15
+ fetchLocal(fpath: string, params?: RenderParams): Promise<string>;
16
+ preprocessString(content: string, params?: RenderParams & ParserParams): Promise<DocumentFragment>;
17
+ preprocessLocal(fpath: string, params?: RenderParams & ParserParams): Promise<DocumentFragment>;
18
+ preprocessRemote(fpath: string, params?: RenderParams & ParserParams): Promise<DocumentFragment>;
19
+ clone(): IRenderer;
20
+ log(params?: RenderParams, ...args: any[]): void;
21
+ eval(expr: string, args?: {
22
+ [key: string]: any;
23
+ }, params?: RenderParams): Promise<any>;
24
+ preprocessNode(root: Document | DocumentFragment | Node, params?: RenderParams): Promise<void>;
25
+ renderNode(root: Document | DocumentFragment | Node, params?: RenderParams): Promise<void>;
26
+ mount(root: Document | DocumentFragment | Node, params?: RenderParams): Promise<void>;
27
+ }
package/dist/core.js ADDED
@@ -0,0 +1,163 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.IRenderer = exports.safeEval = exports.isRelativePath = exports.dirname = exports.traverse = void 0;
13
+ const reactive_1 = require("./reactive");
14
+ const iterator_1 = require("./iterator");
15
+ const plugins_1 = require("./plugins");
16
+ function* traverse(root, skip = new Set()) {
17
+ const explored = new Set();
18
+ const frontier = Array.from(root.childNodes).filter((node) => !skip.has(node));
19
+ // Also yield the root node.
20
+ yield root;
21
+ while (frontier.length) {
22
+ const node = frontier.pop();
23
+ if (!explored.has(node)) {
24
+ explored.add(node);
25
+ yield node;
26
+ }
27
+ if (node.childNodes) {
28
+ Array.from(node.childNodes)
29
+ .filter((node) => !skip.has(node))
30
+ .forEach((node) => frontier.push(node));
31
+ }
32
+ }
33
+ }
34
+ exports.traverse = traverse;
35
+ function dirname(fpath) {
36
+ if (!fpath.includes("/")) {
37
+ return "";
38
+ }
39
+ else {
40
+ return fpath.split("/").slice(0, -1).join("/");
41
+ }
42
+ }
43
+ exports.dirname = dirname;
44
+ function isRelativePath(fpath) {
45
+ return (!fpath.includes("://") &&
46
+ !fpath.startsWith("/") &&
47
+ !fpath.startsWith("#") &&
48
+ !fpath.startsWith("data:"));
49
+ }
50
+ exports.isRelativePath = isRelativePath;
51
+ function safeEval(code, context, args = {}) {
52
+ const inner = `with (this) { return (async () => (${code}))(); }`;
53
+ return new Function(...Object.keys(args), inner).call(context, ...Object.values(args));
54
+ }
55
+ exports.safeEval = safeEval;
56
+ class IRenderer extends reactive_1.ReactiveProxyStore {
57
+ constructor() {
58
+ super(...arguments);
59
+ this.dirpath = "";
60
+ this.skipNodes = new Set();
61
+ }
62
+ fetchRemote(fpath, params) {
63
+ return __awaiter(this, void 0, void 0, function* () {
64
+ var _a;
65
+ return fetch(fpath, { cache: (_a = params === null || params === void 0 ? void 0 : params.cache) !== null && _a !== void 0 ? _a : "default" }).then((res) => res.text());
66
+ });
67
+ }
68
+ fetchLocal(fpath, params) {
69
+ return __awaiter(this, void 0, void 0, function* () {
70
+ return this.fetchRemote(fpath, params);
71
+ });
72
+ }
73
+ preprocessString(content, params) {
74
+ return __awaiter(this, void 0, void 0, function* () {
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
+ });
80
+ }
81
+ preprocessLocal(fpath, params) {
82
+ return __awaiter(this, void 0, void 0, function* () {
83
+ var _a;
84
+ const content = yield this.fetchLocal(fpath, params);
85
+ return this.preprocessString(content, Object.assign(Object.assign({}, params), { dirpath: dirname(fpath), root: (_a = params === null || params === void 0 ? void 0 : params.root) !== null && _a !== void 0 ? _a : !fpath.endsWith(".tpl.html") }));
86
+ });
87
+ }
88
+ preprocessRemote(fpath, params) {
89
+ return __awaiter(this, void 0, void 0, function* () {
90
+ var _a;
91
+ const cache = (params === null || params === void 0 ? void 0 : params.cache) || "default";
92
+ const content = yield fetch(fpath, { cache }).then((res) => res.text());
93
+ return this.preprocessString(content, Object.assign(Object.assign({}, params), { dirpath: dirname(fpath), root: (_a = params === null || params === void 0 ? void 0 : params.root) !== null && _a !== void 0 ? _a : !fpath.endsWith(".tpl.html") }));
94
+ });
95
+ }
96
+ clone() {
97
+ return new this.constructor(Object.fromEntries(this.store.entries()));
98
+ }
99
+ log(params, ...args) {
100
+ if (params === null || params === void 0 ? void 0 : params.debug)
101
+ console.debug(...args);
102
+ }
103
+ eval(expr_1) {
104
+ return __awaiter(this, arguments, void 0, function* (expr, args = {}, params) {
105
+ const proxy = (0, reactive_1.proxify)(this);
106
+ const result = yield safeEval(expr, proxy, Object.assign({}, args));
107
+ this.log(params, `eval \`${expr}\` => `, result);
108
+ return result;
109
+ });
110
+ }
111
+ preprocessNode(root, params) {
112
+ return __awaiter(this, void 0, void 0, function* () {
113
+ params = Object.assign({ dirpath: this.dirpath, maxdepth: 10 }, params);
114
+ const promises = new iterator_1.Iterator(traverse(root, this.skipNodes)).map((node) => __awaiter(this, void 0, void 0, function* () {
115
+ this.log(params, "Preprocessing node:\n", node);
116
+ // Resolve all the includes in the node.
117
+ yield plugins_1.resolveIncludes.call(this, node, params);
118
+ // Resolve all the relative paths in the node.
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());
123
+ });
124
+ }
125
+ renderNode(root, params) {
126
+ return __awaiter(this, void 0, void 0, function* () {
127
+ // Iterate over all the nodes and apply appropriate handlers.
128
+ // Do these steps one at a time to avoid any potential race conditions.
129
+ for (const node of traverse(root, this.skipNodes)) {
130
+ this.log(params, "Rendering node:\n", node);
131
+ // Resolve the :data attribute in the node.
132
+ yield plugins_1.resolveDataAttribute.call(this, node, params);
133
+ // Resolve the :for attribute in the node.
134
+ yield plugins_1.resolveForAttribute.call(this, node, params);
135
+ // Resolve the $html attribute in the node.
136
+ yield plugins_1.resolveHtmlAttribute.call(this, node, params);
137
+ // Resolve the :show attribute in the node.
138
+ yield plugins_1.resolveShowAttribute.call(this, node, params);
139
+ // Resolve the @watch attribute in the node.
140
+ yield plugins_1.resolveWatchAttribute.call(this, node, params);
141
+ // Resolve the :bind attribute in the node.
142
+ yield plugins_1.resolveBindAttribute.call(this, node, params);
143
+ // Resolve all $attributes in the node.
144
+ yield plugins_1.resolvePropAttributes.call(this, node, params);
145
+ // Resolve all :attributes in the node.
146
+ yield plugins_1.resolveAttrAttributes.call(this, node, params);
147
+ // Resolve all @attributes in the node.
148
+ yield plugins_1.resolveEventAttributes.call(this, node, params);
149
+ // Replace all the {{ variables }} in the text.
150
+ yield plugins_1.resolveTextNodeExpressions.call(this, node, params);
151
+ }
152
+ });
153
+ }
154
+ mount(root, params) {
155
+ return __awaiter(this, void 0, void 0, function* () {
156
+ // Preprocess all the elements recursively first.
157
+ yield this.preprocessNode(root, params);
158
+ // Now that the DOM is complete, render all the nodes.
159
+ yield this.renderNode(root, params);
160
+ });
161
+ }
162
+ }
163
+ exports.IRenderer = IRenderer;
package/dist/gulp.d.ts CHANGED
@@ -3,13 +3,13 @@ import * as stream from "stream";
3
3
  /**
4
4
  * Main entrypoint to be used in Gulp. Usage:
5
5
  *
6
- * var mancha = require('gulp-mancha')
6
+ * var mancha = require('mancha/dist/gulp')
7
7
  * gulp.src(...).pipe(mancha({myvar: myval})).pipe(...)
8
8
  *
9
- * @param vars <key, value> pairs of literal string replacements. `key` will become `{{key}}` before
10
- * replacing it with `value` in the processed files.
9
+ * @param context <key, value> pairs of literal string replacements. `key` will become `{{ key }}`
10
+ * before replacing it with `value` in the processed files.
11
11
  */
12
- declare function mancha(vars?: {
12
+ declare function mancha(context?: {
13
13
  [key: string]: string;
14
14
  }, wwwroot?: string): stream.Transform;
15
15
  export default mancha;
package/dist/gulp.js CHANGED
@@ -1,61 +1,75 @@
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
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
12
  const path = require("path");
4
13
  const stream = require("stream");
5
14
  const through = require("through2");
6
- const Mancha = require("./index.js");
15
+ const index_1 = require("./index");
7
16
  /**
8
17
  * Main entrypoint to be used in Gulp. Usage:
9
18
  *
10
- * var mancha = require('gulp-mancha')
19
+ * var mancha = require('mancha/dist/gulp')
11
20
  * gulp.src(...).pipe(mancha({myvar: myval})).pipe(...)
12
21
  *
13
- * @param vars <key, value> pairs of literal string replacements. `key` will become `{{key}}` before
14
- * replacing it with `value` in the processed files.
22
+ * @param context <key, value> pairs of literal string replacements. `key` will become `{{ key }}`
23
+ * before replacing it with `value` in the processed files.
15
24
  */
16
- function mancha(vars = {}, wwwroot = process.cwd()) {
25
+ function mancha(context = {}, wwwroot = process.cwd()) {
26
+ const renderer = new index_1.RendererImpl(context);
17
27
  return through.obj(function (file, encoding, callback) {
18
28
  const catcher = (err) => {
19
29
  console.log(err);
20
30
  callback(err, file);
21
31
  };
22
- const fsroot = path.dirname(file.path);
23
- const relpath = path.relative(file.path, wwwroot) || ".";
24
- const newvars = Object.assign(vars, { wwwroot: relpath });
32
+ const dirpath = path.dirname(file.path);
25
33
  if (file.isNull()) {
26
34
  callback(null, file);
27
35
  }
28
36
  else {
29
37
  if (file.isBuffer()) {
30
- const fragment = file.contents.toString(encoding);
31
- Mancha.renderContent(fragment, newvars, fsroot)
32
- .then((content) => {
38
+ const chunk = file.contents.toString(encoding);
39
+ renderer
40
+ .preprocessString(chunk, { dirpath, root: !file.path.endsWith(".tpl.html") })
41
+ .then((fragment) => __awaiter(this, void 0, void 0, function* () {
42
+ yield renderer.renderNode(fragment);
43
+ const content = renderer.serializeHTML(fragment);
33
44
  file.contents = Buffer.from(content, encoding);
34
45
  callback(null, file);
35
- })
46
+ }))
36
47
  .catch(catcher);
37
48
  }
38
49
  else if (file.isStream()) {
39
- let fragment = "";
50
+ let docstr = "";
40
51
  file.contents
41
52
  .on("data", (chunk) => {
42
53
  if (Buffer.isBuffer(chunk)) {
43
- fragment += chunk.toString(encoding);
54
+ docstr += chunk.toString(encoding);
44
55
  }
45
56
  else {
46
- fragment += chunk.toString();
57
+ docstr += chunk.toString();
47
58
  }
48
59
  })
49
60
  .on("end", () => {
50
- Mancha.renderContent(fragment, newvars, fsroot)
51
- .then((content) => {
61
+ renderer
62
+ .preprocessString(docstr, { dirpath, root: !file.path.endsWith(".tpl.html") })
63
+ .then((document) => __awaiter(this, void 0, void 0, function* () {
64
+ yield renderer.renderNode(document);
65
+ const content = renderer.serializeHTML(document);
52
66
  const readable = new stream.Readable();
53
67
  readable._read = function () { };
54
68
  readable.push(content);
55
69
  readable.push(null);
56
70
  file.contents = readable;
57
71
  callback(null, file);
58
- })
72
+ }))
59
73
  .catch(catcher);
60
74
  });
61
75
  }
package/dist/index.d.ts CHANGED
@@ -1,8 +1,7 @@
1
- /// <reference types="node" />
2
- export declare function renderLocalPath(fpath: string, vars?: {
3
- [key: string]: string;
4
- }, encoding?: BufferEncoding): Promise<string>;
5
- export declare function renderContent(content: string, vars?: {
6
- [key: string]: string;
7
- }, fsroot?: string | null, maxdepth?: number): Promise<string>;
8
- export { preprocess, folderPath, resolvePath, renderRemotePath, encodeHtmlAttrib, decodeHtmlAttrib, } from "./web";
1
+ import { RendererImpl as WorkerRendererImpl } from "./worker";
2
+ import { ParserParams, RenderParams } from "./interfaces";
3
+ /** The Node Mancha renderer is just like the worker renderer, but it also uses the filesystem. */
4
+ export declare class RendererImpl extends WorkerRendererImpl {
5
+ fetchLocal(fpath: string, params?: RenderParams & ParserParams): Promise<string>;
6
+ }
7
+ export declare const Mancha: RendererImpl;
package/dist/index.js CHANGED
@@ -9,28 +9,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.decodeHtmlAttrib = exports.encodeHtmlAttrib = exports.renderRemotePath = exports.resolvePath = exports.folderPath = exports.preprocess = exports.renderContent = exports.renderLocalPath = void 0;
12
+ exports.Mancha = exports.RendererImpl = void 0;
13
13
  const fs = require("fs/promises");
14
- const web_1 = require("./web");
15
- function renderLocalPath(fpath, vars = {}, encoding = "utf8") {
16
- return __awaiter(this, void 0, void 0, function* () {
17
- const content = yield fs.readFile(fpath, { encoding: encoding });
18
- return renderContent(content, vars, (0, web_1.folderPath)(fpath));
19
- });
20
- }
21
- exports.renderLocalPath = renderLocalPath;
22
- function renderContent(content, vars = {}, fsroot = null, maxdepth = 10) {
23
- return __awaiter(this, void 0, void 0, function* () {
24
- fsroot = fsroot || ".";
25
- return (0, web_1.renderContent)(content, vars, fsroot, maxdepth, renderLocalPath);
26
- });
14
+ const worker_1 = require("./worker");
15
+ /** The Node Mancha renderer is just like the worker renderer, but it also uses the filesystem. */
16
+ class RendererImpl extends worker_1.RendererImpl {
17
+ fetchLocal(fpath, params) {
18
+ return __awaiter(this, void 0, void 0, function* () {
19
+ return fs.readFile(fpath, { encoding: (params === null || params === void 0 ? void 0 : params.encoding) || "utf8" });
20
+ });
21
+ }
27
22
  }
28
- exports.renderContent = renderContent;
29
- // Re-exports from web.
30
- var web_2 = require("./web");
31
- Object.defineProperty(exports, "preprocess", { enumerable: true, get: function () { return web_2.preprocess; } });
32
- Object.defineProperty(exports, "folderPath", { enumerable: true, get: function () { return web_2.folderPath; } });
33
- Object.defineProperty(exports, "resolvePath", { enumerable: true, get: function () { return web_2.resolvePath; } });
34
- Object.defineProperty(exports, "renderRemotePath", { enumerable: true, get: function () { return web_2.renderRemotePath; } });
35
- Object.defineProperty(exports, "encodeHtmlAttrib", { enumerable: true, get: function () { return web_2.encodeHtmlAttrib; } });
36
- Object.defineProperty(exports, "decodeHtmlAttrib", { enumerable: true, get: function () { return web_2.decodeHtmlAttrib; } });
23
+ exports.RendererImpl = RendererImpl;
24
+ // Export the renderer instance directly.
25
+ exports.Mancha = new RendererImpl();
@@ -0,0 +1,20 @@
1
+ /// <reference types="node" />
2
+ import { IRenderer } from "./core";
3
+ export interface ParserParams {
4
+ /** Whether the file parsed is a root document, or a document fragment. */
5
+ root?: boolean;
6
+ /** Encoding to use when processing local files. */
7
+ encoding?: BufferEncoding;
8
+ }
9
+ /** The RendererParams interface defines the parameters that can be passed to the renderer. */
10
+ export interface RenderParams {
11
+ /** The current directory of the file being rendered. */
12
+ dirpath?: string;
13
+ /** Maximum level of recursion allowed when resolving includes. */
14
+ maxdepth?: number;
15
+ /** Cache policy used when resolving remote paths. */
16
+ cache?: RequestCache | null;
17
+ /** Whether to print debug information. */
18
+ debug?: boolean;
19
+ }
20
+ export type RendererPlugin = (this: IRenderer, node: ChildNode, params: RenderParams) => Promise<void>;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,10 @@
1
+ export declare class Iterator<T> {
2
+ private readonly iterable;
3
+ constructor(iter: Iterable<T>);
4
+ filter(fn: (val: T) => boolean): Iterator<T>;
5
+ map<S>(fn: (val: T) => S): Iterator<S>;
6
+ array(): T[];
7
+ generator(): Iterable<T>;
8
+ static filterGenerator<T>(fn: (val: T) => boolean, iter: Iterable<T>): Iterable<T>;
9
+ static mapGenerator<T, S>(fn: (val: T) => S, iter: Iterable<T>): Iterable<S>;
10
+ }
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Iterator = void 0;
4
+ class Iterator {
5
+ constructor(iter) {
6
+ this.iterable = iter;
7
+ }
8
+ filter(fn) {
9
+ return new Iterator(Iterator.filterGenerator(fn, this.iterable));
10
+ }
11
+ map(fn) {
12
+ return new Iterator(Iterator.mapGenerator(fn, this.iterable));
13
+ }
14
+ array() {
15
+ return Array.from(this.iterable);
16
+ }
17
+ *generator() {
18
+ for (const val of this.iterable) {
19
+ yield val;
20
+ }
21
+ }
22
+ static *filterGenerator(fn, iter) {
23
+ for (const val of iter) {
24
+ if (fn(val))
25
+ yield val;
26
+ }
27
+ }
28
+ static *mapGenerator(fn, iter) {
29
+ for (const val of iter) {
30
+ yield fn(val);
31
+ }
32
+ }
33
+ }
34
+ exports.Iterator = Iterator;