@ui5/webcomponents-tools 0.0.0-037d08c67

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 (124) hide show
  1. package/CHANGELOG.md +2474 -0
  2. package/LICENSE.txt +201 -0
  3. package/README.md +21 -0
  4. package/assets-meta.js +154 -0
  5. package/bin/create-ui5-element.js +3 -0
  6. package/bin/dev.js +22 -0
  7. package/bin/ui5nps.js +301 -0
  8. package/components-package/eslint.js +195 -0
  9. package/components-package/nps.js +177 -0
  10. package/components-package/postcss.components.js +1 -0
  11. package/components-package/postcss.themes.js +1 -0
  12. package/components-package/vite.config.js +9 -0
  13. package/components-package/wdio.js +421 -0
  14. package/icons-collection/nps.js +80 -0
  15. package/lib/amd-to-es6/index.js +109 -0
  16. package/lib/amd-to-es6/no-remaining-require.js +33 -0
  17. package/lib/cem/cem.js +16 -0
  18. package/lib/cem/custom-elements-manifest.config.mjs +575 -0
  19. package/lib/cem/event.mjs +168 -0
  20. package/lib/cem/patch/@custom-elements-manifest/analyzer/cli.js +128 -0
  21. package/lib/cem/patch/@custom-elements-manifest/analyzer/package.json +59 -0
  22. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/browser-entrypoint.js +23 -0
  23. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/create.js +117 -0
  24. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/arrow-function.js +26 -0
  25. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/class-jsdoc.js +157 -0
  26. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/classes.js +20 -0
  27. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/createArrowFunction.js +17 -0
  28. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/createAttribute.js +24 -0
  29. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/createClass.js +301 -0
  30. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/createClassField.js +26 -0
  31. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/createFunctionLike.js +73 -0
  32. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/createMixin.js +33 -0
  33. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/createVariable.js +22 -0
  34. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/creators/handlers.js +338 -0
  35. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/custom-elements-define-calls.js +90 -0
  36. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/exports.js +156 -0
  37. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/function-like.js +24 -0
  38. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/mixins.js +29 -0
  39. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/reexported-wrapped-mixin-exports.js +84 -0
  40. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/analyse-phase/variables.js +34 -0
  41. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/collect-phase/collect-imports.js +101 -0
  42. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/catalyst/catalyst.js +11 -0
  43. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/catalyst/controller.js +34 -0
  44. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/catalyst-major-2/catalyst.js +11 -0
  45. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/catalyst-major-2/controller.js +34 -0
  46. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/decorators/attr.js +53 -0
  47. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/decorators/custom-element-decorator.js +36 -0
  48. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/fast/fast.js +7 -0
  49. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/lit/lit.js +13 -0
  50. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/lit/member-denylist.js +21 -0
  51. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/lit/method-denylist.js +20 -0
  52. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/lit/property-decorator.js +94 -0
  53. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/lit/static-properties.js +121 -0
  54. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/lit/utils.js +66 -0
  55. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/framework-plugins/stencil/stencil.js +129 -0
  56. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/index.js +80 -0
  57. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/link-phase/cleanup-classes.js +25 -0
  58. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/link-phase/field-denylist.js +22 -0
  59. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/link-phase/method-denylist.js +25 -0
  60. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/post-processing/apply-inheritance.js +78 -0
  61. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/post-processing/is-custom-element.js +34 -0
  62. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/post-processing/link-class-to-tagname.js +27 -0
  63. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/post-processing/remove-unexported-declarations.js +23 -0
  64. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/features/post-processing/resolve-initializers.js +52 -0
  65. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/ast-helpers.js +186 -0
  66. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/cli-helpers.js +164 -0
  67. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/exports.js +44 -0
  68. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/find-external-manifests.js +67 -0
  69. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/imports.js +25 -0
  70. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/index.js +71 -0
  71. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/jsdoc.js +19 -0
  72. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/manifest-helpers.js +194 -0
  73. package/lib/cem/patch/@custom-elements-manifest/analyzer/src/utils/mixins.js +112 -0
  74. package/lib/cem/schema-internal.json +1422 -0
  75. package/lib/cem/schema.json +1098 -0
  76. package/lib/cem/types-internal.d.ts +808 -0
  77. package/lib/cem/types.d.ts +736 -0
  78. package/lib/cem/utils.mjs +429 -0
  79. package/lib/cem/validate.js +81 -0
  80. package/lib/chokidar/chokidar.js +28 -0
  81. package/lib/copy-and-watch/index.js +158 -0
  82. package/lib/copy-list/index.js +36 -0
  83. package/lib/create-icons/index.js +131 -0
  84. package/lib/create-illustrations/index.js +210 -0
  85. package/lib/create-new-component/Component.js +74 -0
  86. package/lib/create-new-component/ComponentTemplate.js +12 -0
  87. package/lib/create-new-component/index.js +115 -0
  88. package/lib/css-processors/css-processor-components.mjs +101 -0
  89. package/lib/css-processors/css-processor-themes.mjs +121 -0
  90. package/lib/css-processors/postcss-plugin.mjs +153 -0
  91. package/lib/css-processors/scope-variables.mjs +51 -0
  92. package/lib/css-processors/shared.mjs +47 -0
  93. package/lib/dev-server/custom-hot-update-plugin.js +39 -0
  94. package/lib/dev-server/dev-server.mjs +78 -0
  95. package/lib/dev-server/virtual-index-html-plugin.js +56 -0
  96. package/lib/eslint/eslint.js +44 -0
  97. package/lib/generate-js-imports/illustrations.js +87 -0
  98. package/lib/generate-json-imports/i18n.js +93 -0
  99. package/lib/generate-json-imports/themes.js +75 -0
  100. package/lib/hbs2lit/index.js +3 -0
  101. package/lib/hbs2lit/src/compiler.js +60 -0
  102. package/lib/hbs2lit/src/extendedAttributeMapping.js +12 -0
  103. package/lib/hbs2lit/src/includesReplacer.js +31 -0
  104. package/lib/hbs2lit/src/litVisitor2.js +278 -0
  105. package/lib/hbs2lit/src/partials2.js +51 -0
  106. package/lib/hbs2lit/src/partialsVisitor.js +187 -0
  107. package/lib/hbs2lit/src/svgProcessor.js +76 -0
  108. package/lib/hbs2ui5/RenderTemplates/LitRenderer.js +45 -0
  109. package/lib/hbs2ui5/index.js +119 -0
  110. package/lib/i18n/defaults.js +90 -0
  111. package/lib/i18n/toJSON.js +71 -0
  112. package/lib/icons-hash/icons-hash.mjs +149 -0
  113. package/lib/postcss-combine-duplicated-selectors/index.js +185 -0
  114. package/lib/remove-dev-mode/remove-dev-mode.mjs +51 -0
  115. package/lib/rimraf/rimraf.js +31 -0
  116. package/lib/scoping/get-all-tags.js +44 -0
  117. package/lib/scoping/lint-src.js +32 -0
  118. package/lib/scoping/missing-dependencies.js +65 -0
  119. package/lib/scoping/report-tags-usage.js +28 -0
  120. package/lib/scoping/scope-test-pages.js +41 -0
  121. package/lib/test-runner/test-runner.js +79 -0
  122. package/lib/vite-bundler/vite-bundler.mjs +35 -0
  123. package/package.json +86 -0
  124. package/tsconfig.json +18 -0
