builder.js 2.5 KB

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