From 6dc1af706211148a4c8eb39b60f42463caafc68c Mon Sep 17 00:00:00 2001 From: v1rtl Date: Tue, 25 May 2021 21:07:44 +0300 Subject: [PATCH] Revert "chore: remove deno_dist" This reverts commit 18bd212ddadf2229f5cac5e7177fb766b9465f1d. --- deno_dist/LICENSE | 7 + deno_dist/README.md | 281 +++++++++++++++++++++++++++++++ deno_dist/browser.ts | 11 ++ deno_dist/compile-string.ts | 114 +++++++++++++ deno_dist/compile.ts | 69 ++++++++ deno_dist/config.ts | 177 ++++++++++++++++++++ deno_dist/containers.ts | 17 ++ deno_dist/err.ts | 56 +++++++ deno_dist/file-handlers.ts | 325 ++++++++++++++++++++++++++++++++++++ deno_dist/file-helpers.ts | 24 +++ deno_dist/file-methods.ts | 4 + deno_dist/file-utils.ts | 199 ++++++++++++++++++++++ deno_dist/mod.ts | 27 +++ deno_dist/parse.ts | 209 +++++++++++++++++++++++ deno_dist/polyfills.ts | 13 ++ deno_dist/render.ts | 117 +++++++++++++ deno_dist/storage.ts | 31 ++++ deno_dist/utils.ts | 127 ++++++++++++++ 18 files changed, 1808 insertions(+) create mode 100644 deno_dist/LICENSE create mode 100644 deno_dist/README.md create mode 100644 deno_dist/browser.ts create mode 100644 deno_dist/compile-string.ts create mode 100644 deno_dist/compile.ts create mode 100644 deno_dist/config.ts create mode 100644 deno_dist/containers.ts create mode 100644 deno_dist/err.ts create mode 100644 deno_dist/file-handlers.ts create mode 100644 deno_dist/file-helpers.ts create mode 100644 deno_dist/file-methods.ts create mode 100644 deno_dist/file-utils.ts create mode 100644 deno_dist/mod.ts create mode 100644 deno_dist/parse.ts create mode 100644 deno_dist/polyfills.ts create mode 100644 deno_dist/render.ts create mode 100644 deno_dist/storage.ts create mode 100644 deno_dist/utils.ts diff --git a/deno_dist/LICENSE b/deno_dist/LICENSE new file mode 100644 index 00000000..e30a7e49 --- /dev/null +++ b/deno_dist/LICENSE @@ -0,0 +1,7 @@ +Copyright 2019 Ben Gubler + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deno_dist/README.md b/deno_dist/README.md new file mode 100644 index 00000000..e73a23fc --- /dev/null +++ b/deno_dist/README.md @@ -0,0 +1,281 @@ +

+ +

+ +

eta (η)

+ +

+ Documentation - + Chat - + RunKit Demo - + Playground +