@@ -0,0 +1,93 @@
1
+ const fs = require("fs").promises;
2
+ const path = require('path');
3
+
4
+ const isTypeScript = process.env.UI5_TS;
5
+ const ext = isTypeScript ? 'ts' : 'js';
6
+
7
+
8
+ const getContent = function(caseLines, languagesKeysStringArray, packageName) {
9
+ return `// @ts-nocheck
10
+ import { registerI18nLoader } from "@ui5/webcomponents-base/dist/asset-registries/i18n.js";
11
+
12
+ const importMessageBundle = async (localeId) => {
13
+ switch (localeId) {
14
+ ${caseLines}
15
+ default: throw "unknown locale"
16
+ }
17
+ }
18
+
19
+ const importAndCheck = async (localeId) => {
20
+ const data = await importMessageBundle(localeId);
21
+ if (typeof data === "string" && data.endsWith(".json")) {
22
+ throw new Error(\`[i18n] Invalid bundling detected - dynamic JSON imports bundled as URLs. Switch to inlining JSON files from the build. Check the \"Assets\" documentation for more information.\`);
23
+ }
24
+ return data;
25
+ }
26
+
27
+ const localeIds = [${languagesKeysStringArray}];
28
+
29
+ localeIds.forEach(localeId => {
30
+ registerI18nLoader(${ packageName.split("").map(c => `"${c}"`).join (" + ") }, localeId, importAndCheck);
31
+ });
32
+ `;
33
+ }
34
+
35
+ const generate = async (argv) => {
36
+
37
+ const packageName = JSON.parse(await fs.readFile("package.json")).name;
38
+
39
+ const inputFolder = path.normalize(argv[2]);
40
+ const outputFileDynamic = path.normalize(`${argv[3]}/i18n.${ext}`);
41
+ const outputFileFetchMetaResolve = path.normalize(`${argv[3]}/i18n-fetch.${ext}`);
42
+ const outputFileDynamicImportJSONImport = path.normalize(`${argv[3]}/i18n-node.${ext}`);
43
+
44
+ // All languages present in the file system
45
+ const files = await fs.readdir(inputFolder);
46
+ const languages = files.map(file => {
47
+ const matches = file.match(/messagebundle_(.+?).properties$/);
48
+ return matches ? matches[1] : undefined;
49
+ }).filter(key => !!key);
50
+
51
+ let contentDynamic;
52
+ let contentFetchMetaResolve;
53
+ let contentDynamicImportJSONAttr;
54
+
55
+ // No i18n - just import dependencies, if any
56
+ if (languages.length === 0) {
57
+ contentDynamic = "";
58
+ contentFetchMetaResolve = "";
59
+ contentDynamicImportJSONAttr = "";
60
+ // There is i18n - generate the full file
61
+ } else {
62
+ // Keys for the array
63
+ const languagesKeysStringArray = languages.map(key => `"${key}",`).join("\n\t");
64
+
65
+ // Actual imports for json assets
66
+ const dynamicImportsString = languages.map(key => ` case "${key}": return (await import(/* webpackChunkName: "${packageName.replace("@", "").replace("/", "-")}-messagebundle-${key}" */ "../assets/i18n/messagebundle_${key}.json")).default;`).join("\n");
67
+ const fetchMetaResolveString = languages.map(key => ` case "${key}": return (await fetch(new URL("../assets/i18n/messagebundle_${key}.json", import.meta.url))).json();`).join("\n");
68
+ const dynamicImportJSONAttrString = languages.map(key => ` case "${key}": return (await import(/* webpackChunkName: "${packageName.replace("@", "").replace("/", "-")}-messagebundle-${key}" */ "../assets/i18n/messagebundle_${key}.json", {with: { type: 'json'}})).default;`).join("\n");
69
+
70
+ // Resulting file content
71
+
72
+ contentDynamic = getContent(dynamicImportsString, languagesKeysStringArray, packageName);
73
+ contentFetchMetaResolve = getContent(fetchMetaResolveString, languagesKeysStringArray, packageName);
74
+ contentDynamicImportJSONAttr = getContent(dynamicImportJSONAttrString, languagesKeysStringArray, packageName);
75
+ }
76
+
77
+ await fs.mkdir(path.dirname(outputFileDynamic), { recursive: true });
78
+ return Promise.all([
79
+ fs.writeFile(outputFileDynamic, contentDynamic),
80
+ fs.writeFile(outputFileFetchMetaResolve, contentFetchMetaResolve),
81
+ fs.writeFile(outputFileDynamicImportJSONImport, contentDynamicImportJSONAttr),
82
+ ]).then(() => {
83
+ if (process.env.UI5_VERBOSE === "true") {
84
+ console.log("Generated i18n JSON imports.");
85
+ }
86
+ });
87
+ }
88
+
89
+ if (require.main === module) {
90
+ generate(process.argv)
91
+ }
92
+
93
+ exports._ui5mainFn = generate;
@@ -0,0 +1,75 @@
1
+ const fs = require("fs").promises;
2
+ const path = require('path');
3
+ const assets = require("../../assets-meta.js");
4
+
5
+ const isTypeScript = process.env.UI5_TS;
6
+ const ext = isTypeScript ? 'ts' : 'js';
7
+
8
+ const CSS_VARIABLES_TARGET = process.env.CSS_VARIABLES_TARGET === "host";
9
+
10
+ const generate = async (argv) => {
11
+ const inputFolder = path.normalize(argv[2]);
12
+ const outputFileDynamic = path.normalize(`${argv[3]}/Themes.${ext}`);
13
+ const outputFileDynamicImportJSONAttr = path.normalize(`${argv[3]}/Themes-node.${ext}`);
14
+ const outputFileFetchMetaResolve = path.normalize(`${argv[3]}/Themes-fetch.${ext}`);
15
+
16
+ // All supported optional themes
17
+ const allThemes = assets.themes.all;
18
+
19
+ // All themes present in the file system
20
+ const dirs = await fs.readdir(inputFolder);
21
+ const themesOnFileSystem = dirs.map(dir => {
22
+ const matches = dir.match(/sap_.*$/);
23
+ return matches ? dir : undefined;
24
+ }).filter(key => !!key && allThemes.includes(key));
25
+
26
+ const packageName = JSON.parse(await fs.readFile("package.json")).name;
27
+
28
+ const availableThemesArray = `[${themesOnFileSystem.map(theme => `"${theme}"`).join(", ")}]`;
29
+ const dynamicImportLines = themesOnFileSystem.map(theme => `\t\tcase "${theme}": return (await import(/* webpackChunkName: "${packageName.replace("@", "").replace("/", "-")}-${theme.replace("_", "-")}-parameters-bundle" */"../assets/themes/${theme}/parameters-bundle.css.json")).default;`).join("\n");
30
+ const dynamicImportJSONAttrLines = themesOnFileSystem.map(theme => `\t\tcase "${theme}": return (await import(/* webpackChunkName: "${packageName.replace("@", "").replace("/", "-")}-${theme.replace("_", "-")}-parameters-bundle" */"../assets/themes/${theme}/parameters-bundle.css.json", {with: { type: 'json'}})).default;`).join("\n");
31
+ const fetchMetaResolveLines = themesOnFileSystem.map(theme => `\t\tcase "${theme}": return (await fetch(new URL("../assets/themes/${theme}/parameters-bundle.css.json", import.meta.url))).json();`).join("\n");
32
+
33
+ // dynamic imports file content
34
+ const contentDynamic = function (lines) {
35
+ return `// @ts-nocheck
36
+ import { registerThemePropertiesLoader } from "@ui5/webcomponents-base/dist/asset-registries/Themes.js";
37
+
38
+ const loadThemeProperties = async (themeName) => {
39
+ switch (themeName) {
40
+ ${lines}
41
+ default: throw "unknown theme"
42
+ }
43
+ };
44
+
45
+ const loadAndCheck = async (themeName) => {
46
+ const data = await loadThemeProperties(themeName);
47
+ if (typeof data === "string" && data.endsWith(".json")) {
48
+ throw new Error(\`[themes] Invalid bundling detected - dynamic JSON imports bundled as URLs. Switch to inlining JSON files from the build. Check the \"Assets\" documentation for more information.\`);
49
+ }
50
+ return data;
51
+ };
52
+
53
+ ${availableThemesArray}
54
+ .forEach(themeName => registerThemePropertiesLoader(${packageName.split("").map(c => `"${c}"`).join(" + ")}, themeName, loadAndCheck${CSS_VARIABLES_TARGET ? ', "host"' : ''}));
55
+ `;
56
+ }
57
+
58
+ await fs.mkdir(path.dirname(outputFileDynamic), { recursive: true });
59
+ return Promise.all([
60
+ fs.writeFile(outputFileDynamic, contentDynamic(dynamicImportLines)),
61
+ fs.writeFile(outputFileDynamicImportJSONAttr, contentDynamic(dynamicImportJSONAttrLines)),
62
+ fs.writeFile(outputFileFetchMetaResolve, contentDynamic(fetchMetaResolveLines)),
63
+ ]).
64
+ then(() => {
65
+ if (process.env.UI5_VERBOSE === "true") {
66
+ console.log("Generated themes JSON imports.");
67
+ }
68
+ })
69
+ };
70
+
71
+ if (require.main === module) {
72
+ generate(process.argv)
73
+ }
74
+
75
+ exports._ui5mainFn = generate;
@@ -0,0 +1,3 @@
1
+ const hbs2lit = require("./src/compiler");
2
+
3
+ module.exports = hbs2lit;
@@ -0,0 +1,60 @@
1
+ const HTMLLitVisitor = require("./litVisitor2");
2
+ const PartialsVisitor = require("./partialsVisitor");
3
+ const Handlebars = require("handlebars/dist/handlebars.min.js");
4
+ const includesReplacer = require("./includesReplacer");
5
+ const svgProcessor = require("./svgProcessor");
6
+
7
+ const removeWhiteSpaces = (source) => {
8
+ return source
9
+ .replace(/\s*\r*\n+\s*/g, " ") // Replace new lines and all whitespace between them with a space
10
+ .replace(/\s*<\s*/g, "<") // Strip whitespace round <
11
+ .replace(/\s*>\s*/g, ">") // Strip whitespace round >
12
+ .replace(/}}\s+{{/g, "}}{{"); // Remove whitespace between }} and {{
13
+ };
14
+
15
+ const hbs2lit = async (file, componentName) => {
16
+ let sPreprocessed = await includesReplacer.replace(file);
17
+
18
+ sPreprocessed = removeWhiteSpaces(sPreprocessed);
19
+
20
+ const blockSignature = process.env.UI5_TS ? `this: ${componentName}` : ""
21
+
22
+ // icons hack
23
+ if (sPreprocessed.startsWith("<g ") || sPreprocessed.startsWith("<g>")) {
24
+ return `
25
+ function block0 (${blockSignature}) {
26
+ return svg\`${sPreprocessed}\`
27
+ }`;
28
+ }
29
+
30
+ const ast = Handlebars.parse(sPreprocessed);
31
+
32
+ const pv = new PartialsVisitor();
33
+ const lv = new HTMLLitVisitor(componentName);
34
+
35
+ let result = "";
36
+
37
+ pv.accept(ast);
38
+ pv.modify(ast);
39
+
40
+ lv.accept(ast);
41
+
42
+ for (let key in lv.blocks) {
43
+ let block = lv.blocks[key];
44
+
45
+ if (block.match(/scopeTag/)) {
46
+ // const matches = block.match(/^(.*?)( => )(.*?);$/);
47
+ const matches = block.match(/^(function .*? \{ return )(.*?);\}$/);
48
+ const scopedCode = matches[2];
49
+ const normalCode = scopedCode.replace(/\${scopeTag\("/g, "").replace(/", tags, suffix\)}/g, "");
50
+ block = `${matches[1]}suffix ? ${scopedCode} : ${normalCode};}`;
51
+ }
52
+
53
+ result += block + "\n";
54
+ }
55
+
56
+ result = svgProcessor.process(result);
57
+ return result;
58
+ };
59
+
60
+ module.exports = hbs2lit;
@@ -0,0 +1,12 @@
1
+ function replaceEqualities(hbs) {
2
+ // converts the boolean attributes to lit like boolean attributes
3
+ return hbs.replace(/(\s+)(disabled|hidden|checked|readonly)\s*=\s*/g, " ?$2 = ")
4
+ // maps all the propertis to attributes
5
+ .replace(/([a-zA-Z][\w\-]*?)\s*=\s*"{{/g, "$1 = \"{{")
6
+ // maps the value attribute to property
7
+ .replace(/(value\s*=)/g, ".value =");
8
+ }
9
+
10
+ module.exports = {
11
+ map: replaceEqualities
12
+ };
@@ -0,0 +1,31 @@
1
+ const path = require("path");
2
+ const fs = require("fs").promises;
3
+
4
+ const replaceIncludes = async (file) => {
5
+ const filePath = path.dirname(file);
6
+ let fileContent = await fs.readFile(file, "utf-8");
7
+
8
+ const inclRegex = /{{>\s*include\s*["'](.+?)["']}}/g;
9
+ let match;
10
+
11
+ while((match = inclRegex.exec(fileContent)) !== null) {
12
+ inclRegex.lastIndex = 0;
13
+
14
+ let targetFile = match[1];
15
+ if (targetFile.startsWith(".")) {
16
+ // Relative path, f.e. {{>include "./Popup.hbs"}} or {{>include "../partials/Header.hbs"}}
17
+ targetFile = path.join(filePath, targetFile);
18
+ } else {
19
+ // Node module path, f.e. {{>include "@ui5/webcomponents/src/Popup.hbs"}}
20
+ targetFile = require.resolve(targetFile);
21
+ }
22
+
23
+ fileContent = fileContent.replace(match[0], await replaceIncludes(targetFile));
24
+ }
25
+
26
+ return fileContent;
27
+ };
28
+
29
+ module.exports = {
30
+ replace: replaceIncludes
31
+ };
@@ -0,0 +1,278 @@
1
+ const Handlebars = require("handlebars/dist/handlebars.min.js");
2
+ const path = require("path");
3
+ const Visitor = Handlebars.Visitor;
4
+
5
+ // skip ifDefined for event handlers and boolean attrs
6
+ let skipIfDefined = false;
7
+
8
+ // when true => an HTML node value, when false => an attribute value
9
+ let isNodeValue = false;
10
+
11
+ // when true => the current attribute is "style"
12
+ let isStyleAttribute = false;
13
+
14
+ // matches event handlers @click= and boolean attrs ?disabled=
15
+ const dynamicAttributeRgx = /\s(\?|@)([a-zA-Z|-]+)="?\s*$/;
16
+
17
+ if (!String.prototype.replaceAll) {
18
+ String.prototype.replaceAll = function(str, newStr){
19
+
20
+ // If a regex pattern
21
+ if (Object.prototype.toString.call(str).toLowerCase() === '[object regexp]') {
22
+ return this.replace(str, newStr);
23
+ }
24
+
25
+ // If a string
26
+ return this.replace(new RegExp(str, 'g'), newStr);
27
+
28
+ };
29
+ }
30
+
31
+ function HTMLLitVisitor(componentName, debug) {
32
+ this.blockCounter = 0;
33
+ this.keys = [];
34
+ this.blocks = {};
35
+ this.result = "";
36
+ this.mainBlock = "";
37
+ this.blockLevel = 0;
38
+ this.componentName = componentName
39
+ const blockParametersDefinitionTS = [`this: ${componentName}`, "context: UI5Element", "tags: string[]", "suffix: string | undefined"];
40
+ const blockParametersDefinitionJS = ["context", "tags", "suffix"];
41
+ this.blockParametersDefinition = process.env.UI5_TS ? blockParametersDefinitionTS : blockParametersDefinitionJS;
42
+ this.blockParametersUsage = ["this", "context", "tags", "suffix"];
43
+ this.paths = []; //contains all normalized relative paths
44
+ this.debug = debug;
45
+ if (this.debug) {
46
+ this.blockByNumber = [];
47
+ }
48
+ }
49
+
50
+ HTMLLitVisitor.prototype = new Visitor();
51
+
52
+ HTMLLitVisitor.prototype.Program = function(program) {
53
+ let key = `block${this.blockCounter++}`;
54
+
55
+ this.keys.push(key);
56
+ this.debug && this.blockByNumber.push(key);
57
+
58
+ // this.blocks[this.currentKey()] = "function " + this.currentKey() + ` (this: any, ` + this.blockParametersDefinition.join(", ") + ") { ";
59
+ this.blocks[this.currentKey()] = `function ${this.currentKey()} (${this.blockParametersDefinition.join(", ")}) { `;
60
+
61
+ if (this.keys.length > 1) { //it's a nested block
62
+ this.blocks[this.prevKey()] += this.currentKey() + ".call(" + this.blockParametersUsage.join(", ") + ")";
63
+ } else {
64
+ this.mainBlock = this.currentKey();
65
+ }
66
+
67
+ this.blocks[this.currentKey()] += "return html`";
68
+ Visitor.prototype.Program.call(this, program);
69
+ this.blocks[this.currentKey()] += "`;}";
70
+
71
+ this.keys.pop(key);
72
+ };
73
+
74
+ HTMLLitVisitor.prototype.ContentStatement = function(content) {
75
+ Visitor.prototype.ContentStatement.call(this, content);
76
+ // let content = content.orgiinal; // attribute="__ attribute = "__ attribute ="__
77
+
78
+ let contentStatement = content.original;
79
+ skipIfDefined = !!dynamicAttributeRgx.exec(contentStatement);
80
+
81
+ const closingIndex = contentStatement.lastIndexOf(">");
82
+ const openingIndex = contentStatement.lastIndexOf("<");
83
+ if (closingIndex !== -1 || openingIndex !== -1) { // Only change isNodeValue whenever < or > is found in the content statement
84
+ isNodeValue = closingIndex > openingIndex;
85
+ }
86
+
87
+ isStyleAttribute = !isNodeValue && contentStatement.match(/style *= *["']? *$/);
88
+
89
+ if (!isStyleAttribute && contentStatement.match(/style=/)) {
90
+ console.log("WARNING: style hard-coded", contentStatement);
91
+ }
92
+
93
+ // Scope custom element tags
94
+ contentStatement = contentStatement.replaceAll(/(<\/?\s*)([a-zA-Z0-9_]+-[a-zA-Z0-9_-]+)/g, "$1\${scopeTag(\"$2\", tags, suffix)}");
95
+
96
+ this.blocks[this.currentKey()] += contentStatement;
97
+ };
98
+
99
+ HTMLLitVisitor.prototype.MustacheStatement = function(mustache) {
100
+ Visitor.prototype.MustacheStatement.call(this, mustache);
101
+
102
+ if (mustache.path.original === "@index") {
103
+ this.blocks[this.currentKey()] += "${index}";
104
+ } else {
105
+ const path = normalizePath.call(this, mustache.path.original);
106
+ const hasCalculatingClasses = path.includes("this.classes");
107
+
108
+ let parsedCode = "";
109
+
110
+ if (isNodeValue && !mustache.escaped) {
111
+ parsedCode = `\${unsafeHTML(${path})}`;
112
+ } else if (hasCalculatingClasses) {
113
+ if (process.env.UI5_TS) {
114
+ parsedCode = `\${classMap(${path} as ClassMapValue)}`;
115
+ } else {
116
+ parsedCode = `\${classMap(${path})}`;
117
+ }
118
+ } else if (isStyleAttribute) {
119
+ parsedCode = `\${styleMap(${path})}`;
120
+ } else if (skipIfDefined){
121
+ parsedCode = `\${${path}}`;
122
+ } else {
123
+ parsedCode = `\${ifDefined(${path})}`;
124
+ }
125
+
126
+ this.blocks[this.currentKey()] += parsedCode;
127
+ }
128
+ };
129
+
130
+ HTMLLitVisitor.prototype.BlockStatement = function(block) {
131
+ if (block.path.original === "if") {
132
+ visitIfBlock.call(this, block);
133
+ } else if (block.path.original === "unless") {
134
+ visitUnlessBlock.call(this, block);
135
+ } else if (block.path.original === "each") {
136
+ visitEachBlock.call(this, block);
137
+ }
138
+ };
139
+
140
+ HTMLLitVisitor.prototype.currentKey = function() {
141
+ return this.keys[this.keys.length - 1];
142
+ };
143
+
144
+ HTMLLitVisitor.prototype.prevKey = function() {
145
+ return this.keys[this.keys.length - 2];
146
+ };
147
+
148
+ function visitSubExpression(mustache) {
149
+ this.acceptRequired(mustache, "path");
150
+ this.acceptArray(mustache.params);
151
+ this.acceptKey(mustache, "hash");
152
+ }
153
+
154
+ function visitIfBlock(block) {
155
+ visitSubExpression.call(this, block);
156
+
157
+ let params = normalizePath.call(this, block.params[0].original);
158
+ this.blocks[this.currentKey()] += "${ " + params + " ? ";
159
+ this.acceptKey(block, "program");
160
+ this.blocks[this.currentKey()] += " : ";
161
+ if (block.inverse) {
162
+ this.acceptKey(block, "inverse");
163
+ } else {
164
+ this.blocks[this.currentKey()] += "undefined";
165
+ }
166
+ this.blocks[this.currentKey()] += " }";
167
+ }
168
+
169
+ function visitUnlessBlock(block) {
170
+ visitSubExpression.call(this, block);
171
+
172
+ let params = normalizePath.call(this, block.params[0].original);
173
+ this.blocks[this.currentKey()] += "${ !" + params + " ? ";
174
+ this.acceptKey(block, "program");
175
+ this.blocks[this.currentKey()] += " : undefined }";
176
+ }
177
+
178
+ function visitEachBlock(block) {
179
+ var bParamAdded = false;
180
+ visitSubExpression.call(this, block);
181
+
182
+ const reapeatDirectiveParamsTS = "(item, index) => (item as typeof item & {_id?: any})._id || index, (item, index: number)";
183
+ const reapeatDirectiveParamsJS = "(item, index) => item._id || index, (item, index)";
184
+ const repleatDirectiveParams = process.env.UI5_TS ? reapeatDirectiveParamsTS : reapeatDirectiveParamsJS;
185
+ this.blocks[this.currentKey()] += "${ repeat(" + normalizePath.call(this, block.params[0].original) + ", " + repleatDirectiveParams + " => ";
186
+ this.paths.push(normalizePath.call(this, block.params[0].original));
187
+ this.blockLevel++;
188
+
189
+ // block params is [this, context, tags, suffix] for top level blocks
190
+ // blcok params is [this, context, tags, suffix, item, index] for nested blocks
191
+ if (!this.blockParametersUsage.includes("index")) {
192
+ // last item is not index, but an each block is processed, add the paramters for further nested blocks
193
+ bParamAdded = true;
194
+ if (process.env.UI5_TS) {
195
+ this.blockParametersDefinition.push("item: any");
196
+ this.blockParametersDefinition.push("index: number");
197
+ } else {
198
+ this.blockParametersDefinition.push("item");
199
+ this.blockParametersDefinition.push("index");
200
+ }
201
+ this.blockParametersUsage.push("item");
202
+ this.blockParametersUsage.push("index");
203
+ }
204
+ this.acceptKey(block, "program");
205
+ if (bParamAdded) {
206
+ // if parameters were added at this step, remove the last two
207
+ this.blockParametersDefinition.pop();
208
+ this.blockParametersDefinition.pop();
209
+ this.blockParametersUsage.pop();
210
+ this.blockParametersUsage.pop();
211
+ }
212
+ this.blockLevel--;
213
+ this.blocks[this.currentKey()] += ") }";
214
+ }
215
+
216
+ function normalizePath(sPath) {
217
+ let result = replaceAll(replaceAll(replaceAll(sPath, ".this", ""), "this.", ""), "this", "");
218
+
219
+ //read carefully - https://github.com/wycats/handlebars.js/issues/1028
220
+ //kpdecker commented on May 20, 2015
221
+
222
+ if (result.indexOf("@root") === 0) {
223
+ // Trying to access root context via the HBS "@root" variable.
224
+ // Example: {{@root.property}} compiles to "context.property" - called from anywhere within the template.
225
+ result = result.replace("@root", "this");
226
+
227
+ } else if (result.indexOf("../") === 0) {
228
+ let absolutePath;
229
+ const levelsUp = (result.match(/..\//g) || []).length;
230
+
231
+ if (this.blockLevel <= levelsUp) {
232
+ // Trying to access root context from nested loops.
233
+ // Example: {{../../property}} compiles to "context.property" - when currently in a nested level loop.
234
+ // Example: {{../../../property}} compile to "context.property" - when requested levels are not present. fallback to root context.
235
+ absolutePath = `this.${replaceAll(result,"../", "")}`;
236
+ } else {
237
+ // Trying to access upper context (one-level-up) and based on the current lelev, that could be "context" or "item".
238
+ // Example: {{../property}} compiles to "context.property" - when called in a top level loop.
239
+ // Example: {{../property}} compiles to "item.property" - when called in a nested level loop.
240
+ // TODO: the second example, although correctly generated to "item.property", "item" will point to the current object within the nested loop,
241
+ // not the upper level loop as intended. So accessing the upper loop from nested loop is currently not working.
242
+ absolutePath = replaceAll(this.paths[this.paths.length - 1 - levelsUp], ".", "/") + "/" + result;
243
+ }
244
+
245
+ result = replaceAll(path.normalize(absolutePath), path.sep, ".");
246
+
247
+ } else {
248
+ // When neither "@root", nor "../" are used, use the following contexts:
249
+ // - use "context" - for the top level of execution, e.g "this.blockLevel = 0".
250
+ // - use "item" - for any nested level, e.g "this.blockLevel > 0".
251
+ // Example:
252
+ //
253
+ // {{text}} -> compiles to "context.text"
254
+ // {{#each items}}
255
+ // Item text: {{text}}</div> -> compiles to "item.text"
256
+ // {{#each words}}
257
+ // Word text: {{text}}</div> -> compiles to "item.text"
258
+ // {{/each}}
259
+ // Item text: {{text}}</div> -> compiles to "item.text"
260
+ // {{/each}}
261
+ // {{text}} -> compiles to "context.text"
262
+
263
+ const blockPath = this.blockLevel > 0 ? "item" : "this";
264
+ result = result ? replaceAll(blockPath + "/" + result, "/", ".") : blockPath;
265
+ }
266
+
267
+ return result;
268
+ }
269
+
270
+ function replaceAll(str, find, repl) {
271
+ let sResult = str;
272
+ while (sResult.indexOf(find) !== -1) {
273
+ sResult = sResult.replace(find, repl);
274
+ }
275
+ return sResult;
276
+ }
277
+
278
+ module.exports = HTMLLitVisitor;
@@ -0,0 +1,51 @@
1
+ //collects the partials defined with the inline mustache syntax
2
+ //also cleans the handlebars template from the partials definitions
3
+ function collectPartials(hbs) {
4
+ let oResult = {};
5
+
6
+ const re = RegExp("{{#\\*inline\\s* \"(\\w+)\"\\s*}}((.|\\s)*?){{\\/inline}}");
7
+ const regexGroups = {partialKey: 1, partialDefinition: 2};
8
+
9
+ let m;
10
+
11
+ do {
12
+ m = re.exec(hbs);
13
+ if (m) {
14
+ // This is necessary to avoid infinite loops with zero-width matches
15
+ if (m.index === re.lastIndex) {
16
+ re.lastIndex++;
17
+ }
18
+
19
+ // The result can be accessed through the `m`-variable.
20
+ oResult[m[regexGroups.partialKey]] = m[regexGroups.partialDefinition];
21
+
22
+ //remove the partial from the hbs
23
+ hbs = hbs.replace(m[0], "");
24
+ }
25
+ } while (m);
26
+
27
+ return {partials: oResult, hbs: hbs};
28
+ }
29
+
30
+ //replaces the partials usages with their actual definitions
31
+ function replacePartials(hbs, mPartials) {
32
+ let sResultHbs = hbs;
33
+ for (let key in mPartials) {
34
+ if (mPartials.hasOwnProperty(key)) {
35
+ let val = mPartials[key];
36
+ let re = new RegExp("{{\\s*>\\s*" + key + "\\s*}}", "g"); //ex match: {{ > controlData }}
37
+ sResultHbs = sResultHbs.replace(re, val);
38
+ }
39
+ }
40
+
41
+ return sResultHbs;
42
+ }
43
+
44
+ module.exports = {
45
+ resolve: function(hbs) {
46
+ let oResult = collectPartials(hbs);
47
+ let sResultHbs = replacePartials(oResult.hbs, oResult.partials);
48
+
49
+ return sResultHbs;
50
+ }
51
+ };