UNPKG

@storm-software/tsdown

Version:

A package containing `tsdown` utilities for building Storm Software libraries and applications

1,105 lines (1,083 loc) 45.1 kB
import { COLOR_KEYS, LogLevel, STORM_DEFAULT_DOCS, STORM_DEFAULT_HOMEPAGE, STORM_DEFAULT_LICENSING, cleanDirectories, correctPaths, findWorkspaceRoot, formatLogMessage, getDefaultConfig, getLogLevel, getLogLevelLabel, getStopwatch, isVerbose, joinPaths, stormWorkspaceConfigSchema, writeDebug, writeFatal, writeSuccess, writeTrace, writeWarning } from "./chunk-MZ443ZDH.js"; import { DEFAULT_BUILD_OPTIONS } from "./chunk-PR5HLZXS.js"; import { __name } from "./chunk-SHUYVCID.js"; // src/build.ts import { createProjectGraphAsync, readProjectsConfigurationFromProjectGraph as readProjectsConfigurationFromProjectGraph2, writeJsonFile } from "@nx/devkit"; // ../build-tools/src/config.ts var DEFAULT_ENVIRONMENT = "production"; var DEFAULT_TARGET = "esnext"; var DEFAULT_ORGANIZATION = "storm-software"; // ../build-tools/src/plugins/swc.ts import { transform } from "@swc/core"; // ../build-tools/src/plugins/ts-resolve.ts import fs from "node:fs"; import { builtinModules } from "node:module"; import path from "node:path"; import _resolve from "resolve"; // ../build-tools/src/plugins/type-definitions.ts import { stripIndents } from "@nx/devkit"; import { relative } from "path"; // ../build-tools/src/utilities/copy-assets.ts import { CopyAssetsHandler } from "@nx/js/src/utils/assets/copy-assets-handler"; import { glob } from "glob"; import { readFile, writeFile } from "node:fs/promises"; var copyAssets = /* @__PURE__ */ __name(async (config, assets, outputPath, projectRoot, sourceRoot, generatePackageJson2 = true, includeSrc = false, banner, footer) => { const pendingAssets = Array.from(assets ?? []); pendingAssets.push({ input: projectRoot, glob: "*.md", output: "." }); pendingAssets.push({ input: ".", glob: "LICENSE", output: "." }); if (generatePackageJson2 === false) { pendingAssets.push({ input: projectRoot, glob: "package.json", output: "." }); } if (includeSrc === true) { pendingAssets.push({ input: sourceRoot, glob: "**/{*.ts,*.tsx,*.js,*.jsx}", output: "src/" }); } writeTrace(`\u{1F4DD} Copying the following assets to the output directory: ${pendingAssets.map((pendingAsset) => typeof pendingAsset === "string" ? ` - ${pendingAsset} -> ${outputPath}` : ` - ${pendingAsset.input}/${pendingAsset.glob} -> ${joinPaths(outputPath, pendingAsset.output)}`).join("\n")}`, config); const assetHandler = new CopyAssetsHandler({ projectDir: projectRoot, rootDir: config.workspaceRoot, outputDir: outputPath, assets: pendingAssets }); await assetHandler.processAllAssetsOnce(); if (includeSrc === true) { writeDebug(`\u{1F4DD} Adding banner and writing source files: ${joinPaths(outputPath, "src")}`, config); const files = await glob([ joinPaths(config.workspaceRoot, outputPath, "src/**/*.ts"), joinPaths(config.workspaceRoot, outputPath, "src/**/*.tsx"), joinPaths(config.workspaceRoot, outputPath, "src/**/*.js"), joinPaths(config.workspaceRoot, outputPath, "src/**/*.jsx") ]); await Promise.allSettled(files.map(async (file) => writeFile(file, `${banner && typeof banner === "string" ? banner.startsWith("//") ? banner : `// ${banner}` : ""} ${await readFile(file, "utf8")} ${footer && typeof footer === "string" ? footer.startsWith("//") ? footer : `// ${footer}` : ""}`))); } }, "copyAssets"); // ../build-tools/src/utilities/generate-package-json.ts import { calculateProjectBuildableDependencies } from "@nx/js/src/utils/buildable-libs-utils"; import { Glob } from "glob"; import { existsSync, readFileSync } from "node:fs"; import { readFile as readFile2 } from "node:fs/promises"; import { readCachedProjectGraph, readProjectsConfigurationFromProjectGraph } from "nx/src/project-graph/project-graph"; var addPackageDependencies = /* @__PURE__ */ __name(async (workspaceRoot, projectRoot, projectName, packageJson) => { const projectGraph = readCachedProjectGraph(); const projectDependencies = calculateProjectBuildableDependencies(void 0, projectGraph, workspaceRoot, projectName, process.env.NX_TASK_TARGET_TARGET || "build", process.env.NX_TASK_TARGET_CONFIGURATION || "production", true); const localPackages = []; for (const project of projectDependencies.dependencies.filter((dep) => dep.node.type === "lib" && dep.node.data?.root !== projectRoot && dep.node.data?.root !== workspaceRoot)) { const projectNode = project.node; if (projectNode.data.root) { const projectPackageJsonPath = joinPaths(workspaceRoot, projectNode.data.root, "package.json"); if (existsSync(projectPackageJsonPath)) { const projectPackageJsonContent = await readFile2(projectPackageJsonPath, "utf8"); const projectPackageJson = JSON.parse(projectPackageJsonContent); if (projectPackageJson.private !== true) { localPackages.push(projectPackageJson); } } } } if (localPackages.length > 0) { writeTrace(`\u{1F4E6} Adding local packages to package.json: ${localPackages.map((p) => p.name).join(", ")}`); const projectJsonFile = await readFile2(joinPaths(projectRoot, "project.json"), "utf8"); const projectJson = JSON.parse(projectJsonFile); const projectName2 = projectJson.name; const projectConfigurations = readProjectsConfigurationFromProjectGraph(projectGraph); if (!projectConfigurations?.projects?.[projectName2]) { throw new Error("The Build process failed because the project does not have a valid configuration in the project.json file. Check if the file exists in the root of the project."); } const implicitDependencies = projectConfigurations.projects?.[projectName2].implicitDependencies?.reduce((ret, dep) => { if (projectConfigurations.projects?.[dep]) { const depPackageJsonPath = joinPaths(workspaceRoot, projectConfigurations.projects[dep].root, "package.json"); if (existsSync(depPackageJsonPath)) { const depPackageJsonContent = readFileSync(depPackageJsonPath, "utf8"); const depPackageJson = JSON.parse(depPackageJsonContent); if (depPackageJson.private !== true && !ret.includes(depPackageJson.name)) { ret.push(depPackageJson.name); } } } return ret; }, []); packageJson.dependencies = localPackages.reduce((ret, localPackage) => { if (!ret[localPackage.name] && !implicitDependencies?.includes(localPackage.name) && packageJson.devDependencies?.[localPackage.name] === void 0) { ret[localPackage.name] = `^${localPackage.version || "0.0.1"}`; } return ret; }, packageJson.dependencies ?? {}); packageJson.devDependencies = localPackages.reduce((ret, localPackage) => { if (!ret[localPackage.name] && implicitDependencies?.includes(localPackage.name) && packageJson.dependencies?.[localPackage.name] === void 0) { ret[localPackage.name] = localPackage.version || "0.0.1"; } return ret; }, packageJson.devDependencies ?? {}); } else { writeTrace("\u{1F4E6} No local packages dependencies to add to package.json"); } return packageJson; }, "addPackageDependencies"); var addWorkspacePackageJsonFields = /* @__PURE__ */ __name(async (config, projectRoot, sourceRoot, projectName, includeSrc = false, packageJson) => { const workspaceRoot = config.workspaceRoot ? config.workspaceRoot : findWorkspaceRoot(); const workspacePackageJsonContent = await readFile2(joinPaths(workspaceRoot, "package.json"), "utf8"); const workspacePackageJson = JSON.parse(workspacePackageJsonContent); packageJson.type ??= "module"; packageJson.sideEffects ??= false; if (includeSrc === true) { let distSrc = sourceRoot.replace(projectRoot, ""); if (distSrc.startsWith("/")) { distSrc = distSrc.substring(1); } packageJson.source ??= `${joinPaths(distSrc, "index.ts").replaceAll("\\", "/")}`; } packageJson.files ??= [ "dist/**/*" ]; if (includeSrc === true && !packageJson.files.includes("src")) { packageJson.files.push("src/**/*"); } packageJson.publishConfig ??= { access: "public" }; packageJson.description ??= workspacePackageJson.description; packageJson.homepage ??= workspacePackageJson.homepage; packageJson.bugs ??= workspacePackageJson.bugs; packageJson.license ??= workspacePackageJson.license; packageJson.keywords ??= workspacePackageJson.keywords; packageJson.funding ??= workspacePackageJson.funding; packageJson.author ??= workspacePackageJson.author; packageJson.maintainers ??= workspacePackageJson.maintainers; if (!packageJson.maintainers && packageJson.author) { packageJson.maintainers = [ packageJson.author ]; } packageJson.contributors ??= workspacePackageJson.contributors; if (!packageJson.contributors && packageJson.author) { packageJson.contributors = [ packageJson.author ]; } packageJson.repository ??= workspacePackageJson.repository; packageJson.repository.directory ??= projectRoot ? projectRoot : joinPaths("packages", projectName); return packageJson; }, "addWorkspacePackageJsonFields"); var addPackageJsonExport = /* @__PURE__ */ __name((file, type = "module", sourceRoot) => { let entry = file.replaceAll("\\", "/"); if (sourceRoot) { entry = entry.replace(sourceRoot, ""); } return { import: { types: `./dist/${entry}.d.${type === "module" ? "ts" : "mts"}`, default: `./dist/${entry}.${type === "module" ? "js" : "mjs"}` }, require: { types: `./dist/${entry}.d.${type === "commonjs" ? "ts" : "cts"}`, default: `./dist/${entry}.${type === "commonjs" ? "js" : "cjs"}` }, default: { types: `./dist/${entry}.d.ts`, default: `./dist/${entry}.js` } }; }, "addPackageJsonExport"); // ../config-tools/src/config-file/get-config-file.ts import { loadConfig } from "c12"; import defu from "defu"; var getConfigFileByName = /* @__PURE__ */ __name(async (fileName, filePath, options = {}) => { const workspacePath = filePath || findWorkspaceRoot(filePath); const configs = await Promise.all([ loadConfig({ cwd: workspacePath, packageJson: true, name: fileName, envName: fileName?.toUpperCase(), jitiOptions: { debug: false, fsCache: process.env.STORM_SKIP_CACHE === "true" ? false : joinPaths(process.env.STORM_CACHE_DIR || "node_modules/.cache/storm", "jiti") }, ...options }), loadConfig({ cwd: workspacePath, packageJson: true, name: fileName, envName: fileName?.toUpperCase(), jitiOptions: { debug: false, fsCache: process.env.STORM_SKIP_CACHE === "true" ? false : joinPaths(process.env.STORM_CACHE_DIR || "node_modules/.cache/storm", "jiti") }, configFile: fileName, ...options }) ]); return defu(configs[0] ?? {}, configs[1] ?? {}); }, "getConfigFileByName"); var getConfigFile = /* @__PURE__ */ __name(async (filePath, additionalFileNames = []) => { const workspacePath = filePath ? filePath : findWorkspaceRoot(filePath); const result = await getConfigFileByName("storm-workspace", workspacePath); let config = result.config; const configFile = result.configFile; if (config && configFile && Object.keys(config).length > 0 && !config.skipConfigLogging) { writeTrace(`Found Storm configuration file "${configFile.includes(`${workspacePath}/`) ? configFile.replace(`${workspacePath}/`, "") : configFile}" at "${workspacePath}"`, { logLevel: "all" }); } if (additionalFileNames && additionalFileNames.length > 0) { const results = await Promise.all(additionalFileNames.map((fileName) => getConfigFileByName(fileName, workspacePath))); for (const result2 of results) { if (result2?.config && result2?.configFile && Object.keys(result2.config).length > 0) { if (!config.skipConfigLogging && !result2.config.skipConfigLogging) { writeTrace(`Found alternative configuration file "${result2.configFile.includes(`${workspacePath}/`) ? result2.configFile.replace(`${workspacePath}/`, "") : result2.configFile}" at "${workspacePath}"`, { logLevel: "all" }); } config = defu(result2.config ?? {}, config ?? {}); } } } if (!config) { return void 0; } config.configFile = configFile; return config; }, "getConfigFile"); // ../config-tools/src/create-storm-config.ts import defu2 from "defu"; // ../config-tools/src/env/get-env.ts var getExtensionEnv = /* @__PURE__ */ __name((extensionName) => { const prefix = `STORM_EXTENSION_${extensionName.toUpperCase()}_`; return Object.keys(process.env).filter((key) => key.startsWith(prefix)).reduce((ret, key) => { const name = key.replace(prefix, "").split("_").map((i) => i.length > 0 ? i.trim().charAt(0).toUpperCase() + i.trim().slice(1) : "").join(""); if (name) { ret[name] = process.env[key]; } return ret; }, {}); }, "getExtensionEnv"); var getConfigEnv = /* @__PURE__ */ __name(() => { const prefix = "STORM_"; let config = { extends: process.env[`${prefix}EXTENDS`] || void 0, name: process.env[`${prefix}NAME`] || void 0, namespace: process.env[`${prefix}NAMESPACE`] || void 0, owner: process.env[`${prefix}OWNER`] || void 0, bot: { name: process.env[`${prefix}BOT_NAME`] || void 0, email: process.env[`${prefix}BOT_EMAIL`] || void 0 }, release: { banner: process.env[`${prefix}RELEASE_BANNER`] || void 0, header: process.env[`${prefix}RELEASE_HEADER`] || void 0, footer: process.env[`${prefix}RELEASE_FOOTER`] || void 0 }, error: { codesFile: process.env[`${prefix}ERROR_CODES_FILE`] || void 0, url: process.env[`${prefix}ERROR_URL`] || void 0 }, account: { twitter: process.env[`${prefix}ACCOUNT_TWITTER`] || void 0, discord: process.env[`${prefix}ACCOUNT_DISCORD`] || void 0, telegram: process.env[`${prefix}ACCOUNT_TELEGRAM`] || void 0, slack: process.env[`${prefix}ACCOUNT_SLACK`] || void 0, medium: process.env[`${prefix}ACCOUNT_MEDIUM`] || void 0, github: process.env[`${prefix}ACCOUNT_GITHUB`] || void 0 }, organization: process.env[`${prefix}ORGANIZATION`] || void 0, packageManager: process.env[`${prefix}PACKAGE_MANAGER`] || void 0, license: process.env[`${prefix}LICENSE`] || void 0, homepage: process.env[`${prefix}HOMEPAGE`] || void 0, docs: process.env[`${prefix}DOCS`] || void 0, licensing: process.env[`${prefix}LICENSING`] || void 0, contact: process.env[`${prefix}CONTACT`] || void 0, timezone: process.env[`${prefix}TIMEZONE`] || process.env.TZ || void 0, locale: process.env[`${prefix}LOCALE`] || process.env.LOCALE || void 0, configFile: process.env[`${prefix}CONFIG_FILE`] ? correctPaths(process.env[`${prefix}CONFIG_FILE`]) : void 0, workspaceRoot: process.env[`${prefix}WORKSPACE_ROOT`] ? correctPaths(process.env[`${prefix}WORKSPACE_ROOT`]) : void 0, directories: { cache: process.env[`${prefix}CACHE_DIR`] ? correctPaths(process.env[`${prefix}CACHE_DIR`]) : void 0, data: process.env[`${prefix}DATA_DIR`] ? correctPaths(process.env[`${prefix}DATA_DIR`]) : void 0, config: process.env[`${prefix}CONFIG_DIR`] ? correctPaths(process.env[`${prefix}CONFIG_DIR`]) : void 0, temp: process.env[`${prefix}TEMP_DIR`] ? correctPaths(process.env[`${prefix}TEMP_DIR`]) : void 0, log: process.env[`${prefix}LOG_DIR`] ? correctPaths(process.env[`${prefix}LOG_DIR`]) : void 0, build: process.env[`${prefix}BUILD_DIR`] ? correctPaths(process.env[`${prefix}BUILD_DIR`]) : void 0 }, skipCache: process.env[`${prefix}SKIP_CACHE`] !== void 0 ? Boolean(process.env[`${prefix}SKIP_CACHE`]) : void 0, mode: (process.env[`${prefix}MODE`] ?? process.env.NODE_ENV ?? process.env.ENVIRONMENT) || void 0, // ci: // process.env[`${prefix}CI`] !== undefined // ? Boolean( // process.env[`${prefix}CI`] ?? // process.env.CI ?? // process.env.CONTINUOUS_INTEGRATION // ) // : undefined, repository: process.env[`${prefix}REPOSITORY`] || void 0, branch: process.env[`${prefix}BRANCH`] || void 0, preid: process.env[`${prefix}PRE_ID`] || void 0, externalPackagePatterns: process.env[`${prefix}EXTERNAL_PACKAGE_PATTERNS`] ? JSON.parse(process.env[`${prefix}EXTERNAL_PACKAGE_PATTERNS`]) : [], registry: { github: process.env[`${prefix}REGISTRY_GITHUB`] || void 0, npm: process.env[`${prefix}REGISTRY_NPM`] || void 0, cargo: process.env[`${prefix}REGISTRY_CARGO`] || void 0, cyclone: process.env[`${prefix}REGISTRY_CYCLONE`] || void 0, container: process.env[`${prefix}REGISTRY_CONTAINER`] || void 0 }, logLevel: process.env[`${prefix}LOG_LEVEL`] !== null && process.env[`${prefix}LOG_LEVEL`] !== void 0 ? process.env[`${prefix}LOG_LEVEL`] && Number.isSafeInteger(Number.parseInt(process.env[`${prefix}LOG_LEVEL`])) ? getLogLevelLabel(Number.parseInt(process.env[`${prefix}LOG_LEVEL`])) : process.env[`${prefix}LOG_LEVEL`] : void 0, skipConfigLogging: process.env[`${prefix}SKIP_CONFIG_LOGGING`] !== void 0 ? Boolean(process.env[`${prefix}SKIP_CONFIG_LOGGING`]) : void 0 }; const themeNames = Object.keys(process.env).filter((envKey) => envKey.startsWith(`${prefix}COLOR_`) && COLOR_KEYS.every((colorKey) => !envKey.startsWith(`${prefix}COLOR_LIGHT_${colorKey}`) && !envKey.startsWith(`${prefix}COLOR_DARK_${colorKey}`))); config.colors = themeNames.length > 0 ? themeNames.reduce((ret, themeName) => { ret[themeName] = getThemeColorConfigEnv(prefix, themeName); return ret; }, {}) : getThemeColorConfigEnv(prefix); if (config.docs === STORM_DEFAULT_DOCS) { if (config.homepage === STORM_DEFAULT_HOMEPAGE) { config.docs = `${STORM_DEFAULT_HOMEPAGE}/projects/${config.name}/docs`; } else { config.docs = `${config.homepage}/docs`; } } if (config.licensing === STORM_DEFAULT_LICENSING) { if (config.homepage === STORM_DEFAULT_HOMEPAGE) { config.licensing = `${STORM_DEFAULT_HOMEPAGE}/projects/${config.name}/licensing`; } else { config.licensing = `${config.homepage}/docs`; } } const serializedConfig = process.env[`${prefix}CONFIG`]; if (serializedConfig) { const parsed = JSON.parse(serializedConfig); config = { ...config, ...parsed, colors: { ...config.colors, ...parsed.colors }, extensions: { ...config.extensions, ...parsed.extensions } }; } return config; }, "getConfigEnv"); var getThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, theme) => { const themeName = `COLOR_${theme && theme !== "base" ? `${theme}_` : ""}`.toUpperCase(); return process.env[`${prefix}${themeName}LIGHT_BRAND`] || process.env[`${prefix}${themeName}DARK_BRAND`] ? getMultiThemeColorConfigEnv(prefix + themeName) : getSingleThemeColorConfigEnv(prefix + themeName); }, "getThemeColorConfigEnv"); var getSingleThemeColorConfigEnv = /* @__PURE__ */ __name((prefix) => { return { dark: process.env[`${prefix}DARK`], light: process.env[`${prefix}LIGHT`], brand: process.env[`${prefix}BRAND`], alternate: process.env[`${prefix}ALTERNATE`], accent: process.env[`${prefix}ACCENT`], link: process.env[`${prefix}LINK`], help: process.env[`${prefix}HELP`], success: process.env[`${prefix}SUCCESS`], info: process.env[`${prefix}INFO`], warning: process.env[`${prefix}WARNING`], danger: process.env[`${prefix}DANGER`], fatal: process.env[`${prefix}FATAL`], positive: process.env[`${prefix}POSITIVE`], negative: process.env[`${prefix}NEGATIVE`] }; }, "getSingleThemeColorConfigEnv"); var getMultiThemeColorConfigEnv = /* @__PURE__ */ __name((prefix) => { return { light: getBaseThemeColorConfigEnv(`${prefix}_LIGHT_`), dark: getBaseThemeColorConfigEnv(`${prefix}_DARK_`) }; }, "getMultiThemeColorConfigEnv"); var getBaseThemeColorConfigEnv = /* @__PURE__ */ __name((prefix) => { return { foreground: process.env[`${prefix}FOREGROUND`], background: process.env[`${prefix}BACKGROUND`], brand: process.env[`${prefix}BRAND`], alternate: process.env[`${prefix}ALTERNATE`], accent: process.env[`${prefix}ACCENT`], link: process.env[`${prefix}LINK`], help: process.env[`${prefix}HELP`], success: process.env[`${prefix}SUCCESS`], info: process.env[`${prefix}INFO`], warning: process.env[`${prefix}WARNING`], danger: process.env[`${prefix}DANGER`], fatal: process.env[`${prefix}FATAL`], positive: process.env[`${prefix}POSITIVE`], negative: process.env[`${prefix}NEGATIVE`] }; }, "getBaseThemeColorConfigEnv"); // ../config-tools/src/env/set-env.ts var setExtensionEnv = /* @__PURE__ */ __name((extensionName, extension) => { for (const key of Object.keys(extension ?? {})) { if (extension[key]) { const result = key?.replace(/([A-Z])+/g, (input) => input ? input[0]?.toUpperCase() + input.slice(1) : "").split(/(?=[A-Z])|[.\-\s_]/).map((x) => x.toLowerCase()) ?? []; let extensionKey; if (result.length === 0) { return; } if (result.length === 1) { extensionKey = result[0]?.toUpperCase() ?? ""; } else { extensionKey = result.reduce((ret, part) => { return `${ret}_${part.toLowerCase()}`; }); } process.env[`STORM_EXTENSION_${extensionName.toUpperCase()}_${extensionKey.toUpperCase()}`] = extension[key]; } } }, "setExtensionEnv"); var setConfigEnv = /* @__PURE__ */ __name((config) => { const prefix = "STORM_"; if (config.extends) { process.env[`${prefix}EXTENDS`] = Array.isArray(config.extends) ? JSON.stringify(config.extends) : config.extends; } if (config.name) { process.env[`${prefix}NAME`] = config.name; } if (config.namespace) { process.env[`${prefix}NAMESPACE`] = config.namespace; } if (config.owner) { process.env[`${prefix}OWNER`] = config.owner; } if (config.bot) { process.env[`${prefix}BOT_NAME`] = config.bot.name; process.env[`${prefix}BOT_EMAIL`] = config.bot.email; } if (config.error) { process.env[`${prefix}ERROR_CODES_FILE`] = config.error.codesFile; process.env[`${prefix}ERROR_URL`] = config.error.url; } if (config.release) { process.env[`${prefix}RELEASE_BANNER`] = config.release.banner; process.env[`${prefix}RELEASE_HEADER`] = config.release.header; process.env[`${prefix}RELEASE_FOOTER`] = config.release.footer; } if (config.account) { if (config.account.twitter) { process.env[`${prefix}ACCOUNT_TWITTER`] = config.account.twitter; } if (config.account.discord) { process.env[`${prefix}ACCOUNT_DISCORD`] = config.account.discord; } if (config.account.telegram) { process.env[`${prefix}ACCOUNT_TELEGRAM`] = config.account.telegram; } if (config.account.slack) { process.env[`${prefix}ACCOUNT_SLACK`] = config.account.slack; } if (config.account.medium) { process.env[`${prefix}ACCOUNT_MEDIUM`] = config.account.medium; } if (config.account.github) { process.env[`${prefix}ACCOUNT_GITHUB`] = config.account.github; } } if (config.organization) { process.env[`${prefix}ORGANIZATION`] = config.organization; } if (config.packageManager) { process.env[`${prefix}PACKAGE_MANAGER`] = config.packageManager; } if (config.license) { process.env[`${prefix}LICENSE`] = config.license; } if (config.homepage) { process.env[`${prefix}HOMEPAGE`] = config.homepage; } if (config.docs) { process.env[`${prefix}DOCS`] = config.docs; } if (config.licensing) { process.env[`${prefix}LICENSING`] = config.licensing; } if (config.contact) { process.env[`${prefix}CONTACT`] = config.contact; } if (config.timezone) { process.env[`${prefix}TIMEZONE`] = config.timezone; process.env.TZ = config.timezone; process.env.DEFAULT_TIMEZONE = config.timezone; } if (config.locale) { process.env[`${prefix}LOCALE`] = config.locale; process.env.LOCALE = config.locale; process.env.DEFAULT_LOCALE = config.locale; process.env.LANG = config.locale ? `${config.locale.replaceAll("-", "_")}.UTF-8` : "en_US.UTF-8"; } if (config.configFile) { process.env[`${prefix}CONFIG_FILE`] = correctPaths(config.configFile); } if (config.workspaceRoot) { process.env[`${prefix}WORKSPACE_ROOT`] = correctPaths(config.workspaceRoot); process.env.NX_WORKSPACE_ROOT = correctPaths(config.workspaceRoot); process.env.NX_WORKSPACE_ROOT_PATH = correctPaths(config.workspaceRoot); } if (config.directories) { if (!config.skipCache && config.directories.cache) { process.env[`${prefix}CACHE_DIR`] = correctPaths(config.directories.cache); } if (config.directories.data) { process.env[`${prefix}DATA_DIR`] = correctPaths(config.directories.data); } if (config.directories.config) { process.env[`${prefix}CONFIG_DIR`] = correctPaths(config.directories.config); } if (config.directories.temp) { process.env[`${prefix}TEMP_DIR`] = correctPaths(config.directories.temp); } if (config.directories.log) { process.env[`${prefix}LOG_DIR`] = correctPaths(config.directories.log); } if (config.directories.build) { process.env[`${prefix}BUILD_DIR`] = correctPaths(config.directories.build); } } if (config.skipCache !== void 0) { process.env[`${prefix}SKIP_CACHE`] = String(config.skipCache); if (config.skipCache) { process.env.NX_SKIP_NX_CACHE ??= String(config.skipCache); process.env.NX_CACHE_PROJECT_GRAPH ??= String(config.skipCache); } } if (config.mode) { process.env[`${prefix}MODE`] = config.mode; process.env.NODE_ENV = config.mode; process.env.ENVIRONMENT = config.mode; } if (config.colors?.base?.light || config.colors?.base?.dark) { for (const key of Object.keys(config.colors)) { setThemeColorConfigEnv(`${prefix}COLOR_${key}_`, config.colors[key]); } } else { setThemeColorConfigEnv(`${prefix}COLOR_`, config.colors); } if (config.repository) { process.env[`${prefix}REPOSITORY`] = config.repository; } if (config.branch) { process.env[`${prefix}BRANCH`] = config.branch; } if (config.preid) { process.env[`${prefix}PRE_ID`] = String(config.preid); } if (config.externalPackagePatterns) { process.env[`${prefix}EXTERNAL_PACKAGE_PATTERNS`] = JSON.stringify(config.externalPackagePatterns); } if (config.registry) { if (config.registry.github) { process.env[`${prefix}REGISTRY_GITHUB`] = String(config.registry.github); } if (config.registry.npm) { process.env[`${prefix}REGISTRY_NPM`] = String(config.registry.npm); } if (config.registry.cargo) { process.env[`${prefix}REGISTRY_CARGO`] = String(config.registry.cargo); } if (config.registry.cyclone) { process.env[`${prefix}REGISTRY_CYCLONE`] = String(config.registry.cyclone); } if (config.registry.container) { process.env[`${prefix}REGISTRY_CONTAINER`] = String(config.registry.container); } } if (config.logLevel) { process.env[`${prefix}LOG_LEVEL`] = String(config.logLevel); process.env.LOG_LEVEL = String(config.logLevel); process.env.NX_VERBOSE_LOGGING = String(getLogLevel(config.logLevel) >= LogLevel.DEBUG ? true : false); process.env.RUST_BACKTRACE = getLogLevel(config.logLevel) >= LogLevel.DEBUG ? "full" : "none"; } if (config.skipConfigLogging !== void 0) { process.env[`${prefix}SKIP_CONFIG_LOGGING`] = String(config.skipConfigLogging); } process.env[`${prefix}CONFIG`] = JSON.stringify(config); for (const key of Object.keys(config.extensions ?? {})) { if (config.extensions[key] && Object.keys(config.extensions[key])) { setExtensionEnv(key, config.extensions[key]); } } }, "setConfigEnv"); var setThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, config) => { return config?.light?.brand || config?.dark?.brand ? setMultiThemeColorConfigEnv(prefix, config) : setSingleThemeColorConfigEnv(prefix, config); }, "setThemeColorConfigEnv"); var setSingleThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, config) => { if (config.dark) { process.env[`${prefix}DARK`] = config.dark; } if (config.light) { process.env[`${prefix}LIGHT`] = config.light; } if (config.brand) { process.env[`${prefix}BRAND`] = config.brand; } if (config.alternate) { process.env[`${prefix}ALTERNATE`] = config.alternate; } if (config.accent) { process.env[`${prefix}ACCENT`] = config.accent; } if (config.link) { process.env[`${prefix}LINK`] = config.link; } if (config.help) { process.env[`${prefix}HELP`] = config.help; } if (config.success) { process.env[`${prefix}SUCCESS`] = config.success; } if (config.info) { process.env[`${prefix}INFO`] = config.info; } if (config.warning) { process.env[`${prefix}WARNING`] = config.warning; } if (config.danger) { process.env[`${prefix}DANGER`] = config.danger; } if (config.fatal) { process.env[`${prefix}FATAL`] = config.fatal; } if (config.positive) { process.env[`${prefix}POSITIVE`] = config.positive; } if (config.negative) { process.env[`${prefix}NEGATIVE`] = config.negative; } }, "setSingleThemeColorConfigEnv"); var setMultiThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, config) => { return { light: setBaseThemeColorConfigEnv(`${prefix}LIGHT_`, config.light), dark: setBaseThemeColorConfigEnv(`${prefix}DARK_`, config.dark) }; }, "setMultiThemeColorConfigEnv"); var setBaseThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, config) => { if (config.foreground) { process.env[`${prefix}FOREGROUND`] = config.foreground; } if (config.background) { process.env[`${prefix}BACKGROUND`] = config.background; } if (config.brand) { process.env[`${prefix}BRAND`] = config.brand; } if (config.alternate) { process.env[`${prefix}ALTERNATE`] = config.alternate; } if (config.accent) { process.env[`${prefix}ACCENT`] = config.accent; } if (config.link) { process.env[`${prefix}LINK`] = config.link; } if (config.help) { process.env[`${prefix}HELP`] = config.help; } if (config.success) { process.env[`${prefix}SUCCESS`] = config.success; } if (config.info) { process.env[`${prefix}INFO`] = config.info; } if (config.warning) { process.env[`${prefix}WARNING`] = config.warning; } if (config.danger) { process.env[`${prefix}DANGER`] = config.danger; } if (config.fatal) { process.env[`${prefix}FATAL`] = config.fatal; } if (config.positive) { process.env[`${prefix}POSITIVE`] = config.positive; } if (config.negative) { process.env[`${prefix}NEGATIVE`] = config.negative; } }, "setBaseThemeColorConfigEnv"); // ../config-tools/src/create-storm-config.ts var _extension_cache = /* @__PURE__ */ new WeakMap(); var _static_cache = void 0; var createStormWorkspaceConfig = /* @__PURE__ */ __name(async (extensionName, schema, workspaceRoot, skipLogs = false) => { let result; if (!_static_cache?.data || !_static_cache?.timestamp || _static_cache.timestamp < Date.now() - 8e3) { let _workspaceRoot = workspaceRoot; if (!_workspaceRoot) { _workspaceRoot = findWorkspaceRoot(); } const configEnv = getConfigEnv(); const defaultConfig = await getDefaultConfig(_workspaceRoot); const configFile = await getConfigFile(_workspaceRoot); if (!configFile && !skipLogs) { writeWarning("No Storm Workspace configuration file found in the current repository. Please ensure this is the expected behavior - you can add a `storm-workspace.json` file to the root of your workspace if it is not.\n", { logLevel: "all" }); } result = await stormWorkspaceConfigSchema.parseAsync(defu2(configEnv, configFile, defaultConfig)); result.workspaceRoot ??= _workspaceRoot; } else { result = _static_cache.data; } if (schema && extensionName) { result.extensions = { ...result.extensions, [extensionName]: createConfigExtension(extensionName, schema) }; } _static_cache = { timestamp: Date.now(), data: result }; return result; }, "createStormWorkspaceConfig"); var createConfigExtension = /* @__PURE__ */ __name((extensionName, schema) => { const extension_cache_key = { extensionName }; if (_extension_cache.has(extension_cache_key)) { return _extension_cache.get(extension_cache_key); } let extension = getExtensionEnv(extensionName); if (schema) { extension = schema.parse(extension); } _extension_cache.set(extension_cache_key, extension); return extension; }, "createConfigExtension"); var loadStormWorkspaceConfig = /* @__PURE__ */ __name(async (workspaceRoot, skipLogs = false) => { const config = await createStormWorkspaceConfig(void 0, void 0, workspaceRoot, skipLogs); setConfigEnv(config); if (!skipLogs && !config.skipConfigLogging) { writeTrace(`\u2699\uFE0F Using Storm Workspace configuration: ${formatLogMessage(config)}`, config); } return config; }, "loadStormWorkspaceConfig"); // ../config-tools/src/get-config.ts var getConfig = /* @__PURE__ */ __name((workspaceRoot, skipLogs = false) => { return loadStormWorkspaceConfig(workspaceRoot, skipLogs); }, "getConfig"); // ../build-tools/src/utilities/get-entry-points.ts import { glob as glob2 } from "glob"; var getEntryPoints = /* @__PURE__ */ __name(async (config, projectRoot, sourceRoot, entry, emitOnAll = false) => { const workspaceRoot = config.workspaceRoot || findWorkspaceRoot(); const entryPoints = []; if (entry) { if (typeof entry === "string") { entryPoints.push(entry); } else if (Array.isArray(entry)) { entryPoints.push(...entry); } else { entryPoints.push(...Object.values(entry)); } } if (emitOnAll) { entryPoints.push(joinPaths(workspaceRoot, sourceRoot || projectRoot, "**/*.{ts,tsx}")); } const results = await Promise.all(entryPoints.map(async (entryPoint) => { const paths = []; if (entryPoint.includes("*")) { const files = await glob2(entryPoint, { withFileTypes: true, ignore: [ "**/node_modules/**" ] }); paths.push(...files.reduce((ret, filePath) => { const result = correctPaths(joinPaths(filePath.path, filePath.name).replaceAll(correctPaths(workspaceRoot), "").replaceAll(correctPaths(projectRoot), "")); if (result) { writeDebug(`Trying to add entry point ${result} at "${joinPaths(filePath.path, filePath.name)}"`, config); if (!paths.includes(result)) { paths.push(result); } } return ret; }, [])); } else { writeDebug(`Trying to add entry point ${entryPoint}"`, config); if (!paths.includes(entryPoint)) { paths.push(entryPoint); } } return paths; })); return results.filter(Boolean).reduce((ret, result) => { result.forEach((res) => { if (res && !ret.includes(res)) { ret.push(res); } }); return ret; }, []); }, "getEntryPoints"); // ../build-tools/src/utilities/get-env.ts var getEnv = /* @__PURE__ */ __name((builder, options) => { return { STORM_BUILD: builder, STORM_ORG: options.orgName || DEFAULT_ORGANIZATION, STORM_NAME: options.name, STORM_MODE: options.mode || DEFAULT_ENVIRONMENT, STORM_PLATFORM: options.platform, STORM_FORMAT: JSON.stringify(options.format), STORM_TARGET: JSON.stringify(options.target), ...options.env }; }, "getEnv"); // ../build-tools/src/utilities/read-nx-config.ts import { existsSync as existsSync2 } from "node:fs"; import { readFile as readFile3 } from "node:fs/promises"; // ../build-tools/src/utilities/task-graph.ts import { createTaskGraph, mapTargetDefaultsToDependencies } from "nx/src/tasks-runner/create-task-graph"; // src/build.ts import defu3 from "defu"; import { existsSync as existsSync3 } from "node:fs"; import hf from "node:fs/promises"; import { findWorkspaceRoot as findWorkspaceRoot2 } from "nx/src/utils/find-workspace-root"; import { build as tsdown } from "tsdown"; var resolveOptions = /* @__PURE__ */ __name(async (userOptions) => { const projectRoot = userOptions.projectRoot; const workspaceRoot = findWorkspaceRoot2(projectRoot); if (!workspaceRoot) { throw new Error("Cannot find Nx workspace root"); } const config = await getConfig(workspaceRoot.dir); writeDebug(" \u2699\uFE0F Resolving build options", config); const stopwatch = getStopwatch("Build options resolution"); const projectGraph = await createProjectGraphAsync({ exitOnError: true }); const projectJsonPath = joinPaths(workspaceRoot.dir, projectRoot, "project.json"); if (!existsSync3(projectJsonPath)) { throw new Error("Cannot find project.json configuration"); } const projectJsonFile = await hf.readFile(projectJsonPath, "utf8"); const projectJson = JSON.parse(projectJsonFile); const projectName = projectJson.name; const projectConfigurations = readProjectsConfigurationFromProjectGraph2(projectGraph); if (!projectConfigurations?.projects?.[projectName]) { throw new Error("The Build process failed because the project does not have a valid configuration in the project.json file. Check if the file exists in the root of the project."); } const options = defu3(userOptions, DEFAULT_BUILD_OPTIONS); options.name ??= `${projectName}-${options.format}`; options.target ??= DEFAULT_TARGET; const packageJsonPath = joinPaths(workspaceRoot.dir, options.projectRoot, "package.json"); if (!existsSync3(packageJsonPath)) { throw new Error("Cannot find package.json configuration"); } const env = getEnv("tsdown", options); const result = { ...options, config, ...userOptions, tsconfig: joinPaths(projectRoot, userOptions.tsconfig ? userOptions.tsconfig.replace(projectRoot, "") : "tsconfig.json"), format: options.format || "cjs", entryPoints: await getEntryPoints(config, projectRoot, projectJson.sourceRoot, userOptions.entry || [ "./src/index.ts" ], userOptions.emitOnAll), outdir: userOptions.outputPath || joinPaths("dist", projectRoot), plugins: [], name: userOptions.name || projectName, projectConfigurations, projectName, projectGraph, sourceRoot: userOptions.sourceRoot || projectJson.sourceRoot || joinPaths(projectRoot, "src"), minify: userOptions.minify || !userOptions.debug, verbose: userOptions.verbose || isVerbose() || userOptions.debug === true, includeSrc: userOptions.includeSrc === true, metafile: userOptions.metafile !== false, generatePackageJson: userOptions.generatePackageJson !== false, clean: userOptions.clean !== false, emitOnAll: userOptions.emitOnAll === true, dts: userOptions.emitTypes === true ? { transformer: "oxc" } : userOptions.emitTypes, bundleDts: userOptions.emitTypes, assets: userOptions.assets ?? [], shims: userOptions.injectShims !== true, bundle: userOptions.bundle !== false, watch: userOptions.watch === true, define: { STORM_FORMAT: JSON.stringify(options.format || "cjs"), ...options.format === "cjs" && options.injectShims ? { "import.meta.url": "importMetaUrl" } : {}, ...Object.keys(env || {}).reduce((res, key) => { const value = JSON.stringify(env[key]); return { ...res, [`process.env.${key}`]: value, [`import.meta.env.${key}`]: value }; }, {}), ...options.define } }; stopwatch(); return result; }, "resolveOptions"); async function generatePackageJson(options) { if (options.generatePackageJson !== false && existsSync3(joinPaths(options.projectRoot, "package.json"))) { writeDebug(" \u270D\uFE0F Writing package.json file", options.config); const stopwatch = getStopwatch("Write package.json file"); const packageJsonPath = joinPaths(options.projectRoot, "project.json"); if (!existsSync3(packageJsonPath)) { throw new Error("Cannot find package.json configuration"); } const packageJsonFile = await hf.readFile(joinPaths(options.config.workspaceRoot, options.projectRoot, "package.json"), "utf8"); if (!packageJsonFile) { throw new Error("Cannot find package.json configuration file"); } let packageJson = JSON.parse(packageJsonFile); packageJson = await addPackageDependencies(options.config.workspaceRoot, options.projectRoot, options.projectName, packageJson); packageJson = await addWorkspacePackageJsonFields(options.config, options.projectRoot, options.sourceRoot, options.projectName, false, packageJson); packageJson.exports ??= {}; packageJson.exports["./package.json"] ??= "./package.json"; packageJson.exports["."] ??= addPackageJsonExport("index", packageJson.type, options.sourceRoot); let entryPoints = [ { in: "./src/index.ts", out: "./src/index.ts" } ]; if (options.entryPoints) { if (Array.isArray(options.entryPoints)) { entryPoints = options.entryPoints.map((entryPoint) => typeof entryPoint === "string" ? { in: entryPoint, out: entryPoint } : entryPoint); } for (const entryPoint of entryPoints) { const split = entryPoint.out.split("."); split.pop(); const entry = split.join(".").replaceAll("\\", "/"); packageJson.exports[`./${entry}`] ??= addPackageJsonExport(entry, packageJson.type, options.sourceRoot); } } packageJson.main = packageJson.type === "commonjs" ? "./dist/index.js" : "./dist/index.cjs"; packageJson.module = packageJson.type === "module" ? "./dist/index.js" : "./dist/index.mjs"; packageJson.types = "./dist/index.d.ts"; packageJson.exports = Object.keys(packageJson.exports).reduce((ret, key) => { if (key.endsWith("/index") && !ret[key.replace("/index", "")]) { ret[key.replace("/index", "")] = packageJson.exports[key]; } return ret; }, packageJson.exports); await writeJsonFile(joinPaths(options.outdir, "package.json"), packageJson); stopwatch(); } return options; } __name(generatePackageJson, "generatePackageJson"); async function executeTSDown(options) { writeDebug(` \u{1F680} Running ${options.name} build`, options.config); const stopwatch = getStopwatch(`${options.name} build`); await tsdown({ ...options, entry: options.entryPoints, outDir: options.outdir, config: false }); stopwatch(); return options; } __name(executeTSDown, "executeTSDown"); async function copyBuildAssets(options) { writeDebug(` \u{1F4CB} Copying asset files to output directory: ${options.outdir}`, options.config); const stopwatch = getStopwatch(`${options.name} asset copy`); await copyAssets(options.config, options.assets ?? [], options.outdir, options.projectRoot, options.sourceRoot, true, false); stopwatch(); return options; } __name(copyBuildAssets, "copyBuildAssets"); async function reportResults(options) { writeSuccess(` \u{1F4E6} The ${options.name} build completed successfully`, options.config); } __name(reportResults, "reportResults"); async function cleanOutputPath(options) { if (options.clean !== false && options.outdir) { writeDebug(` \u{1F9F9} Cleaning ${options.name} output path: ${options.outdir}`, options.config); const stopwatch = getStopwatch(`${options.name} output clean`); await cleanDirectories(options.name, options.outdir, options.config); stopwatch(); } return options; } __name(cleanOutputPath, "cleanOutputPath"); async function build(options) { writeDebug(` \u26A1 Executing Storm TSDown pipeline`); const stopwatch = getStopwatch("TSDown pipeline"); try { const opts = Array.isArray(options) ? options : [ options ]; if (opts.length === 0) { throw new Error("No build options were provided"); } const resolved = await Promise.all(opts.map(async (opt) => await resolveOptions(opt))); if (resolved.length > 0) { await cleanOutputPath(resolved[0]); await generatePackageJson(resolved[0]); await Promise.all(resolved.map(async (opt) => { await executeTSDown(opt); await copyBuildAssets(opt); await reportResults(opt); })); } else { writeWarning(" \u{1F6A7} No options were passed to TSBuild. Please check the parameters passed to the `build` function."); } writeSuccess(" \u{1F3C1} TSDown pipeline build completed successfully"); } catch (error) { writeFatal("Fatal errors that the build process could not recover from have occured. The build process has been terminated."); throw error; } finally { stopwatch(); } } __name(build, "build"); export { cleanOutputPath, build };