+ + +[logo]: https://img.shields.io/badge/all_contributors-8-orange.svg 'Number of contributors on All-Contributors' + + + + +[![GitHub package.json version (master)](https://img.shields.io/github/package-json/v/eta-dev/eta/master?label=current%20version)](https://www.npmjs.com/package/eta) +[![deno module](https://img.shields.io/badge/deno-module-informational?logo=deno)](https://deno.land/x/eta) +[![Travis](https://img.shields.io/travis/com/eta-dev/eta/master.svg)](https://travis-ci.com/eta-dev/eta) +[![All Contributors][logo]](#contributors-) +[![Coveralls](https://img.shields.io/coveralls/eta-dev/eta.svg)](https://coveralls.io/github/eta-dev/eta) +[![Donate](https://img.shields.io/badge/donate-paypal-blue.svg)](https://paypal.me/bengubler) + + + +**Summary** + +Eta is a lightweight and blazing fast embedded JS templating engine that works inside Node, Deno, and the browser. Created by the developers of [Squirrelly](https://squirrelly.js.org), it's written in TypeScript and emphasizes phenomenal performance, configurability, and low bundle size. + +### 🌟 Features + +- 📦 0 dependencies +- 💡 2.3KB minzipped; size restricted to <3KB forever with [size-limit](https://github.com/ai/size-limit) +- ⚡️ Written in TypeScript +- ✨ Deno support (+ Node and browser) +- 🚀 Super Fast + - Check out [these benchmarks](https://ghcdn.rawgit.org/eta-dev/eta/master/browser-tests/benchmark.html) +- 🔧 Configurable + - Plugins, custom delimiters, caching +- 🔨 Powerful + - Precompilation, partials, async + - **Layout support**! + - ExpressJS support out-of-the-box +- 🔥 Reliable + - Better quotes/comments support + - _ex._ `<%= someval + "string %>" %>` compiles correctly, while it fails with doT or EJS + - Great error reporting +- ⚡️ Exports ES Modules as well as UMD +- 📝 Easy template syntax + +## Eta vs other template engines + +
+ + Eta vs EJS + + +Eta's syntax is very similar to EJS' (most templates should work with either engine), Eta has a similar API, and Eta and EJS share the same file-handling logic. Here are the differences between Eta and EJS: + +- Eta is more lightweight. Eta weighs less than **2.5KB gzipped**, while EJS is **4.4KB gzipped** +- Eta compiles and renders templates **_much_ faster than EJS**. Check out these benchmarks: https://ghcdn.rawgit.org/eta-dev/eta/master/browser-tests/benchmark.html +- Eta allows left whitespace control (with `-`), something that doesn't work in EJS because EJS uses `-` on the left side to indicate that the value shouldn't be escaped. Instead, Eta uses `~` to output a raw value +- Eta gives you more flexibility with delimeters -- you could set them to `{{` and `}}`, for example, while with EJS this isn't possible +- Eta adds plugin support +- Comments in Eta use `/* ... */` which allows commenting around template tags +- Eta parses strings correctly. _Example: `<%= "%>" %>` works in Eta, while it breaks in EJS_ +- Eta exposes Typescript types and distributes a UMD build +- Eta supports custom tag-type indicators. _Example: you could change `<%=` to `<%*`_ + +
+ +
+ + Eta vs doT.js + + +Eta and doT.js both allow embedded JavaScript, and [both have best-in-class performance](https://ghcdn.rawgit.org/eta-dev/eta/master/browser-tests/benchmark.html) when compared to other template engines (though Eta is slightly faster with HTML-escaped templates). Here are some of the differences between Eta and doT.js: + +- Eta allows you to control how you strip preceding and trailing whitespace after tags. +- It's much simpler to set custom delimiters with Eta than doT -- you don't have to rewrite every configuration Regular Expression +- Eta supports plugins +- Eta supports async +- Eta parses strings and multi-line comments correctly. _Example: `<%= "%>" %>` works in Eta, while the equivalent breaks in doT_ +- Eta exposes Typescript types and distributes a UMD build +- Eta supports runtime partials and file-handling. + +
+ +
+ + Eta vs Handlebars + + +Eta and Handlebars are very different in some ways -- Eta is an embedded template engine, while Handlebars is a logic-less template engine. Here some additional differences between Eta and Handlebars: + +- Eta is more lightweight. Eta weighs less than **2.5KB gzipped**, while Handlebars is **~22KB gzipped** +- Eta compiles and renders templates **_much_ faster than Handlebars** -- around **7x faster**. Check out these benchmarks: https://ghcdn.rawgit.org/eta-dev/eta/master/browser-tests/benchmark.html +- Eta allows you to set custom delimiters +- Eta supports plugins +- Eta exposes Typescript types and distributes a UMD build +- Custom tag-type indicators. _Example: you could change `<%=` to `<%*`_ +- With Eta, you don't need to register tons of helpers to do simple tasks like check if one value equals another value +- Note that Eta templates run as **trusted code** -- just like any other JavaScript you write.

If you are running user-defined/created templates on your machine, server, site, etc., you probably should go with a tool built for that purpose, like Handlebars. + +
+ +
+ + Eta vs ES6 Template Literals + + +Template literals are a super useful tool, especially for shortening simple string concatenation. But writing complete templates using template literals can quickly get out of hand. Here's a comparison of Eta and template literals: + +- Eta compiles templates into JavaScript functions that use string concatenation and have comparable performance with template literals +- Eta lets you control preceding and trailing whitespace around tags +- Eta gives you more flexibility with delimeters -- you could set them to `{{` and `}}`, for example, or set them to `${` and `}` to mimic template literals +- Eta supports plugins +- Eta supports comments with `/* ... */` syntax, just like in regular JavaScript. Template literals require you to stick a blank string after the comment: `/* ... */""`, which is much less readable +- To write conditionals inside template literals, you have to use the ternary operator. Add more conditions or nested conditionals, and it quickly becomes a nightmarish mess of `? ... : ... ? ... : ...`. Writing conditionals in Eta is much simpler and more readable +- Eta supports partials + +
+ +## Why Eta? + +Simply put, Eta is super: super lightweight, super fast, super powerful, and super simple. Like with EJS, you don't have to worry about learning an entire new templating syntax. Just write JavaScript inside your templates. + +### Where did Eta's name come from? + +"Eta" means tiny in Esperanto. Plus, it can be used as an acronym for all sorts of cool phrases: "ECMAScript Template Awesomeness", "Embedded Templating Alternative", etc.... + +Additionally, Eta is a letter of the Greek alphabet (it stands for all sorts of cool things in various mathematical fields, including efficiency) and is three letters long (perfect for a file extension). + +## Integrations + +
+ + Visual Studio Code + + + [@shadowtime2000](https://github.com/shadowtime2000) created [eta-vscode](https://marketplace.visualstudio.com/items?itemName=shadowtime2000.eta-vscode). + +
+ +
+ + ESLint + + + [eslint-plugin-eta](https://github.com/eta-dev/eslint-plugin-eta) was created to provide an ESLint processor so you can lint your Eta templates. + +
+ +
+ + CLI + + + An official Eta CLI exists called [etajs-cli](https://github.com/eta-dev/etajs-cli). + +
+ +
+ + Webpack + + + Currently there is no official Webpack integration but [@clshortfuse](https://github.com/clshortfuse) shared the loader he uses: + ```javascript + { + loader: 'html-loader', + options: { + preprocessor(content, loaderContext) { + return eta.render(content, {}, { filename: loaderContext.resourcePath }); + }, + }, + } + ``` + +
+ +## 📜 Docs + +We know nobody reads through the long and boring documentation in the ReadMe anyway, so head over to the documentation website: + +📝 [https://eta.js.org](https://eta.js.org) + +## 📓 Examples + +### Simple Template + +```javascript +import * as Eta from 'eta'; +var myTemplate = '

My favorite kind of cake is: <%= it.favoriteCake %>

' + +Eta.render(myTemplate, { favoriteCake: 'Chocolate!' }) +// Returns: '

My favorite kind of cake is: Chocolate!

' +``` + +### Conditionals + +```ejs +<% if(it.somevalue === 1) { %> +Display this +<% } else { %> +Display this instead +<% } %> +``` + +### Loops + +```ejs + +``` + +### Partials + +```ejs +<%~ include('mypartial') %> +``` + +```ejs +<%~ includeFile('./footer') %> +``` + +```ejs +<%~ include('users', {users: it.users}) %> +``` + +## ✔️ Tests + +Tests can be run with `npm test`. Multiple tests check that parsing, rendering, and compiling return expected results, formatting follows guidelines, and code coverage is at the expected level. + +## Resources + +To be added + +## Projects using `eta` + +- [Docusaurus v2](https://v2.docusaurus.io): open-source documentation framework that uses Eta to generate a SSR build +- [Add yours!](https://github.com/eta-dev/eta/edit/master/README.md) + +## Contributors + +Made with ❤ by [@nebrelbug](https://github.com/eta-dev) and all these wonderful contributors ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): + + + + + + + + + + + + + + + + + +

Ben Gubler

💻 💬 📖 ⚠️

Clite Tailor

🤔 💻

Ioan CHIRIAC

💻 🤔

Craig Morten

💻

Rajan Tiwari

💡

shadowtime2000

💻 🤔 ⚠️

Hamza Hamidi

📖

Calum Knott

🤔
+ + + + + +This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! + +## Credits + +- Async support and file handling were added based on code from [EJS](https://github.com/mde/ejs), which is licensed under the Apache-2.0 license. Code was modified and refactored to some extent. +- Syntax and some parts of compilation are heavily based off EJS, Nunjucks, and doT. diff --git a/deno_dist/browser.ts b/deno_dist/browser.ts new file mode 100644 index 00000000..e4fa475c --- /dev/null +++ b/deno_dist/browser.ts @@ -0,0 +1,11 @@ +export { default as compileToString } from "./compile-string.ts"; +export { default as compile } from "./compile.ts"; +export { default as parse } from "./parse.ts"; +export { default as render, renderAsync } from "./render.ts"; +export { templates } from "./containers.ts"; +export { + config, + config as defaultConfig, + configure, + getConfig, +} from "./config.ts"; diff --git a/deno_dist/compile-string.ts b/deno_dist/compile-string.ts new file mode 100644 index 00000000..5aa2674b --- /dev/null +++ b/deno_dist/compile-string.ts @@ -0,0 +1,114 @@ +import Parse from "./parse.ts"; + +/* TYPES */ + +import type { EtaConfig } from "./config.ts"; +import type { AstObject } from "./parse.ts"; + +/* END TYPES */ + +/** + * Compiles a template string to a function string. Most often users just use `compile()`, which calls `compileToString` and creates a new function using the result + * + * **Example** + * + * ```js + * compileToString("Hi <%= it.user %>", eta.config) + * // "var tR='',include=E.include.bind(E),includeFile=E.includeFile.bind(E);tR+='Hi ';tR+=E.e(it.user);if(cb){cb(null,tR)} return tR" + * ``` + */ + +export default function compileToString( + str: string, + config: EtaConfig, +): string { + const buffer: Array = Parse(str, config); + + let res = "var tR='',__l,__lP" + + (config.include ? ",include=E.include.bind(E)" : "") + + (config.includeFile ? ",includeFile=E.includeFile.bind(E)" : "") + + "\nfunction layout(p,d){__l=p;__lP=d}\n" + + (config.useWith ? "with(" + config.varName + "||{}){" : "") + + compileScope(buffer, config) + + (config.includeFile + ? "if(__l)tR=" + + (config.async ? "await " : "") + + `includeFile(__l,Object.assign(${config.varName},{body:tR},__lP))\n` + : config.include + ? "if(__l)tR=" + + (config.async ? "await " : "") + + `include(__l,Object.assign(${config.varName},{body:tR},__lP))\n` + : "") + + "if(cb){cb(null,tR)} return tR" + + (config.useWith ? "}" : ""); + + if (config.plugins) { + for (let i = 0; i < config.plugins.length; i++) { + const plugin = config.plugins[i]; + if (plugin.processFnString) { + res = plugin.processFnString(res, config); + } + } + } + + return res; +} + +/** + * Loops through the AST generated by `parse` and transform each item into JS calls + * + * **Example** + * + * ```js + * // AST version of 'Hi <%= it.user %>' + * let templateAST = ['Hi ', { val: 'it.user', t: 'i' }] + * compileScope(templateAST, eta.config) + * // "tR+='Hi ';tR+=E.e(it.user);" + * ``` + */ + +function compileScope(buff: Array, config: EtaConfig) { + let i = 0; + const buffLength = buff.length; + let returnStr = ""; + + for (i; i < buffLength; i++) { + const currentBlock = buff[i]; + if (typeof currentBlock === "string") { + const str = currentBlock; + + // we know string exists + returnStr += "tR+='" + str + "'\n"; + } else { + const type = currentBlock.t; // ~, s, !, ?, r + let content = currentBlock.val || ""; + + if (type === "r") { + // raw + + if (config.filter) { + content = "E.filter(" + content + ")"; + } + + returnStr += "tR+=" + content + "\n"; + } else if (type === "i") { + // interpolate + + if (config.filter) { + content = "E.filter(" + content + ")"; + } + + if (config.autoEscape) { + content = "E.e(" + content + ")"; + } + returnStr += "tR+=" + content + "\n"; + // reference + } else if (type === "e") { + // execute + returnStr += content + "\n"; // you need a \n in case you have <% } %> + } + } + } + + return returnStr; +} diff --git a/deno_dist/compile.ts b/deno_dist/compile.ts new file mode 100644 index 00000000..9bee022c --- /dev/null +++ b/deno_dist/compile.ts @@ -0,0 +1,69 @@ +import compileToString from "./compile-string.ts"; +import { getConfig } from "./config.ts"; +import EtaErr from "./err.ts"; + +/* TYPES */ + +import type { EtaConfig, PartialConfig } from "./config.ts"; +import type { CallbackFn } from "./file-handlers.ts"; +import { getAsyncFunctionConstructor } from "./polyfills.ts"; +export type TemplateFunction = ( + data: object, + config: EtaConfig, + cb?: CallbackFn, +) => string; + +/* END TYPES */ + +/** + * Takes a template string and returns a template function that can be called with (data, config, [cb]) + * + * @param str - The template string + * @param config - A custom configuration object (optional) + * + * **Example** + * + * ```js + * let compiledFn = eta.compile("Hi <%= it.user %>") + * // function anonymous() + * let compiledFnStr = compiledFn.toString() + * // "function anonymous(it,E,cb\n) {\nvar tR='',include=E.include.bind(E),includeFile=E.includeFile.bind(E);tR+='Hi ';tR+=E.e(it.user);if(cb){cb(null,tR)} return tR\n}" + * ``` + */ + +export default function compile( + str: string, + config?: PartialConfig, +): TemplateFunction { + const options: EtaConfig = getConfig(config || {}); + + /* ASYNC HANDLING */ + // The below code is modified from mde/ejs. All credit should go to them. + const ctor = options.async + ? (getAsyncFunctionConstructor() as FunctionConstructor) + : Function; + /* END ASYNC HANDLING */ + + try { + return new ctor( + options.varName, + "E", // EtaConfig + "cb", // optional callback + compileToString(str, options), + ) as TemplateFunction; // eslint-disable-line no-new-func + } catch (e) { + if (e instanceof SyntaxError) { + throw EtaErr( + "Bad template syntax\n\n" + + e.message + + "\n" + + Array(e.message.length + 1).join("=") + + "\n" + + compileToString(str, options) + + "\n", // This will put an extra newline before the callstack for extra readability + ); + } else { + throw e; + } + } +} diff --git a/deno_dist/config.ts b/deno_dist/config.ts new file mode 100644 index 00000000..a75cd647 --- /dev/null +++ b/deno_dist/config.ts @@ -0,0 +1,177 @@ +import { templates } from "./containers.ts"; +import { copyProps, XMLEscape } from "./utils.ts"; +import EtaErr from "./err.ts"; + +/* TYPES */ + +import type { TemplateFunction } from "./compile.ts"; +import type { Cacher } from "./storage.ts"; + +type trimConfig = "nl" | "slurp" | false; + +export interface EtaConfig { + /** Whether or not to automatically XML-escape interpolations. Default true */ + autoEscape: boolean; + + /** Configure automatic whitespace trimming. Default `[false, 'nl']` */ + autoTrim: trimConfig | [trimConfig, trimConfig]; + + /** Compile to async function */ + async: boolean; + + /** Whether or not to cache templates if `name` or `filename` is passed */ + cache: boolean; + + /** XML-escaping function */ + e: (str: string) => string; + + /** Parsing options */ + parse: { + /** Which prefix to use for evaluation. Default `""` */ + exec: string; + + /** Which prefix to use for interpolation. Default `"="` */ + interpolate: string; + + /** Which prefix to use for raw interpolation. Default `"~"` */ + raw: string; + }; + + /** Array of plugins */ + plugins: Array< + { + processFnString?: Function; + processAST?: Function; + processTemplate?: Function; + } + >; + + /** Remove all safe-to-remove whitespace */ + rmWhitespace: boolean; + + /** Delimiters: by default `['<%', '%>']` */ + tags: [string, string]; + + /** Holds template cache */ + templates: Cacher; + + /** Name of the data object. Default `it` */ + varName: string; + + /** Absolute path to template file */ + filename?: string; + + /** Holds cache of resolved filepaths. Set to `false` to disable */ + filepathCache?: Record | false; + + /** A filter function applied to every interpolation or raw interpolation */ + filter?: Function; + + /** Function to include templates by name */ + include?: Function; + + /** Function to include templates by filepath */ + includeFile?: Function; + + /** Name of template */ + name?: string; + + /** Where should absolute paths begin? Default '/' */ + root?: string; + + /** Make data available on the global object instead of varName */ + useWith?: boolean; + + /** Whether or not to cache templates if `name` or `filename` is passed: duplicate of `cache` */ + "view cache"?: boolean; + + /** Directory or directories that contain templates */ + views?: string | Array; + + [index: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any +} + +export interface EtaConfigWithFilename extends EtaConfig { + filename: string; +} + +export type PartialConfig = Partial; + +/* END TYPES */ + +/** + * Include a template based on its name (or filepath, if it's already been cached). + * + * Called like `include(templateNameOrPath, data)` + */ + +function includeHelper( + this: EtaConfig, + templateNameOrPath: string, + data: object, +): string { + const template = this.templates.get(templateNameOrPath); + if (!template) { + throw EtaErr('Could not fetch template "' + templateNameOrPath + '"'); + } + return template(data, this); +} + +/** Eta's base (global) configuration */ +const config: EtaConfig = { + async: false, + autoEscape: true, + autoTrim: [false, "nl"], + cache: false, + e: XMLEscape, + include: includeHelper, + parse: { + exec: "", + interpolate: "=", + raw: "~", + }, + plugins: [], + rmWhitespace: false, + tags: ["<%", "%>"], + templates: templates, + useWith: false, + varName: "it", +}; + +/** + * Takes one or two partial (not necessarily complete) configuration objects, merges them 1 layer deep into eta.config, and returns the result + * + * @param override Partial configuration object + * @param baseConfig Partial configuration object to merge before `override` + * + * **Example** + * + * ```js + * let customConfig = getConfig({tags: ['!#', '#!']}) + * ``` + */ + +function getConfig(override: PartialConfig, baseConfig?: EtaConfig): EtaConfig { + // TODO: run more tests on this + + const res: PartialConfig = {}; // Linked + copyProps(res, config); // Creates deep clone of eta.config, 1 layer deep + + if (baseConfig) { + copyProps(res, baseConfig); + } + + if (override) { + copyProps(res, override); + } + + return res as EtaConfig; +} + +/** Update Eta's base config */ + +function configure(options: PartialConfig): Partial { + return copyProps(config, options); +} + +export { config, configure, getConfig }; diff --git a/deno_dist/containers.ts b/deno_dist/containers.ts new file mode 100644 index 00000000..51d69738 --- /dev/null +++ b/deno_dist/containers.ts @@ -0,0 +1,17 @@ +import { Cacher } from "./storage.ts"; + +/* TYPES */ + +import type { TemplateFunction } from "./compile.ts"; + +/* END TYPES */ + +/** + * Eta's template storage + * + * Stores partials and cached templates + */ + +const templates = new Cacher({}); + +export { templates }; diff --git a/deno_dist/err.ts b/deno_dist/err.ts new file mode 100644 index 00000000..df2e42bc --- /dev/null +++ b/deno_dist/err.ts @@ -0,0 +1,56 @@ +function setPrototypeOf(obj: any, proto: any) { + // eslint-disable-line @typescript-eslint/no-explicit-any + if (Object.setPrototypeOf) { + Object.setPrototypeOf(obj, proto); + } else { + obj.__proto__ = proto; + } +} + +// This is pretty much the only way to get nice, extended Errors +// without using ES6 + +/** + * This returns a new Error with a custom prototype. Note that it's _not_ a constructor + * + * @param message Error message + * + * **Example** + * + * ```js + * throw EtaErr("template not found") + * ``` + */ + +export default function EtaErr(message: string): Error { + const err = new Error(message); + setPrototypeOf(err, EtaErr.prototype); + return err; +} + +EtaErr.prototype = Object.create(Error.prototype, { + name: { value: "Eta Error", enumerable: false }, +}); + +/** + * Throws an EtaErr with a nicely formatted error and message showing where in the template the error occurred. + */ + +export function ParseErr(message: string, str: string, indx: number): void { + const whitespace = str.slice(0, indx).split(/\n/); + + const lineNo = whitespace.length; + const colNo = whitespace[lineNo - 1].length + 1; + message += " at line " + + lineNo + + " col " + + colNo + + ":\n\n" + + " " + + str.split(/\n/)[lineNo - 1] + + "\n" + + " " + + Array(colNo).join(" ") + + "^"; + throw EtaErr(message); +} diff --git a/deno_dist/file-handlers.ts b/deno_dist/file-handlers.ts new file mode 100644 index 00000000..2eafaecd --- /dev/null +++ b/deno_dist/file-handlers.ts @@ -0,0 +1,325 @@ +// express is set like: app.engine('html', require('eta').renderFile) + +import EtaErr from "./err.ts"; +import compile from "./compile.ts"; +import { getConfig } from "./config.ts"; +import { getPath, readFile } from "./file-utils.ts"; +import { copyProps } from "./utils.ts"; +import { promiseImpl } from "./polyfills.ts"; + +/* TYPES */ + +import type { + EtaConfig, + EtaConfigWithFilename, + PartialConfig, +} from "./config.ts"; +import type { TemplateFunction } from "./compile.ts"; + +export type CallbackFn = (err: Error | null, str?: string) => void; + +interface DataObj { + /** Express.js settings may be stored here */ + settings?: { + [key: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any + }; + [key: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any +} + +interface PartialConfigWithFilename extends Partial { + filename: string; +} + +/* END TYPES */ + +/** + * Reads a template, compiles it into a function, caches it if caching isn't disabled, returns the function + * + * @param filePath Absolute path to template file + * @param options Eta configuration overrides + * @param noCache Optionally, make Eta not cache the template + */ + +export function loadFile( + filePath: string, + options: PartialConfigWithFilename, + noCache?: boolean, +): TemplateFunction { + const config = getConfig(options); + const template = readFile(filePath); + try { + const compiledTemplate = compile(template, config); + if (!noCache) { + config.templates.define( + (config as EtaConfigWithFilename).filename, + compiledTemplate, + ); + } + return compiledTemplate; + } catch (e) { + throw EtaErr("Loading file: " + filePath + " failed:\n\n" + e.message); + } +} + +/** + * Get the template from a string or a file, either compiled on-the-fly or + * read from cache (if enabled), and cache the template if needed. + * + * If `options.cache` is true, this function reads the file from + * `options.filename` so it must be set prior to calling this function. + * + * @param options compilation options + * @return Eta template function + */ + +function handleCache(options: EtaConfigWithFilename): TemplateFunction { + const filename = options.filename; + + if (options.cache) { + const func = options.templates.get(filename); + if (func) { + return func; + } + + return loadFile(filename, options); + } + + // Caching is disabled, so pass noCache = true + return loadFile(filename, options, true); +} + +/** + * Try calling handleCache with the given options and data and call the + * callback with the result. If an error occurs, call the callback with + * the error. Used by renderFile(). + * + * @param data template data + * @param options compilation options + * @param cb callback + */ + +function tryHandleCache( + data: object, + options: EtaConfigWithFilename, + cb: CallbackFn | undefined, +) { + if (cb) { + try { + // Note: if there is an error while rendering the template, + // It will bubble up and be caught here + const templateFn = handleCache(options); + templateFn(data, options, cb); + } catch (err) { + return cb(err); + } + } else { + // No callback, try returning a promise + if (typeof promiseImpl === "function") { + return new promiseImpl( + function (resolve: Function, reject: Function) { + try { + const templateFn = handleCache(options); + const result = templateFn(data, options); + resolve(result); + } catch (err) { + reject(err); + } + }, + ); + } else { + throw EtaErr( + "Please provide a callback function, this env doesn't support Promises", + ); + } + } +} + +/** + * Get the template function. + * + * If `options.cache` is `true`, then the template is cached. + * + * This returns a template function and the config object with which that template function should be called. + * + * @remarks + * + * It's important that this returns a config object with `filename` set. + * Otherwise, the included file would not be able to use relative paths + * + * @param path path for the specified file (if relative, specify `views` on `options`) + * @param options compilation options + * @return [Eta template function, new config object] + */ + +function includeFile( + path: string, + options: EtaConfig, +): [TemplateFunction, EtaConfig] { + // the below creates a new options object, using the parent filepath of the old options object and the path + const newFileOptions = getConfig( + { filename: getPath(path, options) }, + options, + ); + // TODO: make sure properties are currectly copied over + return [handleCache(newFileOptions as EtaConfigWithFilename), newFileOptions]; +} + +/** + * Render a template from a filepath. + * + * @param filepath Path to template file. If relative, specify `views` on the config object + * + * This can take two different function signatures: + * + * - `renderFile(filename, dataAndConfig, [cb])` + * - Eta will merge `dataAndConfig` into `eta.config` + * - `renderFile(filename, data, [config], [cb])` + * + * Note that renderFile does not immediately return the rendered result. If you pass in a callback function, it will be called with `(err, res)`. Otherwise, `renderFile` will return a `Promise` that resolves to the render result. + * + * **Examples** + * + * ```js + * eta.renderFile("./template.eta", data, {cache: true}, function (err, rendered) { + * if (err) console.log(err) + * console.log(rendered) + * }) + * + * let rendered = await eta.renderFile("./template.eta", data, {cache: true}) + * + * let rendered = await eta.renderFile("./template", {...data, cache: true}) + * ``` + */ + +function renderFile( + filename: string, + data: DataObj, + config?: PartialConfig, + cb?: CallbackFn, +): Promise | void; + +function renderFile( + filename: string, + data: DataObj, + cb?: CallbackFn, +): Promise | void; + +function renderFile( + filename: string, + data: DataObj, + config?: PartialConfig, + cb?: CallbackFn, +): Promise | void { + /* + Here we have some function overloading. + Essentially, the first 2 arguments to renderFile should always be the filename and data + However, with Express, configuration options will be passed along with the data. + Thus, Express will call renderFile with (filename, dataAndOptions, cb) + And we want to also make (filename, data, options, cb) available + */ + + let renderConfig: EtaConfigWithFilename; + let callback: CallbackFn | undefined; + data = data || {}; // If data is undefined, we don't want accessing data.settings to error + + // First, assign our callback function to `callback` + // We can leave it undefined if neither parameter is a function; + // Callbacks are optional + if (typeof cb === "function") { + // The 4th argument is the callback + callback = cb; + } else if (typeof config === "function") { + // The 3rd arg is the callback + callback = config; + } + + // If there is a config object passed in explicitly, use it + if (typeof config === "object") { + renderConfig = getConfig( + (config as PartialConfig) || {}, + ) as EtaConfigWithFilename; + } else { + // Otherwise, get the config from the data object + // And then grab some config options from data.settings + // Which is where Express sometimes stores them + renderConfig = getConfig(data as PartialConfig) as EtaConfigWithFilename; + if (data.settings) { + // Pull a few things from known locations + if (data.settings.views) { + renderConfig.views = data.settings.views; + } + if (data.settings["view cache"]) { + renderConfig.cache = true; + } + // Undocumented after Express 2, but still usable, esp. for + // items that are unsafe to be passed along with data, like `root` + const viewOpts = data.settings["view options"]; + + if (viewOpts) { + copyProps(renderConfig, viewOpts); + } + } + } + + // Set the filename option on the template + // This will first try to resolve the file path (see getPath for details) + renderConfig.filename = getPath(filename, renderConfig); + + return tryHandleCache(data, renderConfig, callback); +} + +/** + * Render a template from a filepath asynchronously. + * + * @param filepath Path to template file. If relative, specify `views` on the config object + * + * This can take two different function signatures: + * + * - `renderFile(filename, dataAndConfig, [cb])` + * - Eta will merge `dataAndConfig` into `eta.config` + * - `renderFile(filename, data, [config], [cb])` + * + * Note that renderFile does not immediately return the rendered result. If you pass in a callback function, it will be called with `(err, res)`. Otherwise, `renderFile` will return a `Promise` that resolves to the render result. + * + * **Examples** + * + * ```js + * eta.renderFile("./template.eta", data, {cache: true}, function (err, rendered) { + * if (err) console.log(err) + * console.log(rendered) + * }) + * + * let rendered = await eta.renderFile("./template.eta", data, {cache: true}) + * + * let rendered = await eta.renderFile("./template", {...data, cache: true}) + * ``` + */ + +function renderFileAsync( + filename: string, + data: DataObj, + config?: PartialConfig, + cb?: CallbackFn, +): Promise | void; + +function renderFileAsync( + filename: string, + data: DataObj, + cb?: CallbackFn, +): Promise | void; + +function renderFileAsync( + filename: string, + data: DataObj, + config?: PartialConfig, + cb?: CallbackFn, +): Promise | void { + return renderFile( + filename, + typeof config === "function" ? { ...data, async: true } : data, + typeof config === "object" ? { ...config, async: true } : config, + cb, + ); +} + +export { includeFile, renderFile, renderFileAsync }; diff --git a/deno_dist/file-helpers.ts b/deno_dist/file-helpers.ts new file mode 100644 index 00000000..5c5f984e --- /dev/null +++ b/deno_dist/file-helpers.ts @@ -0,0 +1,24 @@ +import { includeFile } from "./file-handlers.ts"; + +/* TYPES */ + +import type { EtaConfig } from "./config.ts"; + +interface GenericData { + [index: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any +} + +/* END TYPES */ + +/** + * Called with `includeFile(path, data)` + */ + +export function includeFileHelper( + this: EtaConfig, + path: string, + data: GenericData, +): string { + const templateAndConfig = includeFile(path, this); + return templateAndConfig[0](data, templateAndConfig[1]); +} diff --git a/deno_dist/file-methods.ts b/deno_dist/file-methods.ts new file mode 100644 index 00000000..e4bf5c8d --- /dev/null +++ b/deno_dist/file-methods.ts @@ -0,0 +1,4 @@ +export * as fs from "https://deno.land/std@0.97.0/fs/mod.ts"; +export * as path from "https://deno.land/std@0.97.0/path/mod.ts"; + +export const readFileSync = Deno.readTextFileSync; diff --git a/deno_dist/file-utils.ts b/deno_dist/file-utils.ts new file mode 100644 index 00000000..0818cfea --- /dev/null +++ b/deno_dist/file-utils.ts @@ -0,0 +1,199 @@ +import { fs, path, readFileSync } from "./file-methods.ts"; +const _BOM = /^\uFEFF/; + +// express is set like: app.engine('html', require('eta').renderFile) + +import EtaErr from "./err.ts"; + +/* TYPES */ + +import type { EtaConfig } from "./config.ts"; + +/* END TYPES */ + +/** + * Get the path to the included file from the parent file path and the + * specified path. + * + * If `name` does not have an extension, it will default to `.eta` + * + * @param name specified path + * @param parentfile parent file path + * @param isDirectory whether parentfile is a directory + * @return absolute path to template + */ + +function getWholeFilePath( + name: string, + parentfile: string, + isDirectory?: boolean, +): string { + const includePath = path.resolve( + isDirectory ? parentfile : path.dirname(parentfile), // returns directory the parent file is in + name, // file + ) + (path.extname(name) ? "" : ".eta"); + return includePath; +} + +/** + * Get the absolute path to an included template + * + * If this is called with an absolute path (for example, starting with '/' or 'C:\') + * then Eta will attempt to resolve the absolute path within options.views. If it cannot, + * Eta will fallback to options.root or '/' + * + * If this is called with a relative path, Eta will: + * - Look relative to the current template (if the current template has the `filename` property) + * - Look inside each directory in options.views + * + * Note: if Eta is unable to find a template using path and options, it will throw an error. + * + * @param path specified path + * @param options compilation options + * @return absolute path to template + */ + +function getPath(path: string, options: EtaConfig): string { + let includePath: string | false = false; + const views = options.views; + let searchedPaths: Array = []; + + // If these four values are the same, + // getPath() will return the same result every time. + // We can cache the result to avoid expensive + // file operations. + const pathOptions = JSON.stringify({ + filename: options.filename, // filename of the template which called includeFile() + path: path, + root: options.root, + views: options.views, + }); + + if ( + options.cache && options.filepathCache && options.filepathCache[pathOptions] + ) { + // Use the cached filepath + return options.filepathCache[pathOptions]; + } + + /** Add a filepath to the list of paths we've checked for a template */ + function addPathToSearched(pathSearched: string) { + if (!searchedPaths.includes(pathSearched)) { + searchedPaths.push(pathSearched); + } + } + + /** + * Take a filepath (like 'partials/mypartial.eta'). Attempt to find the template file inside `views`; + * return the resulting template file path, or `false` to indicate that the template was not found. + * + * @param views the filepath that holds templates, or an array of filepaths that hold templates + * @param path the path to the template + */ + + function searchViews( + views: Array | string | undefined, + path: string, + ): string | false { + let filePath; + + // If views is an array, then loop through each directory + // And attempt to find the template + if ( + Array.isArray(views) && + views.some(function (v) { + filePath = getWholeFilePath(path, v, true); + + addPathToSearched(filePath); + + return fs.existsSync(filePath); + }) + ) { + // If the above returned true, we know that the filePath was just set to a path + // That exists (Array.some() returns as soon as it finds a valid element) + return (filePath as unknown) as string; + } else if (typeof views === "string") { + // Search for the file if views is a single directory + filePath = getWholeFilePath(path, views, true); + + addPathToSearched(filePath); + + if (fs.existsSync(filePath)) { + return filePath; + } + } + + // Unable to find a file + return false; + } + + // Path starts with '/', 'C:\', etc. + const match = /^[A-Za-z]+:\\|^\//.exec(path); + + // Absolute path, like /partials/partial.eta + if (match && match.length) { + // We have to trim the beginning '/' off the path, or else + // path.resolve(dir, path) will always resolve to just path + const formattedPath = path.replace(/^\/*/, ""); + + // First, try to resolve the path within options.views + includePath = searchViews(views, formattedPath); + if (!includePath) { + // If that fails, searchViews will return false. Try to find the path + // inside options.root (by default '/', the base of the filesystem) + const pathFromRoot = getWholeFilePath( + formattedPath, + options.root || "/", + true, + ); + + addPathToSearched(pathFromRoot); + + includePath = pathFromRoot; + } + } else { + // Relative paths + // Look relative to a passed filename first + if (options.filename) { + const filePath = getWholeFilePath(path, options.filename); + + addPathToSearched(filePath); + + if (fs.existsSync(filePath)) { + includePath = filePath; + } + } + // Then look for the template in options.views + if (!includePath) { + includePath = searchViews(views, path); + } + if (!includePath) { + throw EtaErr( + 'Could not find the template "' + path + '". Paths tried: ' + + searchedPaths, + ); + } + } + + // If caching and filepathCache are enabled, + // cache the input & output of this function. + if (options.cache && options.filepathCache) { + options.filepathCache[pathOptions] = includePath; + } + + return includePath; +} + +/** + * Reads a file synchronously + */ + +function readFile(filePath: string): string { + try { + return readFileSync(filePath).toString().replace(_BOM, ""); // TODO: is replacing BOM's necessary? + } catch { + throw EtaErr("Failed to read template at '" + filePath + "'"); + } +} + +export { getPath, readFile }; diff --git a/deno_dist/mod.ts b/deno_dist/mod.ts new file mode 100644 index 00000000..42ba4f5e --- /dev/null +++ b/deno_dist/mod.ts @@ -0,0 +1,27 @@ +/* Export file stuff */ +import { includeFileHelper } from "./file-helpers.ts"; +import { config } from "./config.ts"; + +config.includeFile = includeFileHelper; +config.filepathCache = {}; + +export { + loadFile, + renderFile, + renderFile as __express, + renderFileAsync, +} from "./file-handlers.ts"; + +/* End file stuff */ + +export { default as compileToString } from "./compile-string.ts"; +export { default as compile } from "./compile.ts"; +export { default as parse } from "./parse.ts"; +export { default as render, renderAsync } from "./render.ts"; +export { templates } from "./containers.ts"; +export { + config, + config as defaultConfig, + configure, + getConfig, +} from "./config.ts"; diff --git a/deno_dist/parse.ts b/deno_dist/parse.ts new file mode 100644 index 00000000..442630cf --- /dev/null +++ b/deno_dist/parse.ts @@ -0,0 +1,209 @@ +import { ParseErr } from "./err.ts"; +import { trimWS } from "./utils.ts"; + +/* TYPES */ + +import type { EtaConfig } from "./config.ts"; + +export type TagType = "r" | "e" | "i" | ""; + +export interface TemplateObject { + t: TagType; + val: string; +} + +export type AstObject = string | TemplateObject; + +/* END TYPES */ + +const templateLitReg = + /`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g; + +const singleQuoteReg = /'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g; + +const doubleQuoteReg = /"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g; + +/** Escape special regular expression characters inside a string */ + +function escapeRegExp(string: string) { + // From MDN + return string.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string +} + +export default function parse( + str: string, + config: EtaConfig, +): Array { + let buffer: Array = []; + let trimLeftOfNextStr: string | false = false; + let lastIndex = 0; + const parseOptions = config.parse; + + if (config.plugins) { + for (let i = 0; i < config.plugins.length; i++) { + const plugin = config.plugins[i]; + if (plugin.processTemplate) { + str = plugin.processTemplate(str, config); + } + } + } + + /* Adding for EJS compatibility */ + if (config.rmWhitespace) { + // Code taken directly from EJS + // Have to use two separate replaces here as `^` and `$` operators don't + // work well with `\r` and empty lines don't work well with the `m` flag. + // Essentially, this replaces the whitespace at the beginning and end of + // each line and removes multiple newlines. + str = str.replace(/[\r\n]+/g, "\n").replace(/^\s+|\s+$/gm, ""); + } + /* End rmWhitespace option */ + + templateLitReg.lastIndex = 0; + singleQuoteReg.lastIndex = 0; + doubleQuoteReg.lastIndex = 0; + + function pushString(strng: string, shouldTrimRightOfString?: string | false) { + if (strng) { + // if string is truthy it must be of type 'string' + + strng = trimWS( + strng, + config, + trimLeftOfNextStr, // this will only be false on the first str, the next ones will be null or undefined + shouldTrimRightOfString, + ); + + if (strng) { + // replace \ with \\, ' with \' + // we're going to convert all CRLF to LF so it doesn't take more than one replace + + strng = strng.replace(/\\|'/g, "\\$&").replace(/\r\n|\n|\r/g, "\\n"); + + buffer.push(strng); + } + } + } + + const prefixes = [ + parseOptions.exec, + parseOptions.interpolate, + parseOptions.raw, + ].reduce(function ( + accumulator, + prefix, + ) { + if (accumulator && prefix) { + return accumulator + "|" + escapeRegExp(prefix); + } else if (prefix) { + // accumulator is falsy + return escapeRegExp(prefix); + } else { + // prefix and accumulator are both falsy + return accumulator; + } + }, ""); + + const parseOpenReg = new RegExp( + "([^]*?)" + escapeRegExp(config.tags[0]) + "(-|_)?\\s*(" + prefixes + + ")?\\s*", + "g", + ); + + const parseCloseReg = new RegExp( + "'|\"|`|\\/\\*|(\\s*(-|_)?" + escapeRegExp(config.tags[1]) + ")", + "g", + ); + // TODO: benchmark having the \s* on either side vs using str.trim() + + let m; + + while ((m = parseOpenReg.exec(str))) { + lastIndex = m[0].length + m.index; + + const precedingString = m[1]; + const wsLeft = m[2]; + const prefix = m[3] || ""; // by default either ~, =, or empty + + pushString(precedingString, wsLeft); + + parseCloseReg.lastIndex = lastIndex; + let closeTag; + let currentObj: AstObject | false = false; + + while ((closeTag = parseCloseReg.exec(str))) { + if (closeTag[1]) { + let content = str.slice(lastIndex, closeTag.index); + + parseOpenReg.lastIndex = lastIndex = parseCloseReg.lastIndex; + + trimLeftOfNextStr = closeTag[2]; + + const currentType: TagType = prefix === parseOptions.exec + ? "e" + : prefix === parseOptions.raw + ? "r" + : prefix === parseOptions.interpolate + ? "i" + : ""; + + currentObj = { t: currentType, val: content }; + break; + } else { + const char = closeTag[0]; + if (char === "/*") { + const commentCloseInd = str.indexOf("*/", parseCloseReg.lastIndex); + + if (commentCloseInd === -1) { + ParseErr("unclosed comment", str, closeTag.index); + } + parseCloseReg.lastIndex = commentCloseInd; + } else if (char === "'") { + singleQuoteReg.lastIndex = closeTag.index; + + const singleQuoteMatch = singleQuoteReg.exec(str); + if (singleQuoteMatch) { + parseCloseReg.lastIndex = singleQuoteReg.lastIndex; + } else { + ParseErr("unclosed string", str, closeTag.index); + } + } else if (char === '"') { + doubleQuoteReg.lastIndex = closeTag.index; + const doubleQuoteMatch = doubleQuoteReg.exec(str); + + if (doubleQuoteMatch) { + parseCloseReg.lastIndex = doubleQuoteReg.lastIndex; + } else { + ParseErr("unclosed string", str, closeTag.index); + } + } else if (char === "`") { + templateLitReg.lastIndex = closeTag.index; + const templateLitMatch = templateLitReg.exec(str); + if (templateLitMatch) { + parseCloseReg.lastIndex = templateLitReg.lastIndex; + } else { + ParseErr("unclosed string", str, closeTag.index); + } + } + } + } + if (currentObj) { + buffer.push(currentObj); + } else { + ParseErr("unclosed tag", str, m.index + precedingString.length); + } + } + + pushString(str.slice(lastIndex, str.length), false); + + if (config.plugins) { + for (let i = 0; i < config.plugins.length; i++) { + const plugin = config.plugins[i]; + if (plugin.processAST) { + buffer = plugin.processAST(buffer, config); + } + } + } + + return buffer; +} diff --git a/deno_dist/polyfills.ts b/deno_dist/polyfills.ts new file mode 100644 index 00000000..2d60c0a9 --- /dev/null +++ b/deno_dist/polyfills.ts @@ -0,0 +1,13 @@ +export const promiseImpl = Promise; + +export function getAsyncFunctionConstructor(): Function { + return async function () {}.constructor; +} + +export function trimLeft(str: string): string { + return str.trimLeft(); +} + +export function trimRight(str: string): string { + return str.trimRight(); +} diff --git a/deno_dist/render.ts b/deno_dist/render.ts new file mode 100644 index 00000000..1e210ed8 --- /dev/null +++ b/deno_dist/render.ts @@ -0,0 +1,117 @@ +import compile from "./compile.ts"; +import { getConfig } from "./config.ts"; +import { promiseImpl } from "./polyfills.ts"; +import EtaErr from "./err.ts"; + +/* TYPES */ + +import type { EtaConfig, PartialConfig } from "./config.ts"; +import type { TemplateFunction } from "./compile.ts"; +import type { CallbackFn } from "./file-handlers.ts"; + +/* END TYPES */ + +function handleCache( + template: string | TemplateFunction, + options: EtaConfig, +): TemplateFunction { + if (options.cache && options.name && options.templates.get(options.name)) { + return options.templates.get(options.name); + } + + const templateFunc = typeof template === "function" + ? template + : compile(template, options); + + // Note that we don't have to check if it already exists in the cache; + // it would have returned earlier if it had + if (options.cache && options.name) { + options.templates.define(options.name, templateFunc); + } + + return templateFunc; +} + +/** + * Render a template + * + * If `template` is a string, Eta will compile it to a function and then call it with the provided data. + * If `template` is a template function, Eta will call it with the provided data. + * + * If `config.async` is `false`, Eta will return the rendered template. + * + * If `config.async` is `true` and there's a callback function, Eta will call the callback with `(err, renderedTemplate)`. + * If `config.async` is `true` and there's not a callback function, Eta will return a Promise that resolves to the rendered template. + * + * If `config.cache` is `true` and `config` has a `name` or `filename` property, Eta will cache the template on the first render and use the cached template for all subsequent renders. + * + * @param template Template string or template function + * @param data Data to render the template with + * @param config Optional config options + * @param cb Callback function + */ + +export default function render( + template: string | TemplateFunction, + data: object, + config?: PartialConfig, + cb?: CallbackFn, +): string | Promise | void { + const options = getConfig(config || {}); + + if (options.async) { + if (cb) { + // If user passes callback + try { + // Note: if there is an error while rendering the template, + // It will bubble up and be caught here + const templateFn = handleCache(template, options); + templateFn(data, options, cb); + } catch (err) { + return cb(err); + } + } else { + // No callback, try returning a promise + if (typeof promiseImpl === "function") { + return new promiseImpl(function (resolve: Function, reject: Function) { + try { + resolve(handleCache(template, options)(data, options)); + } catch (err) { + reject(err); + } + }); + } else { + throw EtaErr( + "Please provide a callback function, this env doesn't support Promises", + ); + } + } + } else { + return handleCache(template, options)(data, options); + } +} + +/** + * Render a template asynchronously + * + * If `template` is a string, Eta will compile it to a function and call it with the provided data. + * If `template` is a function, Eta will call it with the provided data. + * + * If there is a callback function, Eta will call it with `(err, renderedTemplate)`. + * If there is not a callback function, Eta will return a Promise that resolves to the rendered template + * + * @param template Template string or template function + * @param data Data to render the template with + * @param config Optional config options + * @param cb Callback function + */ + +export function renderAsync( + template: string | TemplateFunction, + data: object, + config?: PartialConfig, + cb?: CallbackFn, +): string | Promise | void { + // Using Object.assign to lower bundle size, using spread operator makes it larger because of typescript injected polyfills + return render(template, data, Object.assign({}, config, { async: true }), cb); +} diff --git a/deno_dist/storage.ts b/deno_dist/storage.ts new file mode 100644 index 00000000..118298a7 --- /dev/null +++ b/deno_dist/storage.ts @@ -0,0 +1,31 @@ +import { copyProps } from "./utils.ts"; + +/** + * Handles storage and accessing of values + * + * In this case, we use it to store compiled template functions + * Indexed by their `name` or `filename` + */ +class Cacher { + constructor(private cache: Record) {} + define(key: string, val: T): void { + this.cache[key] = val; + } + get(key: string): T { + // string | array. + // TODO: allow array of keys to look down + // TODO: create plugin to allow referencing helpers, filters with dot notation + return this.cache[key]; + } + remove(key: string): void { + delete this.cache[key]; + } + reset(): void { + this.cache = {}; + } + load(cacheObj: Record): void { + copyProps(this.cache, cacheObj); + } +} + +export { Cacher }; diff --git a/deno_dist/utils.ts b/deno_dist/utils.ts new file mode 100644 index 00000000..9e08b437 --- /dev/null +++ b/deno_dist/utils.ts @@ -0,0 +1,127 @@ +// TODO: allow '-' to trim up until newline. Use [^\S\n\r] instead of \s +// TODO: only include trimLeft polyfill if not in ES6 + +import { trimLeft, trimRight } from "./polyfills.ts"; + +/* TYPES */ + +import type { EtaConfig } from "./config.ts"; + +interface EscapeMap { + "&": "&"; + "<": "<"; + ">": ">"; + '"': """; + "'": "'"; + [index: string]: string; +} + +/* END TYPES */ + +export function hasOwnProp(obj: object, prop: string): boolean { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +export function copyProps(toObj: T, fromObj: T): T { + for (const key in fromObj) { + if (hasOwnProp((fromObj as unknown) as object, key)) { + toObj[key] = fromObj[key]; + } + } + return toObj; +} + +/** + * Takes a string within a template and trims it, based on the preceding tag's whitespace control and `config.autoTrim` + */ + +function trimWS( + str: string, + config: EtaConfig, + wsLeft: string | false, + wsRight?: string | false, +): string { + let leftTrim; + let rightTrim; + + if (Array.isArray(config.autoTrim)) { + // kinda confusing + // but _}} will trim the left side of the following string + leftTrim = config.autoTrim[1]; + rightTrim = config.autoTrim[0]; + } else { + leftTrim = rightTrim = config.autoTrim; + } + + if (wsLeft || wsLeft === false) { + leftTrim = wsLeft; + } + + if (wsRight || wsRight === false) { + rightTrim = wsRight; + } + + if (!rightTrim && !leftTrim) { + return str; + } + + if (leftTrim === "slurp" && rightTrim === "slurp") { + return str.trim(); + } + + if (leftTrim === "_" || leftTrim === "slurp") { + // console.log('trimming left' + leftTrim) + // full slurp + + str = trimLeft(str); + } else if (leftTrim === "-" || leftTrim === "nl") { + // nl trim + str = str.replace(/^(?:\r\n|\n|\r)/, ""); + } + + if (rightTrim === "_" || rightTrim === "slurp") { + // full slurp + str = trimRight(str); + } else if (rightTrim === "-" || rightTrim === "nl") { + // nl trim + str = str.replace(/(?:\r\n|\n|\r)$/, ""); // TODO: make sure this gets \r\n + } + + return str; +} + +/** + * A map of special HTML characters to their XML-escaped equivalents + */ + +const escMap: EscapeMap = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", +}; + +function replaceChar(s: string): string { + return escMap[s]; +} + +/** + * XML-escapes an input value after converting it to a string + * + * @param str - Input value (usually a string) + * @returns XML-escaped string + */ + +function XMLEscape(str: any): string { + // eslint-disable-line @typescript-eslint/no-explicit-any + // To deal with XSS. Based on Escape implementations of Mustache.JS and Marko, then customized. + const newStr = String(str); + if (/[&<>"']/.test(newStr)) { + return newStr.replace(/[&<>"']/g, replaceChar); + } else { + return newStr; + } +} + +export { trimWS, XMLEscape };