template.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. 'use strict';
  2. const Assert = require('@hapi/hoek/lib/assert');
  3. const Clone = require('@hapi/hoek/lib/clone');
  4. const EscapeHtml = require('@hapi/hoek/lib/escapeHtml');
  5. const Formula = require('@sideway/formula');
  6. const Common = require('./common');
  7. const Errors = require('./errors');
  8. const Ref = require('./ref');
  9. const internals = {
  10. symbol: Symbol('template'),
  11. opens: new Array(1000).join('\u0000'),
  12. closes: new Array(1000).join('\u0001'),
  13. dateFormat: {
  14. date: Date.prototype.toDateString,
  15. iso: Date.prototype.toISOString,
  16. string: Date.prototype.toString,
  17. time: Date.prototype.toTimeString,
  18. utc: Date.prototype.toUTCString
  19. }
  20. };
  21. module.exports = exports = internals.Template = class {
  22. constructor(source, options) {
  23. Assert(typeof source === 'string', 'Template source must be a string');
  24. Assert(!source.includes('\u0000') && !source.includes('\u0001'), 'Template source cannot contain reserved control characters');
  25. this.source = source;
  26. this.rendered = source;
  27. this._template = null;
  28. if (options) {
  29. const { functions, ...opts } = options;
  30. this._settings = Object.keys(opts).length ? Clone(opts) : undefined;
  31. this._functions = functions;
  32. if (this._functions) {
  33. Assert(Object.keys(this._functions).every((key) => typeof key === 'string'), 'Functions keys must be strings');
  34. Assert(Object.values(this._functions).every((key) => typeof key === 'function'), 'Functions values must be functions');
  35. }
  36. }
  37. else {
  38. this._settings = undefined;
  39. this._functions = undefined;
  40. }
  41. this._parse();
  42. }
  43. _parse() {
  44. // 'text {raw} {{ref}} \\{{ignore}} {{ignore\\}} {{ignore {{ignore}'
  45. if (!this.source.includes('{')) {
  46. return;
  47. }
  48. // Encode escaped \\{{{{{
  49. const encoded = internals.encode(this.source);
  50. // Split on first { in each set
  51. const parts = internals.split(encoded);
  52. // Process parts
  53. let refs = false;
  54. const processed = [];
  55. const head = parts.shift();
  56. if (head) {
  57. processed.push(head);
  58. }
  59. for (const part of parts) {
  60. const raw = part[0] !== '{';
  61. const ender = raw ? '}' : '}}';
  62. const end = part.indexOf(ender);
  63. if (end === -1 || // Ignore non-matching closing
  64. part[1] === '{') { // Ignore more than two {
  65. processed.push(`{${internals.decode(part)}`);
  66. continue;
  67. }
  68. let variable = part.slice(raw ? 0 : 1, end);
  69. const wrapped = variable[0] === ':';
  70. if (wrapped) {
  71. variable = variable.slice(1);
  72. }
  73. const dynamic = this._ref(internals.decode(variable), { raw, wrapped });
  74. processed.push(dynamic);
  75. if (typeof dynamic !== 'string') {
  76. refs = true;
  77. }
  78. const rest = part.slice(end + ender.length);
  79. if (rest) {
  80. processed.push(internals.decode(rest));
  81. }
  82. }
  83. if (!refs) {
  84. this.rendered = processed.join('');
  85. return;
  86. }
  87. this._template = processed;
  88. }
  89. static date(date, prefs) {
  90. return internals.dateFormat[prefs.dateFormat].call(date);
  91. }
  92. describe(options = {}) {
  93. if (!this._settings &&
  94. options.compact) {
  95. return this.source;
  96. }
  97. const desc = { template: this.source };
  98. if (this._settings) {
  99. desc.options = this._settings;
  100. }
  101. if (this._functions) {
  102. desc.functions = this._functions;
  103. }
  104. return desc;
  105. }
  106. static build(desc) {
  107. return new internals.Template(desc.template, desc.options || desc.functions ? { ...desc.options, functions: desc.functions } : undefined);
  108. }
  109. isDynamic() {
  110. return !!this._template;
  111. }
  112. static isTemplate(template) {
  113. return template ? !!template[Common.symbols.template] : false;
  114. }
  115. refs() {
  116. if (!this._template) {
  117. return;
  118. }
  119. const refs = [];
  120. for (const part of this._template) {
  121. if (typeof part !== 'string') {
  122. refs.push(...part.refs);
  123. }
  124. }
  125. return refs;
  126. }
  127. resolve(value, state, prefs, local) {
  128. if (this._template &&
  129. this._template.length === 1) {
  130. return this._part(this._template[0], /* context -> [*/ value, state, prefs, local, {} /*] */);
  131. }
  132. return this.render(value, state, prefs, local);
  133. }
  134. _part(part, ...args) {
  135. if (part.ref) {
  136. return part.ref.resolve(...args);
  137. }
  138. return part.formula.evaluate(args);
  139. }
  140. render(value, state, prefs, local, options = {}) {
  141. if (!this.isDynamic()) {
  142. return this.rendered;
  143. }
  144. const parts = [];
  145. for (const part of this._template) {
  146. if (typeof part === 'string') {
  147. parts.push(part);
  148. }
  149. else {
  150. const rendered = this._part(part, /* context -> [*/ value, state, prefs, local, options /*] */);
  151. const string = internals.stringify(rendered, value, state, prefs, local, options);
  152. if (string !== undefined) {
  153. const result = part.raw || (options.errors && options.errors.escapeHtml) === false ? string : EscapeHtml(string);
  154. parts.push(internals.wrap(result, part.wrapped && prefs.errors.wrap.label));
  155. }
  156. }
  157. }
  158. return parts.join('');
  159. }
  160. _ref(content, { raw, wrapped }) {
  161. const refs = [];
  162. const reference = (variable) => {
  163. const ref = Ref.create(variable, this._settings);
  164. refs.push(ref);
  165. return (context) => {
  166. const resolved = ref.resolve(...context);
  167. return resolved !== undefined ? resolved : null;
  168. };
  169. };
  170. try {
  171. const functions = this._functions ? { ...internals.functions, ...this._functions } : internals.functions;
  172. var formula = new Formula.Parser(content, { reference, functions, constants: internals.constants });
  173. }
  174. catch (err) {
  175. err.message = `Invalid template variable "${content}" fails due to: ${err.message}`;
  176. throw err;
  177. }
  178. if (formula.single) {
  179. if (formula.single.type === 'reference') {
  180. const ref = refs[0];
  181. return { ref, raw, refs, wrapped: wrapped || ref.type === 'local' && ref.key === 'label' };
  182. }
  183. return internals.stringify(formula.single.value);
  184. }
  185. return { formula, raw, refs };
  186. }
  187. toString() {
  188. return this.source;
  189. }
  190. };
  191. internals.Template.prototype[Common.symbols.template] = true;
  192. internals.Template.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects
  193. internals.encode = function (string) {
  194. return string
  195. .replace(/\\(\{+)/g, ($0, $1) => {
  196. return internals.opens.slice(0, $1.length);
  197. })
  198. .replace(/\\(\}+)/g, ($0, $1) => {
  199. return internals.closes.slice(0, $1.length);
  200. });
  201. };
  202. internals.decode = function (string) {
  203. return string
  204. .replace(/\u0000/g, '{')
  205. .replace(/\u0001/g, '}');
  206. };
  207. internals.split = function (string) {
  208. const parts = [];
  209. let current = '';
  210. for (let i = 0; i < string.length; ++i) {
  211. const char = string[i];
  212. if (char === '{') {
  213. let next = '';
  214. while (i + 1 < string.length &&
  215. string[i + 1] === '{') {
  216. next += '{';
  217. ++i;
  218. }
  219. parts.push(current);
  220. current = next;
  221. }
  222. else {
  223. current += char;
  224. }
  225. }
  226. parts.push(current);
  227. return parts;
  228. };
  229. internals.wrap = function (value, ends) {
  230. if (!ends) {
  231. return value;
  232. }
  233. if (ends.length === 1) {
  234. return `${ends}${value}${ends}`;
  235. }
  236. return `${ends[0]}${value}${ends[1]}`;
  237. };
  238. internals.stringify = function (value, original, state, prefs, local, options = {}) {
  239. const type = typeof value;
  240. const wrap = prefs && prefs.errors && prefs.errors.wrap || {};
  241. let skipWrap = false;
  242. if (Ref.isRef(value) &&
  243. value.render) {
  244. skipWrap = value.in;
  245. value = value.resolve(original, state, prefs, local, { in: value.in, ...options });
  246. }
  247. if (value === null) {
  248. return 'null';
  249. }
  250. if (type === 'string') {
  251. return internals.wrap(value, options.arrayItems && wrap.string);
  252. }
  253. if (type === 'number' ||
  254. type === 'function' ||
  255. type === 'symbol') {
  256. return value.toString();
  257. }
  258. if (type !== 'object') {
  259. return JSON.stringify(value);
  260. }
  261. if (value instanceof Date) {
  262. return internals.Template.date(value, prefs);
  263. }
  264. if (value instanceof Map) {
  265. const pairs = [];
  266. for (const [key, sym] of value.entries()) {
  267. pairs.push(`${key.toString()} -> ${sym.toString()}`);
  268. }
  269. value = pairs;
  270. }
  271. if (!Array.isArray(value)) {
  272. return value.toString();
  273. }
  274. const values = [];
  275. for (const item of value) {
  276. values.push(internals.stringify(item, original, state, prefs, local, { arrayItems: true, ...options }));
  277. }
  278. return internals.wrap(values.join(', '), !skipWrap && wrap.array);
  279. };
  280. internals.constants = {
  281. true: true,
  282. false: false,
  283. null: null,
  284. second: 1000,
  285. minute: 60 * 1000,
  286. hour: 60 * 60 * 1000,
  287. day: 24 * 60 * 60 * 1000
  288. };
  289. internals.functions = {
  290. if(condition, then, otherwise) {
  291. return condition ? then : otherwise;
  292. },
  293. length(item) {
  294. if (typeof item === 'string') {
  295. return item.length;
  296. }
  297. if (!item || typeof item !== 'object') {
  298. return null;
  299. }
  300. if (Array.isArray(item)) {
  301. return item.length;
  302. }
  303. return Object.keys(item).length;
  304. },
  305. msg(code) {
  306. const [value, state, prefs, local, options] = this;
  307. const messages = options.messages;
  308. if (!messages) {
  309. return '';
  310. }
  311. const template = Errors.template(value, messages[0], code, state, prefs) || Errors.template(value, messages[1], code, state, prefs);
  312. if (!template) {
  313. return '';
  314. }
  315. return template.render(value, state, prefs, local, options);
  316. },
  317. number(value) {
  318. if (typeof value === 'number') {
  319. return value;
  320. }
  321. if (typeof value === 'string') {
  322. return parseFloat(value);
  323. }
  324. if (typeof value === 'boolean') {
  325. return value ? 1 : 0;
  326. }
  327. if (value instanceof Date) {
  328. return value.getTime();
  329. }
  330. return null;
  331. }
  332. };