Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(tools): enable TypeScript as default #8521

Merged
merged 3 commits into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions packages/base/package-scripts.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ const viteConfig = `-c "${require.resolve("@ui5/webcomponents-tools/components-p
const scripts = {
clean: "rimraf jsdoc-dist && rimraf src/generated && rimraf dist && rimraf .port",
lint: `eslint .`,
generate: "cross-env UI5_TS=true nps clean integrate copy generateAssetParameters generateVersionInfo generateStyles generateTemplates",
prepare: "cross-env UI5_TS=true nps clean integrate copy generateAssetParameters generateVersionInfo generateStyles generateTemplates typescript integrate.no-remaining-require",
generate: "nps clean integrate copy generateAssetParameters generateVersionInfo generateStyles generateTemplates",
prepare: "nps clean integrate copy generateAssetParameters generateVersionInfo generateStyles generateTemplates typescript integrate.no-remaining-require",
typescript: "tsc -b",
integrate: {
default: "nps integrate.copy-used-modules integrate.amd-to-es6 integrate.third-party",
Expand All @@ -40,7 +40,7 @@ const scripts = {
generateAssetParameters: `node "${assetParametersScript}"`,
generateVersionInfo: `node "${versionScript}"`,
generateStyles: `node "${stylesScript}"`,
generateTemplates: `mkdirp src/generated/templates && cross-env UI5_BASE=true UI5_TS=true node "${LIB}/hbs2ui5/index.js" -d test/elements -o src/generated/templates`,
generateTemplates: `mkdirp src/generated/templates && cross-env UI5_BASE=true node "${LIB}/hbs2ui5/index.js" -d test/elements -o src/generated/templates`,
generateAPI: {
default: "nps generateAPI.generateCEM generateAPI.validateCEM",
generateCEM: `cem analyze --config "${LIB}/cem/custom-elements-manifest.config.mjs" --dev`,
Expand Down
1 change: 0 additions & 1 deletion packages/create-package/template/package-scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ const getScripts = require("@ui5/webcomponents-tools/components-package/nps.js")

const options = {
port: 8080,
typescript: true,
};

const scripts = getScripts(options);
Expand Down
1 change: 0 additions & 1 deletion packages/fiori/package-scripts.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ const options = {
portStep: 2,
dev: true,
fioriPackage: true,
typescript: true,
noWatchTS: true,
illustrationsData: [
{
Expand Down
1 change: 0 additions & 1 deletion packages/icons-business-suite/package-scripts.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ const getScripts = require("@ui5/webcomponents-tools/icons-collection/nps.js");
const options = {
collectionName: "SAP-icons-business-suite",
versions: ["v1", "v2"],
typescript: true,
};

const scripts = getScripts(options);
Expand Down
1 change: 0 additions & 1 deletion packages/main/package-scripts.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ const getScripts = require("@ui5/webcomponents-tools/components-package/nps.js")
const options = {
port: 8080,
portStep: 2,
typescript: true,
noWatchTS: true,
dev: true,
};
Expand Down
4 changes: 2 additions & 2 deletions packages/theming/package-scripts.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ const LIB = path.join(__dirname, `../tools/lib/`);
module.exports = {
scripts: {
clean: "rimraf dist && rimraf src/generated",
generate: `cross-env UI5_TS=true nps build.postcss build.jsonImports`,
generate: "nps build.postcss build.jsonImports",
build: {
default: `cross-env UI5_TS=true nps clean build.src build.postcss build.jsonImports build.typescript generateReport`,
default: "nps clean build.src build.postcss build.jsonImports build.typescript generateReport",
src: `copy-and-watch "src/**/*.{json}" dist/`,
typescript: "tsc",
postcss: `node "${LIB}/css-processors/css-processor-themes.mjs"`,
Expand Down
29 changes: 12 additions & 17 deletions packages/tools/components-package/nps.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,17 @@ const getScripts = (options) => {
// The script creates the "src/generated/js-imports/Illustration.js" file that registers loaders (dynamic JS imports) for each illustration
const createIllustrationsLoadersScript = illustrationsData.map(illustrations => `node ${LIB}/generate-js-imports/illustrations.js ${illustrations.destinationPath} ${illustrations.dynamicImports.outputFile} ${illustrations.set} ${illustrations.collection} ${illustrations.dynamicImports.location} ${illustrations.dynamicImports.filterOut.join(" ")}`).join(" && ");

const tsOption = options.typescript;
const tsCommandOld = tsOption ? "tsc" : "";
let tsWatchCommandStandalone = tsOption ? "tsc --watch" : "";
let tsWatchCommandStandalone = "tsc --watch";
// this command is only used for standalone projects. monorepo projects get their watch from vite, so opt-out here
if (options.noWatchTS) {
tsWatchCommandStandalone = "";
}
const tsCrossEnv = tsOption ? "cross-env UI5_TS=true" : "";

if (tsOption) {
try {
require("typescript");
} catch(e) {
console.error(`TypeScript is not found. Try to install it by running \`npm install --save-dev typescript\` if you are using npm or by running \`yarn add --dev typescript\` if you are using yarn.`);
process.exit(e.code);
}
try {
require("typescript");
} catch(e) {
console.error(`TypeScript is not found. Try to install it by running \`npm install --save-dev typescript\` if you are using npm or by running \`yarn add --dev typescript\` if you are using yarn.`);
process.exit(e.code);
}

