template.js 10 KB

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