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