ember-repl 3.0.0-beta.5 → 3.0.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/declarations/browser/__PRIVATE__.d.ts +2 -0
  2. package/declarations/browser/__PRIVATE__.d.ts.map +1 -0
  3. package/declarations/browser/compile/formats.d.ts +2 -0
  4. package/declarations/browser/compile/formats.d.ts.map +1 -1
  5. package/declarations/browser/compile/index.d.ts +31 -7
  6. package/declarations/browser/compile/index.d.ts.map +1 -1
  7. package/declarations/browser/compile/markdown-to-ember.d.ts +2 -0
  8. package/declarations/browser/compile/markdown-to-ember.d.ts.map +1 -1
  9. package/declarations/browser/compile/types.d.ts +2 -0
  10. package/declarations/browser/compile/types.d.ts.map +1 -1
  11. package/declarations/browser/gjs.d.ts +1 -1
  12. package/declarations/browser/gjs.d.ts.map +1 -1
  13. package/declarations/browser/known-modules.d.ts +4 -0
  14. package/declarations/browser/known-modules.d.ts.map +1 -1
  15. package/dist/browser/__PRIVATE__.js +2 -0
  16. package/dist/browser/__PRIVATE__.js.map +1 -0
  17. package/dist/browser/cjs/index.js +1 -1
  18. package/dist/browser/cjs/index.js.map +1 -1
  19. package/dist/browser/compile/formats.js +2 -1
  20. package/dist/browser/compile/formats.js.map +1 -1
  21. package/dist/browser/compile/index.js +28 -14
  22. package/dist/browser/compile/index.js.map +1 -1
  23. package/dist/browser/compile/markdown-to-ember.js +26 -8
  24. package/dist/browser/compile/markdown-to-ember.js.map +1 -1
  25. package/dist/browser/compile/types.js +1 -1
  26. package/dist/browser/esm/index.js +1 -1
  27. package/dist/browser/esm/index.js.map +1 -1
  28. package/dist/browser/gjs.js +12 -13
  29. package/dist/browser/gjs.js.map +1 -1
  30. package/dist/browser/known-modules.js +4 -4
  31. package/dist/browser/known-modules.js.map +1 -1
  32. package/package.json +59 -54
  33. package/src/browser/__PRIVATE__.ts +1 -0
  34. package/src/browser/cjs/index.ts +1 -1
  35. package/src/browser/compile/formats.ts +3 -0
  36. package/src/browser/compile/index.ts +58 -24
  37. package/src/browser/compile/markdown-to-ember.ts +91 -76
  38. package/src/browser/compile/types.ts +4 -0
  39. package/src/browser/esm/index.ts +1 -1
  40. package/src/browser/gjs.ts +13 -15
  41. package/src/browser/known-modules.ts +4 -2
  42. package/declarations/browser/eti/babel-plugin.d.ts +0 -54
  43. package/declarations/browser/eti/babel-plugin.d.ts.map +0 -1
  44. package/declarations/browser/eti/debug.d.ts +0 -2
  45. package/declarations/browser/eti/debug.d.ts.map +0 -1
  46. package/declarations/browser/eti/parse-templates.d.ts +0 -56
  47. package/declarations/browser/eti/parse-templates.d.ts.map +0 -1
  48. package/declarations/browser/eti/preprocess.d.ts +0 -58
  49. package/declarations/browser/eti/preprocess.d.ts.map +0 -1
  50. package/declarations/browser/eti/template-tag-transform.d.ts +0 -15
  51. package/declarations/browser/eti/template-tag-transform.d.ts.map +0 -1
  52. package/declarations/browser/eti/util.d.ts +0 -14
  53. package/declarations/browser/eti/util.d.ts.map +0 -1
  54. package/dist/browser/eti/babel-plugin.js +0 -95
  55. package/dist/browser/eti/babel-plugin.js.map +0 -1
  56. package/dist/browser/eti/debug.js +0 -9
  57. package/dist/browser/eti/debug.js.map +0 -1
  58. package/dist/browser/eti/parse-templates.js +0 -181
  59. package/dist/browser/eti/parse-templates.js.map +0 -1
  60. package/dist/browser/eti/preprocess.js +0 -106
  61. package/dist/browser/eti/preprocess.js.map +0 -1
  62. package/dist/browser/eti/template-tag-transform.js +0 -46
  63. package/dist/browser/eti/template-tag-transform.js.map +0 -1
  64. package/dist/browser/eti/util.js +0 -39
  65. package/dist/browser/eti/util.js.map +0 -1
  66. package/src/browser/eti/babel-plugin.ts +0 -105
  67. package/src/browser/eti/debug.ts +0 -7
  68. package/src/browser/eti/parse-templates.ts +0 -284
  69. package/src/browser/eti/preprocess.ts +0 -187
  70. package/src/browser/eti/template-tag-transform.ts +0 -100
  71. package/src/browser/eti/util.ts +0 -72
