literal.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = literalTemplate;
  6. var _options = require("./options.js");
  7. var _parse = require("./parse.js");
  8. var _populate = require("./populate.js");
  9. function literalTemplate(formatter, tpl, opts) {
  10. const {
  11. metadata,
  12. names
  13. } = buildLiteralData(formatter, tpl, opts);
  14. return arg => {
  15. const defaultReplacements = {};
  16. arg.forEach((replacement, i) => {
  17. defaultReplacements[names[i]] = replacement;
  18. });
  19. return arg => {
  20. const replacements = (0, _options.normalizeReplacements)(arg);
  21. if (replacements) {
  22. Object.keys(replacements).forEach(key => {
  23. if (hasOwnProperty.call(defaultReplacements, key)) {
  24. throw new Error("Unexpected replacement overlap.");
  25. }
  26. });
  27. }
  28. return formatter.unwrap((0, _populate.default)(metadata, replacements ? Object.assign(replacements, defaultReplacements) : defaultReplacements));
  29. };
  30. };
  31. }
  32. function buildLiteralData(formatter, tpl, opts) {
  33. let prefix = "BABEL_TPL$";
  34. const raw = tpl.join("");
  35. do {
  36. prefix = "$$" + prefix;
  37. } while (raw.includes(prefix));
  38. const {
  39. names,
  40. code
  41. } = buildTemplateCode(tpl, prefix);
  42. const metadata = (0, _parse.default)(formatter, formatter.code(code), {
  43. parser: opts.parser,
  44. placeholderWhitelist: new Set(names.concat(opts.placeholderWhitelist ? Array.from(opts.placeholderWhitelist) : [])),
  45. placeholderPattern: opts.placeholderPattern,
  46. preserveComments: opts.preserveComments,
  47. syntacticPlaceholders: opts.syntacticPlaceholders
  48. });
  49. return {
  50. metadata,
  51. names
  52. };
  53. }
  54. function buildTemplateCode(tpl, prefix) {
  55. const names = [];
  56. let code = tpl[0];
  57. for (let i = 1; i < tpl.length; i++) {
  58. const value = `${prefix}${i - 1}`;
  59. names.push(value);
  60. code += value + tpl[i];
  61. }
  62. return {
  63. names,
  64. code
  65. };
  66. }
  67. //# sourceMappingURL=literal.js.map