let viteConfig;
Expand Down Expand Up @@ -58,19 +53,19 @@ const getScripts = (options) => {
lint: `eslint . ${eslintConfig}`,
lintfix: `eslint . ${eslintConfig} --fix`,
generate: {
default: `${tsCrossEnv} nps prepare.all`,
default: "nps prepare.all",
all: 'concurrently "nps build.templates" "nps build.i18n" "nps prepare.styleRelated" "nps copy" "nps build.illustrations"',
styleRelated: "nps build.styles build.jsonImports build.jsImports",
},
prepare: {
default: `${tsCrossEnv} nps clean prepare.all copy prepare.typescript generateAPI`,
default: "nps clean prepare.all copy prepare.typescript generateAPI",
all: 'concurrently "nps build.templates" "nps build.i18n" "nps prepare.styleRelated" "nps build.illustrations"',
styleRelated: "nps build.styles build.jsonImports build.jsImports",
typescript: tsCommandOld,
typescript: "tsc",
},
build: {
default: "nps prepare lint build.bundle", // build.bundle2
templates: `mkdirp src/generated/templates && ${tsCrossEnv} node "${LIB}/hbs2ui5/index.js" -d src/ -o src/generated/templates`,
templates: `mkdirp src/generated/templates && node "${LIB}/hbs2ui5/index.js" -d src/ -o src/generated/templates`,
styles: {
default: `concurrently "nps build.styles.themes" "nps build.styles.components" "nps build.styles.componentStyles"`,
themes: `node "${LIB}/css-processors/css-processor-themes.mjs"`,
Expand Down Expand Up @@ -102,7 +97,7 @@ const getScripts = (options) => {
props: `node "${LIB}/copy-and-watch/index.js" --silent "src/**/*.properties" dist/`,
},
watch: {
default: `${tsCrossEnv} concurrently "nps watch.templates" "nps watch.typescript" "nps watch.api" "nps watch.src" "nps watch.styles" "nps watch.i18n" "nps watch.props"`,
default: `concurrently "nps watch.templates" "nps watch.typescript" "nps watch.api" "nps watch.src" "nps watch.styles" "nps watch.i18n" "nps watch.props"`,
devServer: 'concurrently "nps watch.default" "nps watch.bundle"',
src: 'nps "copy.src --watch --safe --skip-initial-copy"',
typescript: tsWatchCommandStandalone,
Expand Down Expand Up @@ -137,7 +132,7 @@ const getScripts = (options) => {
bundle: `node ${LIB}/dev-server/dev-server.js ${viteConfig}`,
},
generateAPI: {
default: `nps ${ tsOption ? "generateAPI.generateCEM generateAPI.validateCEM" : "generateAPI.prepare generateAPI.preprocess generateAPI.jsdoc generateAPI.cleanup generateAPI.prepareManifest generateAPI.validateCEM"}`,
default: `nps generateAPI.generateCEM generateAPI.validateCEM`,
generateCEM: `cem analyze --config "${LIB}/cem/custom-elements-manifest.config.mjs" ${ options.dev ? "--dev" : "" }`,
validateCEM: `node "${LIB}/cem/validate.js" ${ options.dev ? "--dev" : "" }`,
prepare: `node "${LIB}/copy-and-watch/index.js" --silent "dist/**/*.js" jsdoc-dist/`,
Expand Down
8 changes: 3 additions & 5 deletions packages/tools/icons-collection/nps.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,14 @@ const copyIconAssetsCommand = (options) => {
const getScripts = (options) => {
const createJSImportsCmd = createIconImportsCommand(options);
const copyAssetsCmd = copyIconAssetsCommand(options);
const tsCommand = options.typescript ? "tsc --build" : "";
const tsCrossEnv = options.typescript ? "cross-env UI5_TS=true" : "";

const scripts = {
clean: "rimraf dist && rimraf src/generated",
copy: copyAssetsCmd,
generate: `${tsCrossEnv} nps clean copy build.i18n build.icons build.jsonImports copyjson`,
generate: "nps clean copy build.i18n build.icons build.jsonImports copyjson",
copyjson: "copy-and-watch \"src/generated/**/*.json\" dist/generated/",
build: {
default: `${tsCrossEnv} nps clean copy build.i18n typescript build.icons build.jsonImports`,
default: "nps clean copy build.i18n typescript build.icons build.jsonImports",
i18n: {
default: "nps build.i18n.defaultsjs build.i18n.json",
defaultsjs: `mkdirp dist/generated/i18n && node "${LIB}/i18n/defaults.js" src/i18n src/generated/i18n`,
Expand All @@ -62,7 +60,7 @@ const getScripts = (options) => {
},
icons: createJSImportsCmd,
},
typescript: tsCommand,
typescript: "tsc --build",
};

return scripts;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@ import chokidar from "chokidar";
import scopeVariables from "./scope-variables.mjs";
import { writeFileIfChanged, getFileContent } from "./shared.mjs";

const tsMode = process.env.UI5_TS === "true";
const extension = tsMode ? ".css.ts" : ".css.js";

const packageJSON = JSON.parse(fs.readFileSync("./package.json"))
const inputFilesGlob = "src/themes/*.css";
const restArgs = process.argv.slice(2);
Expand All @@ -27,8 +24,8 @@ let customPlugin = {
writeFile(f.path, newText);

// JS/TS
const jsPath = f.path.replace(/dist[\/\\]css/, "src/generated/").replace(".css", extension);
const jsContent = getFileContent(tsMode, jsPath, packageJSON.name, "\`" + newText + "\`", true);
const jsPath = f.path.replace(/dist[\/\\]css/, "src/generated/").replace(".css", ".css.ts");
const jsContent = getFileContent(jsPath, packageJSON.name, "\`" + newText + "\`", true);
writeFileIfChanged(jsPath, jsContent);
});
})
Expand Down
7 changes: 2 additions & 5 deletions packages/tools/lib/css-processors/css-processor-themes.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@ import combineDuplicatedSelectors from "../postcss-combine-duplicated-selectors/
import { writeFileIfChanged, stripThemingBaseContent, getFileContent } from "./shared.mjs";
import scopeVariables from "./scope-variables.mjs";

const tsMode = process.env.UI5_TS === "true";
const extension = tsMode ? ".css.ts" : ".css.js";

const packageJSON = JSON.parse(fs.readFileSync("./package.json"))

let inputFiles = await globby("src/**/parameters-bundle.css");
Expand Down Expand Up @@ -50,8 +47,8 @@ let scopingPlugin = {
writeFileIfChanged(jsonPath, JSON.stringify({_: data}));

// JS/TS
const jsPath = f.path.replace(/dist[\/\\]css/, "src/generated/").replace(".css", extension);
const jsContent = getFileContent(tsMode, jsPath, packageJSON.name, "\`" + newText + "\`");
const jsPath = f.path.replace(/dist[\/\\]css/, "src/generated/").replace(".css", ".css.ts");
const jsContent = getFileContent(jsPath, packageJSON.name, "\`" + newText + "\`");
writeFileIfChanged(jsPath, jsContent);
});
})
Expand Down
16 changes: 1 addition & 15 deletions packages/tools/lib/css-processors/shared.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,7 @@ registerThemePropertiesLoader("${packageName}", "${DEFAULT_THEME}", async () =>
`;
};

const getFileContent = (tsMode, targetFile, packageName, css, includeDefaultTheme) => {
if (tsMode) {
return getTSContent(targetFile, packageName, css, includeDefaultTheme);
}

return getJSContent(targetFile, packageName, css, includeDefaultTheme);
}

const getTSContent = (targetFile, packageName, css, includeDefaultTheme) => {
const getFileContent = (targetFile, packageName, css, includeDefaultTheme) => {
const typeImport = "import type { StyleData } from \"@ui5/webcomponents-base/dist/types.js\";"
const defaultTheme = includeDefaultTheme ? getDefaultThemeCode(packageName) : "";

Expand All @@ -67,10 +59,4 @@ export default styleData;
`;
}

const getJSContent = (targetFile, packageName, css, includeDefaultTheme) => {
const defaultTheme = includeDefaultTheme ? getDefaultThemeCode(packageName) : "";

return `${defaultTheme}export default {packageName:"${packageName}",fileName:"${targetFile.substr(targetFile.lastIndexOf("themes"))}",content:${css}}`
}

export { writeFileIfChanged, stripThemingBaseContent, getFileContent}
7 changes: 2 additions & 5 deletions packages/tools/lib/generate-json-imports/i18n.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
const fs = require("fs").promises;
const path = require('path');

const isTypeScript = process.env.UI5_TS;
const ext = isTypeScript ? 'ts' : 'js';

const generate = async () => {

const packageName = JSON.parse(await fs.readFile("package.json")).name;

const inputFolder = path.normalize(process.argv[2]);
const outputFile = path.normalize(`${process.argv[3]}/i18n-static.${ext}`);
const outputFileDynamic = path.normalize(`${process.argv[3]}/i18n.${ext}`);
const outputFile = path.normalize(`${process.argv[3]}/i18n-static.ts`);
const outputFileDynamic = path.normalize(`${process.argv[3]}/i18n.ts`);

// All languages present in the file system
const files = await fs.readdir(inputFolder);
Expand Down
7 changes: 2 additions & 5 deletions packages/tools/lib/generate-json-imports/themes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@ const fs = require("fs").promises;
const path = require('path');
const assets = require("../../assets-meta.js");

const isTypeScript = process.env.UI5_TS;
const ext = isTypeScript ? 'ts' : 'js';

const generate = async () => {
const inputFolder = path.normalize(process.argv[2]);
const outputFile = path.normalize(`${process.argv[3]}/Themes-static.${ext}`);
const outputFileDynamic = path.normalize(`${process.argv[3]}/Themes.${ext}`);
const outputFile = path.normalize(`${process.argv[3]}/Themes-static.ts`);
const outputFileDynamic = path.normalize(`${process.argv[3]}/Themes.ts`);

// All supported optional themes
const allThemes = assets.themes.all;
Expand Down
4 changes: 1 addition & 3 deletions packages/tools/lib/hbs2lit/src/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,10 @@ const hbs2lit = async (file, componentName) => {

sPreprocessed = removeWhiteSpaces(sPreprocessed);

const blockSignature = process.env.UI5_TS ? `this: ${componentName}` : ""

// icons hack
if (sPreprocessed.startsWith("<g ") || sPreprocessed.startsWith("<g>")) {
return `
function block0 (${blockSignature}) {
function block0 (this: ${componentName}) {
return svg\`${sPreprocessed}\`
}`;
}
Expand Down
22 changes: 6 additions & 16 deletions packages/tools/lib/hbs2lit/src/litVisitor2.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ function HTMLLitVisitor(componentName, debug) {
this.blockLevel = 0;
this.componentName = componentName
const blockParametersDefinitionTS = [`this: ${componentName}`, "context: UI5Element", "tags: string[]", "suffix: string | undefined"];
const blockParametersDefinitionJS = ["context", "tags", "suffix"];
this.blockParametersDefinition = process.env.UI5_TS ? blockParametersDefinitionTS : blockParametersDefinitionJS;
this.blockParametersDefinition = blockParametersDefinitionTS;
this.blockParametersUsage = ["this", "context", "tags", "suffix"];
this.paths = []; //contains all normalized relative paths
this.debug = debug;
Expand Down Expand Up @@ -110,11 +109,7 @@ HTMLLitVisitor.prototype.MustacheStatement = function(mustache) {
if (isNodeValue && !mustache.escaped) {
parsedCode = `\${unsafeHTML(${path})}`;
} else if (hasCalculatingClasses) {
if (process.env.UI5_TS) {
parsedCode = `\${classMap(${path} as ClassMapValue)}`;
} else {
parsedCode = `\${classMap(${path})}`;
}
parsedCode = `\${classMap(${path} as ClassMapValue)}`;
} else if (isStyleAttribute) {
parsedCode = `\${styleMap(${path})}`;
} else if (skipIfDefined){
Expand Down Expand Up @@ -180,8 +175,7 @@ function visitEachBlock(block) {
visitSubExpression.call(this, block);

const reapeatDirectiveParamsTS = "(item, index) => (item as typeof item & {_id?: any})._id || index, (item, index: number)";
const reapeatDirectiveParamsJS = "(item, index) => item._id || index, (item, index)";
const repleatDirectiveParams = process.env.UI5_TS ? reapeatDirectiveParamsTS : reapeatDirectiveParamsJS;
const repleatDirectiveParams = reapeatDirectiveParamsTS;
this.blocks[this.currentKey()] += "${ repeat(" + normalizePath.call(this, block.params[0].original) + ", " + repleatDirectiveParams + " => ";
this.paths.push(normalizePath.call(this, block.params[0].original));
this.blockLevel++;
Expand All @@ -191,13 +185,9 @@ function visitEachBlock(block) {
if (!this.blockParametersUsage.includes("index")) {
// last item is not index, but an each block is processed, add the paramters for further nested blocks
bParamAdded = true;
if (process.env.UI5_TS) {
this.blockParametersDefinition.push("item: any");
this.blockParametersDefinition.push("index: number");
} else {
this.blockParametersDefinition.push("item");
this.blockParametersDefinition.push("index");
}
this.blockParametersDefinition.push("item: any");
this.blockParametersDefinition.push("index: number");

this.blockParametersUsage.push("item");
this.blockParametersUsage.push("index");
}
Expand Down
5 changes: 1 addition & 4 deletions packages/tools/lib/hbs2lit/src/svgProcessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,10 @@ function getSVGBlock(input, blockCounter) {
const definitionTS = `\nfunction blockSVG${blockCounter} (this: any, context: UI5Element, tags: string[], suffix: string | undefined) {
return svg\`${input}\`;
};`;
const definitionJS = `\nfunction blockSVG${blockCounter} (context, tags, suffix) {
return svg\`${input}\`;
};`;

return {
usage: `\${blockSVG${blockCounter}.call(this, context, tags, suffix)}`,
definition: process.env.UI5_TS ? definitionTS : definitionJS,
definition: definitionTS,
};
}

Expand Down
4 changes: 0 additions & 4 deletions packages/tools/lib/hbs2ui5/RenderTemplates/LitRenderer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
const tsImports = (controlName, hasTypes) => {
if (!process.env.UI5_TS) {
return "";
}

const importPrefix = process.env.UI5_BASE ? "../../../" : "@ui5/webcomponents-base/dist/"

return `import type UI5Element from "${importPrefix}UI5Element.js";
Expand Down
2 changes: 1 addition & 1 deletion packages/tools/lib/hbs2ui5/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ const writeRenderers = async (outputDir, controlName, fileContent) => {

await fs.mkdir(outputDir, { recursive: true });

const compiledFilePath = `${outputDir}${path.sep}${controlName}Template.lit.${process.env.UI5_TS ? "ts" : "js"}`;
const compiledFilePath = `${outputDir}${path.sep}${controlName}Template.lit.ts`;

// strip DOS line endings because the break the source maps
let fileContentUnix = fileContent.replace(/\r\n/g, "\n");
Expand Down
Loading