builder.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = createTemplateBuilder;
  6. var _options = require("./options");
  7. var _string = require("./string");
  8. var _literal = require("./literal");
  9. const NO_PLACEHOLDER = (0, _options.validate)({
  10. placeholderPattern: false
  11. });
  12. function createTemplateBuilder(formatter, defaultOpts) {
  13. const templateFnCache = new WeakMap();
  14. const templateAstCache = new WeakMap();
  15. const cachedOpts = defaultOpts || (0, _options.validate)(null);
  16. return Object.assign((tpl, ...args) => {
  17. if (typeof tpl === "string") {
  18. if (args.length > 1) throw new Error("Unexpected extra params.");
  19. return extendedTrace((0, _string.default)(formatter, tpl, (0, _options.merge)(cachedOpts, (0, _options.validate)(args[0]))));
  20. } else if (Array.isArray(tpl)) {
  21. let builder = templateFnCache.get(tpl);
  22. if (!builder) {
  23. builder = (0, _literal.default)(formatter, tpl, cachedOpts);
  24. templateFnCache.set(tpl, builder);
  25. }
  26. return extendedTrace(builder(args));
  27. } else if (typeof tpl === "object" && tpl) {
  28. if (args.length > 0) throw new Error("Unexpected extra params.");
  29. return createTemplateBuilder(formatter, (0, _options.merge)(cachedOpts, (0, _options.validate)(tpl)));
  30. }
  31. throw new Error(`Unexpected template param ${typeof tpl}`);
  32. }, {
  33. ast: (tpl, ...args) => {
  34. if (typeof tpl === "string") {
  35. if (args.length > 1) throw new Error("Unexpected extra params.");
  36. return (0, _string.default)(formatter, tpl, (0, _options.merge)((0, _options.merge)(cachedOpts, (0, _options.validate)(args[0])), NO_PLACEHOLDER))();
  37. } else if (Array.isArray(tpl)) {
  38. let builder = templateAstCache.get(tpl);
  39. if (!builder) {
  40. builder = (0, _literal.default)(formatter, tpl, (0, _options.merge)(cachedOpts, NO_PLACEHOLDER));
  41. templateAstCache.set(tpl, builder);
  42. }
  43. return builder(args)();
  44. }
  45. throw new Error(`Unexpected template param ${typeof tpl}`);
  46. }
  47. });
  48. }
  49. function extendedTrace(fn) {
  50. let rootStack = "";
  51. try {
  52. throw new Error();
  53. } catch (error) {
  54. if (error.stack) {
  55. rootStack = error.stack.split("\n").slice(3).join("\n");
  56. }
  57. }
  58. return arg => {
  59. try {
  60. return fn(arg);
  61. } catch (err) {
  62. err.stack += `\n =============\n${rootStack}`;
  63. throw err;
  64. }
  65. };
  66. }