@@ -1,106 +0,0 @@
1
- import { getTemplateLocals } from '@glimmer/syntax';
2
- import lineColumn from 'line-column';
3
- import MagicString from 'magic-string';
4
- import { expect } from './debug.js';
5
- import { parseTemplates } from './parse-templates.js';
6
-
7
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
8
- // @ts-ignore
9
- function getMatchStartAndEnd(match) {
10
- return {
11
- start: expect(match.index, 'Expected regular expression match to have an index'),
12
- end: expect(match.index, 'Expected regular expression match to have an index') + match[0].length
13
- };
14
- }
15
- function replacementFrom(template, index, oldLength, newLength, type) {
16
- const loc = expect(lineColumn(template).fromIndex(index), 'BUG: expected to find a line/column based on index');
17
- return {
18
- type,
19
- index,
20
- oldLength,
21
- newLength,
22
- originalCol: loc.col,
23
- originalLine: loc.line
24
- };
25
- }
26
- function replaceMatch(s, match, startReplacement, endReplacement, template, includeTemplateTokens) {
27
- const {
28
- start: openStart,
29
- end: openEnd
30
- } = getMatchStartAndEnd(match.start);
31
- const {
32
- start: closeStart,
33
- end: closeEnd
34
- } = getMatchStartAndEnd(match.end);
35
- let options = '';
36
- if (includeTemplateTokens) {
37
- const tokensString = getTemplateLocals(template.slice(openEnd, closeStart)).filter(local => local.match(/^[$A-Z_][0-9A-Z_$]*$/i)).join(',');
38
- if (tokensString.length > 0) {
39
- options = `, scope: () => ({${tokensString}})`;
40
- }
41
- }
42
- const newStart = `${startReplacement}\``;
43
- const newEnd = `\`, { strictMode: true${options} }${endReplacement}`;
44
- s.overwrite(openStart, openEnd, newStart);
45
- s.overwrite(closeStart, closeEnd, newEnd);
46
- ensureBackticksEscaped(s, openEnd + 1, closeStart - 1);
47
- return [replacementFrom(template, openStart, openEnd - openStart, newStart.length, 'start'), replacementFrom(template, closeStart, closeEnd - closeStart, newEnd.length, 'end')];
48
- }
49
-
50
- /**
51
- * Preprocesses all embedded templates within a JavaScript or TypeScript file.
52
- * This function replaces all embedded templates that match our template syntax
53
- * with valid, parseable JS. Optionally, it can also include a source map, and
54
- * it can also include all possible values used within the template.
55
- *
56
- * Input:
57
- *
58
- * <template><MyComponent/><template>
59
- *
60
- * Output:
61
- *
62
- * [GLIMMER_TEMPLATE(`<MyComponent/>`, { scope() { return {MyComponent}; } })];
63
- *
64
- * It can also be used with template literals to provide the in scope values:
65
- *
66
- * Input:
67
- *
68
- * hbs`<MyComponent/>`;
69
- *
70
- * Output
71
- *
72
- * hbs(`<MyComponent/>`, { scope() { return {MyComponent}; } });
73
- */
74
- function preprocessEmbeddedTemplates(template, options) {
75
- const {
76
- templateTag,
77
- templateTagReplacement,
78
- includeTemplateTokens,
79
- relativePath
80
- } = options;
81
- const parseTemplatesOptions = {
82
- templateTag
83
- };
84
- const matches = parseTemplates(template, relativePath, parseTemplatesOptions);
85
- const replacements = [];
86
- const s = new MagicString(template);
87
- for (const match of matches) {
88
- if (match.type === 'template-tag') {
89
- replacements.push(...replaceMatch(s, match, `[${templateTagReplacement}(`, ')]', template, includeTemplateTokens));
90
- }
91
- }
92
- let output = s.toString();
93
- return {
94
- output,
95
- replacements
96
- };
97
- }
98
- function ensureBackticksEscaped(s, start, end) {
99
- if (start >= end) return;
100
- let content = s.slice(start, end);
101
- content = content.replace(/(?<!\\)`/g, '\\`');
102
- s.overwrite(start, end, content, false);
103
- }
104
-
105
- export { preprocessEmbeddedTemplates };
106
- //# sourceMappingURL=preprocess.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"preprocess.js","sources":["../../../src/browser/eti/preprocess.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport { getTemplateLocals } from '@glimmer/syntax';\n\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport lineColumn from 'line-column';\nimport MagicString from 'magic-string';\n\nimport { expect } from './debug.ts';\nimport { parseTemplates } from './parse-templates.ts';\n\nimport type { ParseTemplatesOptions, TemplateMatch } from './parse-templates.ts';\n\ninterface PreprocessOptionsEager {\n importIdentifier?: string;\n importPath?: string;\n templateTag?: string;\n templateTagReplacement?: string;\n\n relativePath: string;\n includeSourceMaps: boolean;\n includeTemplateTokens: boolean;\n}\n\ninterface PreprocessOptionsLazy {\n importIdentifier?: string;\n importPath?: string;\n templateTag?: string;\n templateTagReplacement?: string;\n\n relativePath: string;\n includeSourceMaps: boolean;\n includeTemplateTokens: boolean;\n}\n\ntype PreprocessOptions = PreprocessOptionsLazy | PreprocessOptionsEager;\n\ninterface PreprocessedOutput {\n output: string;\n replacements: Replacement[];\n}\n\ninterface Replacement {\n type: 'start' | 'end';\n index: number;\n oldLength: number;\n newLength: number;\n originalLine: number;\n originalCol: number;\n}\n\nfunction getMatchStartAndEnd(match: RegExpMatchArray) {\n return {\n start: expect(match.index, 'Expected regular expression match to have an index'),\n end:\n expect(match.index, 'Expected regular expression match to have an index') + match[0].length,\n };\n}\n\nfunction replacementFrom(\n template: string,\n index: number,\n oldLength: number,\n newLength: number,\n type: 'start' | 'end'\n): Replacement {\n const loc = expect(\n lineColumn(template).fromIndex(index),\n 'BUG: expected to find a line/column based on index'\n );\n\n return {\n type,\n index,\n oldLength,\n newLength,\n originalCol: loc.col,\n originalLine: loc.line,\n };\n}\n\nfunction replaceMatch(\n s: MagicString,\n match: TemplateMatch,\n startReplacement: string,\n endReplacement: string,\n template: string,\n includeTemplateTokens: boolean\n): Replacement[] {\n const { start: openStart, end: openEnd } = getMatchStartAndEnd(match.start);\n const { start: closeStart, end: closeEnd } = getMatchStartAndEnd(match.end);\n\n let options = '';\n\n if (includeTemplateTokens) {\n const tokensString = getTemplateLocals(template.slice(openEnd, closeStart))\n .filter((local: string) => local.match(/^[$A-Z_][0-9A-Z_$]*$/i))\n .join(',');\n\n if (tokensString.length > 0) {\n options = `, scope: () => ({${tokensString}})`;\n }\n }\n\n const newStart = `${startReplacement}\\``;\n const newEnd = `\\`, { strictMode: true${options} }${endReplacement}`;\n\n s.overwrite(openStart, openEnd, newStart);\n s.overwrite(closeStart, closeEnd, newEnd);\n ensureBackticksEscaped(s, openEnd + 1, closeStart - 1);\n\n return [\n replacementFrom(template, openStart, openEnd - openStart, newStart.length, 'start'),\n replacementFrom(template, closeStart, closeEnd - closeStart, newEnd.length, 'end'),\n ];\n}\n\n/**\n * Preprocesses all embedded templates within a JavaScript or TypeScript file.\n * This function replaces all embedded templates that match our template syntax\n * with valid, parseable JS. Optionally, it can also include a source map, and\n * it can also include all possible values used within the template.\n *\n * Input:\n *\n * <template><MyComponent/><template>\n *\n * Output:\n *\n * [GLIMMER_TEMPLATE(`<MyComponent/>`, { scope() { return {MyComponent}; } })];\n *\n * It can also be used with template literals to provide the in scope values:\n *\n * Input:\n *\n * hbs`<MyComponent/>`;\n *\n * Output\n *\n * hbs(`<MyComponent/>`, { scope() { return {MyComponent}; } });\n */\nexport function preprocessEmbeddedTemplates(\n template: string,\n options: PreprocessOptions\n): PreprocessedOutput {\n const { templateTag, templateTagReplacement, includeTemplateTokens, relativePath } = options;\n\n const parseTemplatesOptions: ParseTemplatesOptions = {\n templateTag,\n };\n\n const matches = parseTemplates(template, relativePath, parseTemplatesOptions);\n const replacements: Replacement[] = [];\n const s = new MagicString(template);\n\n for (const match of matches) {\n if (match.type === 'template-tag') {\n replacements.push(\n ...replaceMatch(\n s,\n match,\n `[${templateTagReplacement}(`,\n ')]',\n template,\n includeTemplateTokens\n )\n );\n }\n }\n\n let output = s.toString();\n\n return {\n output,\n replacements,\n };\n}\n\nfunction ensureBackticksEscaped(s: MagicString, start: number, end: number) {\n if (start >= end) return;\n\n let content = s.slice(start, end);\n\n content = content.replace(/(?<!\\\\)`/g, '\\\\`');\n s.overwrite(start, end, content, false);\n}\n"],"names":["getMatchStartAndEnd","match","start","expect","index","end","length","replacementFrom","template","oldLength","newLength","type","loc","lineColumn","fromIndex","originalCol","col","originalLine","line","replaceMatch","s","startReplacement","endReplacement","includeTemplateTokens","openStart","openEnd","closeStart","closeEnd","options","tokensString","getTemplateLocals","slice","filter","local","join","newStart","newEnd","overwrite","ensureBackticksEscaped","preprocessEmbeddedTemplates","templateTag","templateTagReplacement","relativePath","parseTemplatesOptions","matches","parseTemplates","replacements","MagicString","push","output","toString","content","replace"],"mappings":";;;;;;AAAA;AACA;AAmDA,SAASA,mBAAmBA,CAACC,KAAuB,EAAE;EACpD,OAAO;IACLC,KAAK,EAAEC,MAAM,CAACF,KAAK,CAACG,KAAK,EAAE,oDAAoD,CAAC;AAChFC,IAAAA,GAAG,EACDF,MAAM,CAACF,KAAK,CAACG,KAAK,EAAE,oDAAoD,CAAC,GAAGH,KAAK,CAAC,CAAC,CAAC,CAACK,MAAAA;GACxF,CAAA;AACH,CAAA;AAEA,SAASC,eAAeA,CACtBC,QAAgB,EAChBJ,KAAa,EACbK,SAAiB,EACjBC,SAAiB,EACjBC,IAAqB,EACR;AACb,EAAA,MAAMC,GAAG,GAAGT,MAAM,CAChBU,UAAU,CAACL,QAAQ,CAAC,CAACM,SAAS,CAACV,KAAK,CAAC,EACrC,oDACF,CAAC,CAAA;EAED,OAAO;IACLO,IAAI;IACJP,KAAK;IACLK,SAAS;IACTC,SAAS;IACTK,WAAW,EAAEH,GAAG,CAACI,GAAG;IACpBC,YAAY,EAAEL,GAAG,CAACM,IAAAA;GACnB,CAAA;AACH,CAAA;AAEA,SAASC,YAAYA,CACnBC,CAAc,EACdnB,KAAoB,EACpBoB,gBAAwB,EACxBC,cAAsB,EACtBd,QAAgB,EAChBe,qBAA8B,EACf;EACf,MAAM;AAAErB,IAAAA,KAAK,EAAEsB,SAAS;AAAEnB,IAAAA,GAAG,EAAEoB,OAAAA;AAAQ,GAAC,GAAGzB,mBAAmB,CAACC,KAAK,CAACC,KAAK,CAAC,CAAA;EAC3E,MAAM;AAAEA,IAAAA,KAAK,EAAEwB,UAAU;AAAErB,IAAAA,GAAG,EAAEsB,QAAAA;AAAS,GAAC,GAAG3B,mBAAmB,CAACC,KAAK,CAACI,GAAG,CAAC,CAAA;EAE3E,IAAIuB,OAAO,GAAG,EAAE,CAAA;AAEhB,EAAA,IAAIL,qBAAqB,EAAE;AAC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 +0,0 @@
1
- import { buildPrecompileTemplateCall, registerRefs, TEMPLATE_TAG_NAME } from './util.js';
2
-
3
- /**
4
- * Supports the following syntaxes:
5
- *
6
- * const Foo = [GLIMMER_TEMPLATE('hello')];
7
- *
8
- * export const Foo = [GLIMMER_TEMPLATE('hello')];
9
- *
10
- * export default [GLIMMER_TEMPLATE('hello')];
11
- *
12
- * class Foo {
13
- * [GLIMMER_TEMPLATE('hello')];
14
- * }
15
- */
16
- const transformTemplateTag = function (t, templatePath, state) {
17
- let compiled = buildPrecompileTemplateCall(t, templatePath, state);
18
- let path = templatePath.parentPath;
19
- if (path.type === 'ArrayExpression') {
20
- let arrayParentPath = path.parentPath;
21
- let varId = arrayParentPath.node.id || path.scope.generateUidIdentifier(templatePath);
22
- const templateOnlyComponentExpression = t.callExpression(buildSetComponentTemplate(path, state), [compiled, t.callExpression(state.importUtil.import(templatePath, '@ember/component/template-only', 'default', 'templateOnly'), [t.stringLiteral('dynamic-runtime-file.js'), t.stringLiteral(varId.name)])]);
23
- if (arrayParentPath.type === 'ExpressionStatement' && arrayParentPath.parentPath.type === 'Program') {
24
- registerRefs(arrayParentPath.replaceWith(t.exportDefaultDeclaration(templateOnlyComponentExpression)), newPath => [newPath.get('declaration.callee'), newPath.get('declaration.arguments.0.callee'), newPath.get('declaration.arguments.1.callee')]);
25
- } else {
26
- registerRefs(path.replaceWith(templateOnlyComponentExpression), newPath => [newPath.get('callee'), newPath.get('arguments.0.callee'), newPath.get('arguments.1.callee')]);
27
- }
28
- } else if (path.type === 'ClassProperty') {
29
- let classPath = path.parentPath.parentPath;
30
- if (classPath.node.type === 'ClassDeclaration') {
31
- registerRefs(classPath.insertAfter(t.expressionStatement(t.callExpression(buildSetComponentTemplate(path, state), [compiled, classPath.node.id]))), newPath => [newPath.get('expression.callee'), newPath.get('expression.arguments.0.callee')]);
32
- } else {
33
- registerRefs(classPath.replaceWith(t.expressionStatement(t.callExpression(buildSetComponentTemplate(path, state), [compiled, classPath.node]))), newPath => [newPath.parentPath.get('callee'), newPath.parentPath.get('arguments.0.callee')]);
34
- }
35
- path.remove();
36
- return;
37
- } else {
38
- throw path.buildCodeFrameError(`Attempted to use \`<${TEMPLATE_TAG_NAME}>\` to define a template in an unsupported way. Templates defined using this syntax must be:\n\n1. Assigned to a variable declaration OR\n2. The default export of a file OR\n2. In the top level of the file on their own (sugar for \`export default\`) OR\n4. Used directly within a named class body`);
39
- }
40
- };
41
- function buildSetComponentTemplate(path, state) {
42
- return state.importUtil.import(path, '@ember/component', 'setComponentTemplate');
43
- }
44
-
45
- export { transformTemplateTag };
46
- //# sourceMappingURL=template-tag-transform.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"template-tag-transform.js","sources":["../../../src/browser/eti/template-tag-transform.ts"],"sourcesContent":["import { buildPrecompileTemplateCall, registerRefs, TEMPLATE_TAG_NAME } from './util.ts';\n\n/**\n * Supports the following syntaxes:\n *\n * const Foo = [GLIMMER_TEMPLATE('hello')];\n *\n * export const Foo = [GLIMMER_TEMPLATE('hello')];\n *\n * export default [GLIMMER_TEMPLATE('hello')];\n *\n * class Foo {\n * [GLIMMER_TEMPLATE('hello')];\n * }\n */\nexport const transformTemplateTag = function (t: any, templatePath: any, state: any) {\n let compiled = buildPrecompileTemplateCall(t, templatePath, state);\n let path = templatePath.parentPath;\n\n if (path.type === 'ArrayExpression') {\n let arrayParentPath = path.parentPath;\n let varId = arrayParentPath.node.id || path.scope.generateUidIdentifier(templatePath);\n\n const templateOnlyComponentExpression = t.callExpression(\n buildSetComponentTemplate(path, state),\n [\n compiled,\n t.callExpression(\n state.importUtil.import(\n templatePath,\n '@ember/component/template-only',\n 'default',\n 'templateOnly'\n ),\n [t.stringLiteral('dynamic-runtime-file.js'), t.stringLiteral(varId.name)]\n ),\n ]\n );\n\n if (\n arrayParentPath.type === 'ExpressionStatement' &&\n arrayParentPath.parentPath.type === 'Program'\n ) {\n registerRefs(\n arrayParentPath.replaceWith(t.exportDefaultDeclaration(templateOnlyComponentExpression)),\n (newPath: any) => [\n newPath.get('declaration.callee'),\n newPath.get('declaration.arguments.0.callee'),\n newPath.get('declaration.arguments.1.callee'),\n ]\n );\n } else {\n registerRefs(path.replaceWith(templateOnlyComponentExpression), (newPath: any) => [\n newPath.get('callee'),\n newPath.get('arguments.0.callee'),\n newPath.get('arguments.1.callee'),\n ]);\n }\n } else if (path.type === 'ClassProperty') {\n let classPath = path.parentPath.parentPath;\n\n if (classPath.node.type === 'ClassDeclaration') {\n registerRefs(\n classPath.insertAfter(\n t.expressionStatement(\n t.callExpression(buildSetComponentTemplate(path, state), [compiled, classPath.node.id])\n )\n ),\n (newPath: any) => [\n newPath.get('expression.callee'),\n newPath.get('expression.arguments.0.callee'),\n ]\n );\n } else {\n registerRefs(\n classPath.replaceWith(\n t.expressionStatement(\n t.callExpression(buildSetComponentTemplate(path, state), [compiled, classPath.node])\n )\n ),\n (newPath: any) => [\n newPath.parentPath.get('callee'),\n newPath.parentPath.get('arguments.0.callee'),\n ]\n );\n }\n\n path.remove();\n\n return;\n } else {\n throw path.buildCodeFrameError(\n `Attempted to use \\`<${TEMPLATE_TAG_NAME}>\\` to define a template in an unsupported way. Templates defined using this syntax must be:\\n\\n1. Assigned to a variable declaration OR\\n2. The default export of a file OR\\n2. In the top level of the file on their own (sugar for \\`export default\\`) OR\\n4. Used directly within a named class body`\n );\n }\n};\n\nfunction buildSetComponentTemplate(path: any, state: any) {\n return state.importUtil.import(path, '@ember/component', 'setComponentTemplate');\n}\n"],"names":["transformTemplateTag","t","templatePath","state","compiled","buildPrecompileTemplateCall","path","parentPath","type","arrayParentPath","varId","node","id","scope","generateUidIdentifier","templateOnlyComponentExpression","callExpression","buildSetComponentTemplate","importUtil","import","stringLiteral","name","registerRefs","replaceWith","exportDefaultDeclaration","newPath","get","classPath","insertAfter","expressionStatement","remove","buildCodeFrameError","TEMPLATE_TAG_NAME"],"mappings":";;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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AM,EAAE,CAAA;AAEb,IAAA,OAAA;AACF,GAAC,MAAM;AACL,IAAA,MAAMxB,IAAI,CAACyB,mBAAmB,CAC3B,CAAsBC,oBAAAA,EAAAA,iBAAkB,0SAC3C,CAAC,CAAA;AACH,GAAA;AACF,EAAC;AAED,SAASf,yBAAyBA,CAACX,IAAS,EAAEH,KAAU,EAAE;EACxD,OAAOA,KAAK,CAACe,UAAU,CAACC,MAAM,CAACb,IAAI,EAAE,kBAAkB,EAAE,sBAAsB,CAAC,CAAA;AAClF;;;;"}
@@ -1,39 +0,0 @@
1
- // const Greeting = <template>Hello</template>
2
- const TEMPLATE_TAG_NAME = 'template';
3
- const TEMPLATE_TAG_PLACEHOLDER = '__GLIMMER_TEMPLATE';
4
- function isTemplateTag(callExpressionPath) {
5
- const callee = callExpressionPath.get('callee');
6
- return !Array.isArray(callee) && callee.isIdentifier() && callee.node.name === TEMPLATE_TAG_PLACEHOLDER;
7
- }
8
- function buildPrecompileTemplateCall(t, callExpressionPath, state) {
9
- const callee = callExpressionPath.get('callee');
10
- return t.callExpression(state.importUtil.import(callee, '@ember/template-compilation', 'precompileTemplate'), callExpressionPath.node.arguments);
11
- }
12
- function registerRefs(newPath, getRefPaths) {
13
- if (Array.isArray(newPath)) {
14
- if (newPath.length > 1) {
15
- throw new Error('registerRefs is only meant to handle single node transformations. Received more than one path node.');
16
- }
17
- newPath = newPath[0];
18
- }
19
- const refPaths = getRefPaths(newPath);
20
- for (const ref of refPaths) {
21
- if (!ref.isIdentifier()) {
22
- throw new Error('ember-template-imports internal assumption that refPath should of type identifier. Please open an issue.');
23
- }
24
- const binding = ref.scope.getBinding(ref.node.name);
25
- if (binding !== undefined) {
26
- binding.reference(ref);
27
- }
28
- }
29
- }
30
- const SUPPORTED_EXTENSIONS = ['.js', '.ts', '.gjs', '.gts'];
31
- function isSupportedScriptFileExtension(filePath) {
32
- return SUPPORTED_EXTENSIONS.some(ext => filePath.endsWith(ext));
33
- }
34
- function isStrictMode(templateInfo) {
35
- return templateInfo.type === 'template-tag';
36
- }
37
-
38
- export { TEMPLATE_TAG_NAME, TEMPLATE_TAG_PLACEHOLDER, buildPrecompileTemplateCall, isStrictMode, isSupportedScriptFileExtension, isTemplateTag, registerRefs };
39
- //# sourceMappingURL=util.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"util.js","sources":["../../../src/browser/eti/util.ts"],"sourcesContent":["import type { TemplateMatch } from './parse-templates.ts';\nimport type { NodePath } from '@babel/traverse';\nimport type { CallExpression } from '@babel/types';\nimport type { ImportUtil } from 'babel-import-util';\n\n// const Greeting = <template>Hello</template>\nexport const TEMPLATE_TAG_NAME = 'template';\nexport const TEMPLATE_TAG_PLACEHOLDER = '__GLIMMER_TEMPLATE';\n\nexport function isTemplateTag(callExpressionPath: NodePath<CallExpression>) {\n const callee = callExpressionPath.get('callee');\n\n return (\n !Array.isArray(callee) && callee.isIdentifier() && callee.node.name === TEMPLATE_TAG_PLACEHOLDER\n );\n}\n\nexport function buildPrecompileTemplateCall(\n t: any,\n callExpressionPath: NodePath<CallExpression>,\n state: {\n importUtil: ImportUtil;\n }\n): CallExpression {\n const callee = callExpressionPath.get('callee');\n\n return t.callExpression(\n state.importUtil.import(callee, '@ember/template-compilation', 'precompileTemplate'),\n callExpressionPath.node.arguments\n );\n}\n\nexport function registerRefs(\n newPath: string | string[],\n getRefPaths: (path: string) => NodePath[]\n) {\n if (Array.isArray(newPath)) {\n if (newPath.length > 1) {\n throw new Error(\n 'registerRefs is only meant to handle single node transformations. Received more than one path node.'\n );\n }\n\n newPath = newPath[0] as string;\n }\n\n const refPaths = getRefPaths(newPath);\n\n for (const ref of refPaths) {\n if (!ref.isIdentifier()) {\n throw new Error(\n 'ember-template-imports internal assumption that refPath should of type identifier. Please open an issue.'\n );\n }\n\n const binding = ref.scope.getBinding(ref.node.name);\n\n if (binding !== undefined) {\n binding.reference(ref);\n }\n }\n}\n\nconst SUPPORTED_EXTENSIONS = ['.js', '.ts', '.gjs', '.gts'];\n\nexport function isSupportedScriptFileExtension(filePath: string) {\n return SUPPORTED_EXTENSIONS.some((ext) => filePath.endsWith(ext));\n}\n\nexport function isStrictMode(templateInfo: TemplateMatch): boolean {\n return templateInfo.type === 'template-tag';\n}\n"],"names":["TEMPLATE_TAG_NAME","TEMPLATE_TAG_PLACEHOLDER","isTemplateTag","callExpressionPath","callee","get","Array","isArray","isIdentifier","node","name","buildPrecompileTemplateCall","t","state","callExpression","importUtil","import","arguments","registerRefs","newPath","getRefPaths","length","Error","refPaths","ref","binding","scope","getBinding","undefined","reference","SUPPORTED_EXTENSIONS","isSupportedScriptFileExtension","filePath","some","ext","endsWith","isStrictMode","templateInfo","type"],"mappings":"AAKA;AACO,MAAMA,iBAAiB,GAAG,WAAU;AACpC,MAAMC,wBAAwB,GAAG,qBAAoB;AAErD,SAASC,aAAaA,CAACC,kBAA4C,EAAE;AAC1E,EAAA,MAAMC,MAAM,GAAGD,kBAAkB,CAACE,GAAG,CAAC,QAAQ,CAAC,CAAA;EAE/C,OACE,CAACC,KAAK,CAACC,OAAO,CAACH,MAAM,CAAC,IAAIA,MAAM,CAACI,YAAY,EAAE,IAAIJ,MAAM,CAACK,IAAI,CAACC,IAAI,KAAKT,wBAAwB,CAAA;AAEpG,CAAA;AAEO,SAASU,2BAA2BA,CACzCC,CAAM,EACNT,kBAA4C,EAC5CU,KAEC,EACe;AAChB,EAAA,MAAMT,MAAM,GAAGD,kBAAkB,CAACE,GAAG,CAAC,QAAQ,CAAC,CAAA;EAE/C,OAAOO,CAAC,CAACE,cAAc,CACrBD,KAAK,CAACE,UAAU,CAACC,MAAM,CAACZ,MAAM,EAAE,6BAA6B,EAAE,oBAAoB,CAAC,EACpFD,kBAAkB,CAACM,IAAI,CAACQ,SAC1B,CAAC,CAAA;AACH,CAAA;AAEO,SAASC,YAAYA,CAC1BC,OAA0B,EAC1BC,WAAyC,EACzC;AACA,EAAA,IAAId,KAAK,CAACC,OAAO,CAACY,OAAO,CAAC,EAAE;AAC1B,IAAA,IAAIA,OAAO,CAACE,MAAM,GAAG,CAAC,EAAE;AACtB,MAAA,MAAM,IAAIC,KAAK,CACb,qGACF,CAAC,CAAA;AACH,KAAA;AAEAH,IAAAA,OAAO,GAAGA,OAAO,CAAC,CAAC,CAAW,CAAA;AAChC,GAAA;AAEA,EAAA,MAAMI,QAAQ,GAAGH,WAAW,CAACD,OAAO,CAAC,CAAA;AAErC,EAAA,KAAK,MAAMK,GAAG,IAAID,QAAQ,EAAE;AAC1B,IAAA,IAAI,CAACC,GAAG,CAAChB,YAAY,EAAE,EAAE;AACvB,MAAA,MAAM,IAAIc,KAAK,CACb,0GACF,CAAC,CAAA;AACH,KAAA;AAEA,IAAA,MAAMG,OAAO,GAAGD,GAAG,CAACE,KAAK,CAACC,UAAU,CAACH,GAAG,CAACf,IAAI,CAACC,IAAI,CAAC,CAAA;IAEnD,IAAIe,OAAO,KAAKG,SAAS,EAAE;AACzBH,MAAAA,OAAO,CAACI,SAAS,CAACL,GAAG,CAAC,CAAA;AACxB,KAAA;AACF,GAAA;AACF,CAAA;AAEA,MAAMM,oBAAoB,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,CAAA;AAEpD,SAASC,8BAA8BA,CAACC,QAAgB,EAAE;AAC/D,EAAA,OAAOF,oBAAoB,CAACG,IAAI,CAAEC,GAAG,IAAKF,QAAQ,CAACG,QAAQ,CAACD,GAAG,CAAC,CAAC,CAAA;AACnE,CAAA;AAEO,SAASE,YAAYA,CAACC,YAA2B,EAAW;AACjE,EAAA,OAAOA,YAAY,CAACC,IAAI,KAAK,cAAc,CAAA;AAC7C;;;;"}
@@ -1,105 +0,0 @@
1
- import { ImportUtil } from 'babel-import-util';
2
-
3
- import { transformTemplateTag } from './template-tag-transform.ts';
4
- import * as util from './util.ts';
5
-
6
- import type { NodePath } from '@babel/traverse';
7
- import type { CallExpression, Class, Program } from '@babel/types';
8
-
9
- /**
10
- * This Babel plugin takes parseable code emitted by the string-based
11
- * preprocessor plugin in this package and converts it into calls to
12
- * the standardized `precompileTemplate` macro from `@ember/template-compilation`.
13
- *
14
- * Its goal is to convert code like this:
15
- *
16
- * ```js
17
- * import { hbs } from 'ember-template-imports';
18
- *
19
- * const A = hbs(`A`, {...});
20
- * const B = [__GLIMMER_TEMPLATE(`B`, {...})];
21
- * class C {
22
- * template = hbs(`C`, {...});
23
- * }
24
- *
25
- * [__GLIMMER_TEMPLATE(`default`, {...})];
26
- *
27
- * class D {
28
- * [__GLIMMER_TEMPLATE(`D`, {...})]
29
- * }
30
- * ```
31
- *
32
- * Into this:
33
- *
34
- * ```js
35
- * import { precompileTemplate } from '@ember/template-compilation';
36
- * import { setComponentTemplate } from '@ember/component';
37
- * import templateOnlyComponent from '@ember/component/template-only';
38
- *
39
- * const A = setComponentTemplate(
40
- * precompileTemplate(`A`, {...}),
41
- * templateOnlyComponent('this-module.js', 'A')
42
- * );
43
- * const B = setComponentTemplate(
44
- * precompileTemplate(`B`, {...}),
45
- * templateOnlyComponent('this-module.js', 'B')
46
- * );
47
- * class C {}
48
- * setComponentTemplate(precompileTemplate(`C`, {...}), C);
49
- *
50
- * export default setComponentTemplate(
51
- * precompileTemplate(`default`, {...}),
52
- * templateOnlyComponent('this-module.js', '_thisModule')
53
- * );
54
- *
55
- * class D {}
56
- * setComponentTemplate(precompileTemplate(`D`, {...}), D);
57
- * ```
58
- */
59
- export default function (babel: any) {
60
- let t = babel.types;
61
-
62
- let visitor: any = {
63
- Program: {
64
- enter(path: NodePath<Program>, state: any) {
65
- state.importUtil = new ImportUtil(t, path);
66
- },
67
- },
68
-
69
- // Process class bodies before things like class properties get transformed
70
- // into imperative constructor code that we can't recognize. Taken directly
71
- // from babel-plugin-htmlbars-inline-precompile https://git.io/JMi1G
72
- Class(path: NodePath<Class>, state: any) {
73
- let bodyPath = path.get('body.body');
74
-
75
- if (!Array.isArray(bodyPath)) return;
76
-
77
- bodyPath.forEach((path) => {
78
- if (path.type !== 'ClassProperty') return;
79
-
80
- let keyPath = path.get('key');
81
- let valuePath = path.get('value');
82
-
83
- if (Array.isArray(keyPath)) return;
84
-
85
- if (keyPath && visitor[keyPath.type]) {
86
- visitor[keyPath.type](keyPath, state);
87
- }
88
-
89
- if (Array.isArray(valuePath)) return;
90
-
91
- if (valuePath && visitor[valuePath.type]) {
92
- visitor[valuePath.type](valuePath, state);
93
- }
94
- });
95
- },
96
-
97
- CallExpression(path: NodePath<CallExpression>, state: any) {
98
- if (util.isTemplateTag(path)) {
99
- transformTemplateTag(t, path, state);
100
- }
101
- },
102
- };
103
-
104
- return { visitor };
105
- }
@@ -1,7 +0,0 @@
1
- export function expect<T>(value: T | null | undefined, message: string): T {
2
- if (value === undefined || value === null) {
3
- throw new Error(`LIBRARY BUG: ${message}`);
4
- }
5
-
6
- return value;
7
- }
@@ -1,284 +0,0 @@
1
- import { expect } from './debug.ts';
2
- import { TEMPLATE_TAG_NAME } from './util.ts';
3
-
4
- export type TemplateMatch = TemplateTagMatch;
5
-
6
- export interface TemplateTagMatch {
7
- type: 'template-tag';
8
- tagName: string;
9
- start: RegExpMatchArray;
10
- end: RegExpMatchArray;
11
- contents: string;
12
- }
13
-
14
- /**
15
- * Represents a static import of a template literal.
16
- */
17
- export interface StaticImportConfig {
18
- /**
19
- * The path to the package from which we want to import the template literal
20
- * (e.g.: 'ember-cli-htmlbars')
21
- */
22
- importPath: string;
23
- /**
24
- * The name of the template literal (e.g.: 'hbs') or 'default' if this package
25
- * exports a default function
26
- */
27
- importIdentifier: string;
28
- }
29
-
30
- /**
31
- * The input options to instruct parseTemplates on how to parse the input.
32
- *
33
- * @param templateTag
34
- */
35
- export interface ParseTemplatesOptions {
36
- /** Tag to use, if parsing template tags is enabled. */
37
- templateTag?: string;
38
- }
39
-
40
- const escapeChar = '\\';
41
- const stringDelimiter = /['"]/;
42
-
43
- const singleLineCommentStart = /\/\//;
44
- const newLine = /\n/;
45
- const multiLineCommentStart = /\/\*/;
46
- const multiLineCommentEnd = /\*\//;
47
-
48
- const templateLiteralStart = /([$a-zA-Z_][0-9a-zA-Z_$]*)?`/;
49
- const templateLiteralEnd = /`/;
50
-
51
- const dynamicSegmentStart = /\${/;
52
- const blockStart = /{/;
53
- const dynamicSegmentEnd = /}/;
54
-
55
- function isEscaped(template: string, _offset: number | undefined) {
56
- let offset = expect(_offset, 'Expected an index to check escaping');
57
-
58
- let count = 0;
59
-
60
- while (template[offset - 1] === escapeChar) {
61
- count++;
62
- offset--;
63
- }
64
-
65
- return count % 2 === 1;
66
- }
67
-
68
- export const DEFAULT_PARSE_TEMPLATES_OPTIONS = {
69
- templateTag: TEMPLATE_TAG_NAME,
70
- };
71
-
72
- /**
73
- * Parses a template to find all possible valid matches for an embedded template.
74
- * Supported syntaxes are template literals:
75
- *
76
- * hbs`Hello, world!`
77
- *
78
- * And template tags
79
- *
80
- * <template></template>
81
- *
82
- * The parser excludes any values found within strings recursively, and also
83
- * excludes any string literals with dynamic segments (e.g `${}`) since these
84
- * cannot be valid templates.
85
- *
86
- * @param template The template to parse
87
- * @param relativePath Relative file path for the template (for errors)
88
- * @param options optional configuration options for how to parse templates
89
- * @returns
90
- */
91
- export function parseTemplates(
92
- template: string,
93
- relativePath: string,
94
- options: ParseTemplatesOptions = DEFAULT_PARSE_TEMPLATES_OPTIONS
95
- ): TemplateMatch[] {
96
- const results: TemplateMatch[] = [];
97
- const templateTag = options?.templateTag;
98
-
99
- const templateTagStart = new RegExp(`<${templateTag}[^<]*>`);
100
- const templateTagEnd = new RegExp(`</${templateTag}>`);
101
- const argumentsMatchRegex = new RegExp(`<${templateTag}[^<]*\\S[^<]*>`);
102
-
103
- const allTokens = new RegExp(
104
- [
105
- singleLineCommentStart.source,
106
- newLine.source,
107
- multiLineCommentStart.source,
108
- multiLineCommentEnd.source,
109
- stringDelimiter.source,
110
- templateLiteralStart.source,
111
- templateLiteralEnd.source,
112
- dynamicSegmentStart.source,
113
- dynamicSegmentEnd.source,
114
- blockStart.source,
115
- templateTagStart.source,
116
- templateTagEnd.source,
117
- ].join('|'),
118
- 'g'
119
- );
120
-
121
- const tokens = Array.from(template.matchAll(allTokens));
122
-
123
- while (tokens.length > 0) {
124
- const currentToken = tokens.shift()!; // eslint-disable-line @typescript-eslint/no-non-null-assertion
125
-
126
- parseToken(results, template, currentToken, tokens, true);
127
- }
128
-
129
- /**
130
- * Parse the current token. If top level, then template tags can be parsed.
131
- * Else, we are nested within a dynamic segment, which is currently unsupported.
132
- */
133
- function parseToken(
134
- results: TemplateMatch[],
135
- template: string,
136
- token: RegExpMatchArray,
137
- tokens: RegExpMatchArray[],
138
- isTopLevel = false
139
- ) {
140
- if (token[0].match(multiLineCommentStart)) {
141
- parseMultiLineComment(results, template, token, tokens);
142
- } else if (token[0].match(singleLineCommentStart)) {
143
- parseSingleLineComment(results, template, token, tokens);
144
- } else if (token[0].match(templateLiteralStart)) {
145
- parseTemplateLiteral(template, tokens);
146
- } else if (
147
- isTopLevel &&
148
- templateTag !== undefined &&
149
- templateTagStart &&
150
- token[0].match(templateTagStart)
151
- ) {
152
- parseTemplateTag(results, template, token, tokens, templateTag);
153
- } else if (token[0].match(stringDelimiter)) {
154
- parseString(results, template, token, tokens);
155
- }
156
- }
157
-
158
- /**
159
- * Parse a template literal. If a dynamic segment is found, enters the dynamic
160
- * segment and parses it recursively. If no dynamic segments are found and the
161
- * literal is top level (e.g. not nested within a dynamic segment) and has a
162
- * tag, pushes it into the list of results.
163
- */
164
- function parseTemplateLiteral(template: string, tokens: RegExpMatchArray[]) {
165
- while (tokens.length > 0) {
166
- let currentToken = expect(tokens.shift(), 'expected token');
167
-
168
- if (isEscaped(template, currentToken.index)) continue;
169
-
170
- if (currentToken[0].match(templateLiteralEnd)) {
171
- return;
172
- }
173
- }
174
- }
175
-
176
- /**
177
- * Parse a string. All tokens within a string are ignored
178
- * since there are no dynamic segments within these.
179
- */
180
- function parseString(
181
- _results: TemplateMatch[],
182
- template: string,
183
- startToken: RegExpMatchArray,
184
- tokens: RegExpMatchArray[]
185
- ) {
186
- while (tokens.length > 0) {
187
- const currentToken = expect(tokens.shift(), 'expected token');
188
-
189
- if (currentToken[0] === startToken[0] && !isEscaped(template, currentToken.index)) {
190
- return;
191
- }
192
- }
193
- }
194
-
195
- /**
196
- * Parse a single-line comment. All tokens within a single-line comment are ignored
197
- * since there are no dynamic segments within them.
198
- */
199
- function parseSingleLineComment(
200
- _results: TemplateMatch[],
201
- _template: string,
202
- _startToken: RegExpMatchArray,
203
- tokens: RegExpMatchArray[]
204
- ) {
205
- while (tokens.length > 0) {
206
- const currentToken = expect(tokens.shift(), 'expected token');
207
-
208
- if (currentToken[0] === '\n') {
209
- return;
210
- }
211
- }
212
- }
213
-
214
- /**
215
- * Parse a multi-line comment. All tokens within a multi-line comment are ignored
216
- * since there are no dynamic segments within them.
217
- */
218
- function parseMultiLineComment(
219
- _results: TemplateMatch[],
220
- _template: string,
221
- _startToken: RegExpMatchArray,
222
- tokens: RegExpMatchArray[]
223
- ) {
224
- while (tokens.length > 0) {
225
- const currentToken = expect(tokens.shift(), 'expected token');
226
-
227
- if (currentToken[0] === '*/') {
228
- return;
229
- }
230
- }
231
- }
232
-
233
- /**
234
- * Parses a template tag. Continues parsing until the template tag has closed,
235
- * accounting for nested template tags.
236
- */
237
- function parseTemplateTag(
238
- results: TemplateMatch[],
239
- _template: string,
240
- startToken: RegExpMatchArray,
241
- tokens: RegExpMatchArray[],
242
- templateTag: string
243
- ) {
244
- let stack = 1;
245
-
246
- if (argumentsMatchRegex && startToken[0].match(argumentsMatchRegex)) {
247
- throw new Error(
248
- `embedded template preprocessing currently does not support passing arguments, found args in: ${relativePath}`
249
- );
250
- }
251
-
252
- while (tokens.length > 0) {
253
- const currentToken = expect(tokens.shift(), 'expected token');
254
-
255
- if (currentToken[0].match(templateTagStart)) {
256
- stack++;
257
- } else if (currentToken[0].match(templateTagEnd)) {
258
- stack--;
259
- }
260
-
261
- if (stack === 0) {
262
- let contents = '';
263
-
264
- if (startToken.index !== undefined) {
265
- const templateStart = startToken.index + startToken[0].length;
266
-
267
- contents = template.slice(templateStart, currentToken.index);
268
- }
269
-
270
- results.push({
271
- type: 'template-tag',
272
- tagName: templateTag,
273
- contents: contents,
274
- start: startToken,
275
- end: currentToken,
276
- });
277
-
278
- return;
279
- }
280
- }
281
- }
282
-
283
- return results;
284
- }