UNPKG

@storm-software/cloudflare-tools

Version:

A Nx plugin package that contains various executors, generators, and utilities that assist in managing Cloudflare services.

1,517 lines (1,478 loc) 97.8 kB
import { parseCargoToml } from "./chunk-ZXLMDNFQ.mjs"; import { findWorkspaceRoot, getConfig, getWorkspaceConfig, schemaRegistry, workspaceConfigSchema } from "./chunk-BJQFVPGK.mjs"; import { ProjectTagConstants, addProjectTag } from "./chunk-CSTZEHUP.mjs"; import { brandIcon, correctPaths, formatLogMessage, getStopwatch, isAbsolute, joinPaths, relative, writeDebug, writeError, writeFatal, writeInfo, writeSuccess, writeTrace, writeWarning } from "./chunk-K4H5ZMYA.mjs"; import { __dirname } from "./chunk-6OMGB2W4.mjs"; // ../config-tools/src/utilities/apply-workspace-tokens.ts var applyWorkspaceBaseTokens = async (option, tokenParams) => { let result = option; if (!result) { return result; } if (tokenParams) { const optionKeys = Object.keys(tokenParams); if (optionKeys.some((optionKey) => result.includes(`{${optionKey}}`))) { for (const optionKey of optionKeys) { if (result.includes(`{${optionKey}}`)) { result = result.replaceAll( `{${optionKey}}`, tokenParams?.[optionKey] || "" ); } } } } if (tokenParams.config) { const configKeys = Object.keys(tokenParams.config); if (configKeys.some((configKey) => result.includes(`{${configKey}}`))) { for (const configKey of configKeys) { if (result.includes(`{${configKey}}`)) { result = result.replaceAll( `{${configKey}}`, tokenParams.config[configKey] || "" ); } } } } if (result.includes("{workspaceRoot}")) { result = result.replaceAll( "{workspaceRoot}", tokenParams.workspaceRoot ?? tokenParams.config?.workspaceRoot ?? findWorkspaceRoot() ); } return result; }; var applyWorkspaceProjectTokens = (option, tokenParams) => { return applyWorkspaceBaseTokens(option, tokenParams); }; var applyWorkspaceTokens = async (options, tokenParams, tokenizerFn) => { if (!options) { return {}; } const result = {}; for (const option of Object.keys(options)) { if (typeof options[option] === "string") { result[option] = await Promise.resolve( tokenizerFn(options[option], tokenParams) ); } else if (Array.isArray(options[option])) { result[option] = await Promise.all( options[option].map( async (item) => typeof item === "string" ? await Promise.resolve(tokenizerFn(item, tokenParams)) : item ) ); } else if (typeof options[option] === "object") { result[option] = await applyWorkspaceTokens( options[option], tokenParams, tokenizerFn ); } else { result[option] = options[option]; } } return result; }; // ../workspace-tools/src/base/base-executor.ts import { defu } from "defu"; var withRunExecutor = (name, executorFn, executorOptions = {}) => async (_options, context) => { const stopwatch = getStopwatch(name); let options = _options; let config = {}; try { if (!context.projectsConfigurations?.projects || !context.projectName || !context.projectsConfigurations.projects[context.projectName]) { throw new Error( "The Build process failed because the context is not valid. Please run this command from a workspace." ); } const workspaceRoot2 = findWorkspaceRoot(); const projectRoot = context.projectsConfigurations.projects[context.projectName].root || workspaceRoot2; const sourceRoot = context.projectsConfigurations.projects[context.projectName].sourceRoot || projectRoot || workspaceRoot2; const projectName = context.projectName; config.workspaceRoot = workspaceRoot2; writeInfo( `${brandIcon(config)} Running the ${name} executor for ${projectName} `, config ); if (!executorOptions.skipReadingConfig) { writeTrace( `Loading the Storm Config from environment variables and storm.config.js file... - workspaceRoot: ${workspaceRoot2} - projectRoot: ${projectRoot} - sourceRoot: ${sourceRoot} - projectName: ${projectName} `, config ); config = await getConfig(workspaceRoot2); } if (executorOptions?.hooks?.applyDefaultOptions) { writeDebug("Running the applyDefaultOptions hook...", config); options = await Promise.resolve( executorOptions.hooks.applyDefaultOptions(options, config) ); writeDebug("Completed the applyDefaultOptions hook", config); } writeTrace( `Executor schema options \u2699\uFE0F ${formatLogMessage(options)} `, config ); const tokenized = await applyWorkspaceTokens( options, defu( { workspaceRoot: workspaceRoot2, projectRoot, sourceRoot, projectName, config }, config, context.projectsConfigurations.projects[context.projectName] ), applyWorkspaceProjectTokens ); writeTrace( `Executor schema tokenized options \u2699\uFE0F ${formatLogMessage(tokenized)} `, config ); if (executorOptions?.hooks?.preProcess) { writeDebug("Running the preProcess hook...", config); await Promise.resolve( executorOptions.hooks.preProcess(tokenized, config) ); writeDebug("Completed the preProcess hook", config); } const ret = executorFn(tokenized, context, config); if (_isFunction(ret?.next)) { const asyncGen = ret; for await (const iter of asyncGen) { void iter; } } const result = await Promise.resolve( ret ); if (result && (!result.success || result.error && result?.error?.message && typeof result?.error?.message === "string" && result?.error?.name && typeof result?.error?.name === "string")) { throw new Error( `Failure determined while running the ${name} executor ${formatLogMessage( result )}`, { cause: result?.error } ); } if (executorOptions?.hooks?.postProcess) { writeDebug("Running the postProcess hook...", config); await Promise.resolve(executorOptions.hooks.postProcess(config)); writeDebug("Completed the postProcess hook", config); } writeSuccess(`Completed running the ${name} task executor! `, config); return { success: true }; } catch (error) { writeFatal( "A fatal error occurred while running the executor - the process was forced to terminate", config ); writeError( `An exception was thrown in the executor's process - Details: ${error.message} - Stacktrace: ${error.stack}`, config ); return { success: false }; } finally { stopwatch(); } }; var _isFunction = (value) => { try { return value instanceof Function || typeof value === "function" || !!(value?.constructor && value?.call && value?.apply); } catch (e) { return false; } }; // ../workspace-tools/src/utils/cargo.ts import { joinPathFragments } from "@nx/devkit"; import { execSync, spawn } from "node:child_process"; import { readFileSync } from "node:fs"; import { relative as relative2 } from "node:path"; var INVALID_CARGO_ARGS = [ "allFeatures", "allTargets", "main", "outputPath", "package", "tsConfig" ]; var buildCargoCommand = (baseCommand, options, context) => { const args = []; if (options.toolchain && options.toolchain !== "stable") { args.push(`+${options.toolchain}`); } args.push(baseCommand); for (const [key, value] of Object.entries(options).filter( ([key2]) => key2 && key2 !== "_" )) { if (key === "toolchain" || key === "release" || INVALID_CARGO_ARGS.includes(key)) { continue; } if (typeof value === "boolean") { if (value) { args.push(`--${key}`); } } else if (Array.isArray(value)) { for (const item of value) { args.push(`--${key}`, String(item)); } } else { args.push(`--${key}`, String(value)); } } if (context.projectName && context.projectsConfigurations?.projects && context.projectsConfigurations?.projects[context.projectName] && context.projectsConfigurations?.projects[context.projectName]?.root && context.projectsConfigurations?.projects[context.projectName]?.root.includes("Cargo.toml")) { const cargoToml = parseCargoToml( readFileSync( joinPathFragments( context.projectsConfigurations.projects[context.projectName].root, "Cargo.toml" ), "utf-8" ) ); args.push("-p", cargoToml.package.name); } if (options.allFeatures && !args.includes("--all-features")) { args.push("--all-features"); } if (options.allTargets && !args.includes("--all-targets")) { args.push("--all-targets"); } if (options.release && !args.includes("--profile")) { args.push("--release"); } if (options.outputPath && !args.includes("--target-dir")) { args.push("--target-dir", options.outputPath); } return args; }; async function cargoCommand(workspaceRoot2, ...args) { console.log(`> cargo ${args.join(" ")}`); args.push("--color", "always"); return await Promise.resolve(runProcess(workspaceRoot2, "cargo", ...args)); } function cargoCommandSync(args = "", options) { const normalizedOptions = { stdio: options?.stdio ?? "inherit", env: { ...process.env, ...options?.env } }; try { return { output: execSync(`cargo ${args}`, { encoding: "utf8", windowsHide: true, stdio: normalizedOptions.stdio, env: normalizedOptions.env, maxBuffer: 1024 * 1024 * 10 }), success: true }; } catch (e) { return { output: e.message, success: false }; } } function cargoMetadata() { const output2 = cargoCommandSync("metadata --format-version=1", { stdio: "pipe" }); if (!output2.success) { console.error("Failed to get cargo metadata"); return null; } return JSON.parse(output2.output); } function runProcess(workspaceRoot2, processCmd, ...args) { const metadata = cargoMetadata(); const targetDir = metadata?.target_directory ?? joinPathFragments(workspaceRoot2, "dist"); return new Promise((resolve) => { if (process.env.VERCEL) { return resolve({ success: true }); } execSync(`${processCmd} ${args.join(" ")}`, { cwd: process.cwd(), env: { ...process.env, RUSTC_WRAPPER: "", CARGO_TARGET_DIR: targetDir, CARGO_BUILD_TARGET_DIR: targetDir }, windowsHide: true, stdio: ["inherit", "inherit", "inherit"] }); resolve({ success: true }); }); } // ../workspace-tools/src/executors/cargo-build/executor.ts async function cargoBuildExecutor(options, context) { const command = buildCargoCommand("build", options, context); return await cargoCommand(context.root, ...command); } var executor_default = withRunExecutor( "Cargo - Build", cargoBuildExecutor, { skipReadingConfig: false, hooks: { applyDefaultOptions: (options) => { options.outputPath ??= "dist/{projectRoot}/target"; options.toolchain ??= "stable"; return options; } } } ); // ../workspace-tools/src/executors/cargo-check/executor.ts async function cargoCheckExecutor(options, context) { const command = buildCargoCommand("check", options, context); return await cargoCommand(context.root, ...command); } var executor_default2 = withRunExecutor( "Cargo - Check", cargoCheckExecutor, { skipReadingConfig: false, hooks: { applyDefaultOptions: (options) => { options.toolchain ??= "stable"; return options; } } } ); // ../workspace-tools/src/executors/cargo-clippy/executor.ts async function cargoClippyExecutor(options, context) { const command = buildCargoCommand("clippy", options, context); return await cargoCommand(context.root, ...command); } var executor_default3 = withRunExecutor( "Cargo - Clippy", cargoClippyExecutor, { skipReadingConfig: false, hooks: { applyDefaultOptions: (options) => { options.toolchain ??= "stable"; options.fix ??= false; return options; } } } ); // ../workspace-tools/src/executors/cargo-doc/executor.ts async function cargoDocExecutor(options, context) { const opts = { ...options }; opts["no-deps"] = opts.noDeps; delete opts.noDeps; const command = buildCargoCommand("doc", options, context); return await cargoCommand(context.root, ...command); } var executor_default4 = withRunExecutor( "Cargo - Doc", cargoDocExecutor, { skipReadingConfig: false, hooks: { applyDefaultOptions: (options) => { options.outputPath ??= "dist/{projectRoot}/docs"; options.toolchain ??= "stable"; options.release ??= options.profile ? false : true; options.allFeatures ??= true; options.lib ??= true; options.bins ??= true; options.examples ??= true; options.noDeps ??= false; return options; } } } ); // ../workspace-tools/src/executors/cargo-format/executor.ts async function cargoFormatExecutor(options, context) { const command = buildCargoCommand("fmt", options, context); return await cargoCommand(context.root, ...command); } var executor_default5 = withRunExecutor( "Cargo - Format", cargoFormatExecutor, { skipReadingConfig: false, hooks: { applyDefaultOptions: (options) => { options.outputPath ??= "dist/{projectRoot}/target"; options.toolchain ??= "stable"; return options; } } } ); // ../workspace-tools/src/executors/cargo-publish/executor.ts import { joinPathFragments as joinPathFragments2 } from "@nx/devkit"; import { execSync as execSync2 } from "node:child_process"; import { readFileSync as readFileSync2 } from "node:fs"; import https from "node:https"; var LARGE_BUFFER = 1024 * 1e6; // ../workspace-tools/src/executors/esbuild/executor.ts import { createJiti } from "jiti"; async function esbuildExecutorFn(options, context, config) { writeInfo("\u{1F4E6} Running Storm ESBuild executor on the workspace", config); if (!context.projectsConfigurations?.projects || !context.projectName || !context.projectsConfigurations.projects[context.projectName] || !context.projectsConfigurations.projects[context.projectName]?.root) { throw new Error( "The Build process failed because the context is not valid. Please run this command from a workspace." ); } const jiti = createJiti(config?.workspaceRoot || process.cwd(), { fsCache: config?.skipCache ? false : joinPaths( config?.workspaceRoot || process.cwd(), config?.directories?.cache || "node_modules/.cache/storm", "jiti" ), interopDefault: true }); const { build: build2 } = await jiti.import(jiti.esmResolve("@storm-software/esbuild")); await build2({ ...options, projectRoot: ( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion context.projectsConfigurations.projects?.[context.projectName].root ), name: context.projectName, sourceRoot: context.projectsConfigurations.projects?.[context.projectName]?.sourceRoot, format: options.format, platform: options.platform }); return { success: true }; } var executor_default6 = withRunExecutor( "Storm ESBuild build", esbuildExecutorFn, { skipReadingConfig: false, hooks: { applyDefaultOptions: async (options) => { options.entry ??= ["src/index.ts"]; options.outputPath ??= "dist/{projectRoot}"; options.tsconfig ??= "{projectRoot}/tsconfig.json"; return options; } } } ); // ../workspace-tools/src/executors/napi/executor.ts import { createJiti as createJiti2 } from "jiti"; import { fileExists } from "nx/src/utils/fileutils"; async function napiExecutor(options, context, config) { const jiti = createJiti2(config.workspaceRoot, { fsCache: config.skipCache ? false : joinPaths( config.workspaceRoot, config.directories.cache || "node_modules/.cache/storm", "jiti" ), interopDefault: true }); const { NapiCli } = await jiti.import( jiti.esmResolve("@napi-rs/cli") ); if (!context.projectGraph?.nodes[context.projectName ?? ""]) { throw new Error( "The Napi Build process failed because the project could not be found in the project graph. Please run this command from a workspace root directory." ); } const projectRoot = context.projectGraph?.nodes[context.projectName ?? ""]?.data.root; const packageJson = joinPaths(projectRoot ?? ".", "package.json"); if (!fileExists(packageJson)) { throw new Error(`Could not find package.json at ${packageJson}`); } const napi = new NapiCli(); const normalizedOptions = { ...options }; const metadata = cargoMetadata(); normalizedOptions.targetDir = options.targetDir || metadata?.target_directory || joinPaths(config.workspaceRoot, "dist", "target"); normalizedOptions.outputDir = options.outputPath; normalizedOptions.packageJsonPath ??= packageJson; if (options.cwd) { normalizedOptions.cwd = correctPaths(options.cwd); } else { const absoluteProjectRoot = correctPaths( joinPaths(config.workspaceRoot, projectRoot || ".") ); normalizedOptions.cwd = absoluteProjectRoot; if (normalizedOptions.outputDir) { normalizedOptions.outputDir = relative( normalizedOptions.cwd, correctPaths( isAbsolute(normalizedOptions.outputDir) ? normalizedOptions.outputDir : joinPaths(config.workspaceRoot, normalizedOptions.outputDir) ) ); } if (normalizedOptions.packageJsonPath) { normalizedOptions.packageJsonPath = relative( normalizedOptions.cwd, correctPaths( isAbsolute(normalizedOptions.packageJsonPath) ? normalizedOptions.packageJsonPath : joinPaths(config.workspaceRoot, normalizedOptions.packageJsonPath) ) ); } if (normalizedOptions.configPath) { normalizedOptions.configPath = relative( normalizedOptions.cwd, correctPaths( isAbsolute(normalizedOptions.configPath) ? normalizedOptions.configPath : joinPaths(config.workspaceRoot, normalizedOptions.configPath) ) ); } if (normalizedOptions.manifestPath) { normalizedOptions.manifestPath = relative( normalizedOptions.cwd, correctPaths( isAbsolute(normalizedOptions.manifestPath) ? normalizedOptions.manifestPath : joinPaths(config.workspaceRoot, normalizedOptions.manifestPath) ) ); } } if (process.env.VERCEL) { return { success: true }; } writeDebug( `Normalized Napi Options: packageJsonPath: ${normalizedOptions.packageJsonPath} outputDir: ${normalizedOptions.outputDir} targetDir: ${normalizedOptions.targetDir} manifestPath: ${normalizedOptions.manifestPath} configPath: ${normalizedOptions.configPath} cwd: ${normalizedOptions.cwd}`, config ); const { task } = await napi.build(normalizedOptions); return { success: true, terminalOutput: await task }; } var executor_default7 = withRunExecutor( "Napi - Build Bindings", napiExecutor, { skipReadingConfig: false, hooks: { applyDefaultOptions: (options) => { options.outputPath ??= "{sourceRoot}"; options.toolchain ??= "stable"; options.dtsCache ??= true; options.platform ??= true; options.constEnum ??= false; options.verbose ??= false; options.jsBinding ??= "binding.js"; options.dts ??= "binding.d.ts"; return options; } } } ); // ../workspace-tools/src/executors/npm-publish/executor.ts import { createJiti as createJiti4 } from "jiti"; import { execSync as execSync3 } from "node:child_process"; import { readFile, writeFile } from "node:fs/promises"; import { format } from "prettier"; // ../workspace-tools/src/utils/github.ts import { createJiti as createJiti3 } from "jiti"; // ../workspace-tools/src/utils/package-manager.ts import { detectPackageManager, getPackageManagerCommand } from "@nx/devkit"; // ../workspace-tools/src/executors/npm-publish/executor.ts var LARGE_BUFFER2 = 1024 * 1e6; // ../workspace-tools/src/executors/size-limit/executor.ts import { joinPathFragments as joinPathFragments3 } from "@nx/devkit"; import esBuildPlugin from "@size-limit/esbuild"; import esBuildWhyPlugin from "@size-limit/esbuild-why"; import filePlugin from "@size-limit/file"; import sizeLimit from "size-limit"; async function sizeLimitExecutorFn(options, context, config) { if (!context?.projectName || !context.projectsConfigurations?.projects || !context.projectsConfigurations.projects[context.projectName]) { throw new Error( "The Size-Limit process failed because the context is not valid. Please run this command from a workspace." ); } writeInfo(`\u{1F4CF} Running Size-Limit on ${context.projectName}`, config); sizeLimit([filePlugin, esBuildPlugin, esBuildWhyPlugin], { checks: options.entry ?? context.projectsConfigurations.projects[context.projectName]?.sourceRoot ?? joinPathFragments3( context.projectsConfigurations.projects[context.projectName]?.root ?? "./", "src" ) }).then((result) => { writeInfo( `\u{1F4CF} ${context.projectName} Size-Limit result: ${JSON.stringify(result)}`, config ); }); return { success: true }; } var executor_default8 = withRunExecutor( "Size-Limit Performance Test Executor", sizeLimitExecutorFn, { skipReadingConfig: false, hooks: { applyDefaultOptions: (options) => { return options; } } } ); // ../tsdown/src/build.ts import { createProjectGraphAsync as createProjectGraphAsync2, 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 as relative3 } from "path"; // ../build-tools/src/utilities/copy-assets.ts import { CopyAssetsHandler } from "@nx/js/internal"; import { glob } from "glob"; import { readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises"; var copyAssets = 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(); writeTrace("Completed copying assets to the output directory", config); 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) => writeFile2( file, `${banner && typeof banner === "string" ? banner.startsWith("//") ? banner : `// ${banner}` : ""} ${await readFile2(file, "utf8")} ${footer && typeof footer === "string" ? footer.startsWith("//") ? footer : `// ${footer}` : ""}` ) ) ); } }; // ../build-tools/src/utilities/generate-package-json.ts import { calculateProjectBuildableDependencies } from "@nx/js/internal"; import { Glob } from "glob"; import { existsSync, readFileSync as readFileSync3 } from "node:fs"; import { readFile as readFile3 } from "node:fs/promises"; import { createProjectGraphAsync, readCachedProjectGraph, readProjectsConfigurationFromProjectGraph } from "nx/src/project-graph/project-graph"; var addPackageDependencies = async (workspaceRoot2, projectRoot, projectName, packageJson) => { let projectGraph; try { projectGraph = readCachedProjectGraph(); } catch { await createProjectGraphAsync(); projectGraph = readCachedProjectGraph(); } if (!projectGraph) { throw new Error( "The Build process failed because the project graph is not available. Please run the build command again." ); } const projectDependencies = calculateProjectBuildableDependencies( void 0, projectGraph, workspaceRoot2, 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 !== workspaceRoot2 )) { const projectNode = project.node; if (projectNode.data.root) { const projectPackageJsonPath = joinPaths( workspaceRoot2, projectNode.data.root, "package.json" ); if (existsSync(projectPackageJsonPath)) { const projectPackageJsonContent = await readFile3( 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 readFile3( 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( workspaceRoot2, projectConfigurations.projects[dep].root, "package.json" ); if (existsSync(depPackageJsonPath)) { const depPackageJsonContent = readFileSync3( 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; }; var addWorkspacePackageJsonFields = async (workspaceConfig, projectRoot, sourceRoot, projectName, includeSrc = false, packageJson) => { const workspaceRoot2 = workspaceConfig.workspaceRoot ? workspaceConfig.workspaceRoot : findWorkspaceRoot(); const workspacePackageJsonContent = await readFile3( joinPaths(workspaceRoot2, "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; }; var addPackageJsonExport = (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.${type !== "fixed" ? "ts" : "mts"}`, default: `./dist/${entry}.${type !== "fixed" ? "js" : "mjs"}` } }; }; // ../build-tools/src/utilities/get-entry-points.ts import { glob as glob2 } from "glob"; // ../build-tools/src/utilities/get-env.ts var getEnv = (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 }; }; // ../build-tools/src/utilities/read-nx-config.ts import { existsSync as existsSync2 } from "node:fs"; import { readFile as readFile4 } from "node:fs/promises"; // ../build-tools/src/utilities/task-graph.ts import { createTaskGraph, mapTargetDefaultsToDependencies } from "nx/src/tasks-runner/create-task-graph"; // ../tsdown/src/build.ts import defu2 from "defu"; import { existsSync as existsSync3 } from "node:fs"; import hf from "node:fs/promises"; import { build as tsdown } from "tsdown"; // ../tsdown/src/clean.ts import { rm } from "node:fs/promises"; async function cleanDirectories(name = "TSDown", directory, config) { await rm(directory, { recursive: true, force: true }); } // ../tsdown/src/config.ts function getDefaultOptions(config) { return { entry: ["./src/*.ts"], platform: "node", target: "esnext", mode: "production", dts: true, unused: { level: "error", ignore: ["typescript"] }, publint: true, fixedExtension: true, ...config }; } function toTSDownFormat(format2) { if (!format2 || Array.isArray(format2) && format2.length === 0) { return ["cjs", "es"]; } else if (format2 === "esm") { return "es"; } else if (Array.isArray(format2)) { return format2.map((f) => f === "esm" ? "es" : f); } return format2; } // ../tsdown/src/build.ts var resolveOptions = async (userOptions) => { const options = getDefaultOptions(userOptions); const workspaceRoot2 = findWorkspaceRoot(options.projectRoot); if (!workspaceRoot2) { throw new Error("Cannot find Nx workspace root"); } const workspaceConfig = await getWorkspaceConfig(options.debug === true, { workspaceRoot: workspaceRoot2 }); writeDebug(" \u2699\uFE0F Resolving build options", workspaceConfig); const stopwatch = getStopwatch("Build options resolution"); const projectGraph = await createProjectGraphAsync2({ exitOnError: true }); const projectJsonPath = joinPaths( workspaceRoot2, options.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 packageJsonPath = joinPaths( workspaceRoot2, options.projectRoot, "package.json" ); if (!existsSync3(packageJsonPath)) { throw new Error("Cannot find package.json configuration"); } const debug = options.debug ?? (options.mode || workspaceConfig.mode) === "development"; const sourceRoot = projectJson.sourceRoot || joinPaths(options.projectRoot, "src"); const result = { name: projectName, mode: "production", target: DEFAULT_TARGET, generatePackageJson: true, outDir: joinPaths("dist", options.projectRoot), minify: !debug, plugins: [], assets: [], dts: true, shims: true, logLevel: workspaceConfig.logLevel === "success" || workspaceConfig.logLevel === "performance" || workspaceConfig.logLevel === "debug" || workspaceConfig.logLevel === "trace" || workspaceConfig.logLevel === "all" ? "info" : workspaceConfig.logLevel === "fatal" ? "error" : workspaceConfig.logLevel, sourcemap: debug ? "inline" : false, clean: false, fixedExtension: true, nodeProtocol: true, tsconfig: joinPaths(options.projectRoot, "tsconfig.json"), debug, sourceRoot, cwd: workspaceConfig.workspaceRoot, entry: { ["index"]: joinPaths(sourceRoot, "index.ts") }, workspace: true, ...options, treeshake: options.treeShaking !== false, format: toTSDownFormat(options.format), workspaceConfig, projectName, projectGraph, projectConfigurations }; result.env = defu2( options.env, getEnv("tsdown", result) ); stopwatch(); return result; }; async function generatePackageJson(options) { if (options.generatePackageJson !== false && existsSync3(joinPaths(options.projectRoot, "package.json"))) { writeDebug(" \u270D\uFE0F Writing package.json file", options.workspaceConfig); 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.workspaceConfig.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.workspaceConfig.workspaceRoot, options.projectRoot, options.projectName, packageJson ); packageJson = await addWorkspacePackageJsonFields( options.workspaceConfig, 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 entry = [{ in: "./src/index.ts", out: "./src/index.ts" }]; if (options.entry) { if (Array.isArray(options.entry)) { entry = options.entry.map( (entryPoint) => typeof entryPoint === "string" ? { in: entryPoint, out: entryPoint } : entryPoint ); } for (const entryPoint of entry) { const split = entryPoint.out.split("."); split.pop(); const entry2 = split.join(".").replaceAll("\\", "/"); packageJson.exports[`./${entry2}`] ??= addPackageJsonExport( entry2, options.fixedExtension ? "fixed" : packageJson.type, options.sourceRoot ); } } packageJson.main = !options.fixedExtension && packageJson.type === "commonjs" ? "./dist/index.js" : "./dist/index.cjs"; packageJson.module = !options.fixedExtension && packageJson.type === "module" ? "./dist/index.js" : "./dist/index.mjs"; packageJson.types = `./dist/index.d.${!options.fixedExtension ? "ts" : "mts"}`; 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; } async function executeTSDown(options) { writeDebug(` \u{1F680} Running ${options.name} build`, options.workspaceConfig); const stopwatch = getStopwatch(`${options.name} build`); await tsdown({ ...options, entry: options.entry, config: false }); stopwatch(); return options; } async function copyBuildAssets(options) { writeDebug( ` \u{1F4CB} Copying asset files to output directory: ${options.outDir}`, options.workspaceConfig ); const stopwatch = getStopwatch(`${options.name} asset copy`); await copyAssets( options.workspaceConfig, options.assets ?? [], options.outDir, options.projectRoot, options.sourceRoot, true, false ); stopwatch(); return options; } async function reportResults(options) { writeSuccess( ` \u{1F4E6} The ${options.name} build completed successfully`, options.workspaceConfig ); } async function cleanOutputPath(options) { if (options.clean !== false && options.workspaceConfig) { writeDebug( ` \u{1F9F9} Cleaning ${options.name} output path: ${options.workspaceConfig}`, options.workspaceConfig ); const stopwatch = getStopwatch(`${options.name} output clean`); await cleanDirectories( options.name, options.outDir, options.workspaceConfig ); stopwatch(); } return options; } async function build(options) { writeDebug(` ${brandIcon()} 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(); } } // ../workspace-tools/src/executors/tsdown/executor.ts async function tsdownExecutorFn(options, context, config) { writeInfo("\u{1F4E6} Running Storm TSDown executor on the workspace", config); if (!context.projectsConfigurations?.projects || !context.projectName || !context.projectsConfigurations.projects[context.projectName] || !context.projectsConfigurations.projects[context.projectName]?.root) { throw new Error( "The Build process failed because the context is not valid. Please run this command from a workspace." ); } await build({ ...options, projectRoot: ( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion context.projectsConfigurations.projects?.[context.projectName].root ), name: context.projectName, sourceRoot: context.projectsConfigurations.projects?.[context.projectName]?.sourceRoot, format: options.format, platform: options.platform }); return { success: true }; } var executor_default9 = withRunExecutor( "Storm TSDown build", tsdownExecutorFn, { skipReadingConfig: false, hooks: { applyDefaultOptions: async (options) => { options.entry ??= ["src/index.ts"]; options.outputPath ??= "dist/{projectRoot}"; options.tsconfig ??= "{projectRoot}/tsconfig.json"; return options; } } } ); // ../workspace-tools/src/executors/typia/executor.ts import { removeSync } from "fs-extra"; import { TypiaProgrammer } from "typia/lib/programmers/TypiaProgrammer.js"; async function typiaExecutorFn(options, _, config) { if (options.clean !== false) { writeInfo(`\u{1F9F9} Cleaning output path: ${options.outputPath}`, config); removeSync(options.outputPath); } await Promise.all( options.entry.map((entry) => { writeInfo(`\u{1F680} Running Typia on entry: ${entry}`, config); return TypiaProgrammer.build({ input: entry, output: options.outputPath, project: options.tsconfig }); }) ); return { success: true }; } var executor_default10 = withRunExecutor( "Typia runtime validation generator", typiaExecutorFn, { skipReadingConfig: false, hooks: { applyDefaultOptions: (options) => { options.entry ??= ["{sourceRoot}/index.ts"]; options.outputPath ??= "{sourceRoot}/__generated__/typia"; options.tsconfig ??= "{projectRoot}/tsconfig.json"; options.clean ??= true; return options; } } } ); // ../workspace-tools/src/executors/unbuild/executor.ts import { defu as defu3 } from "defu"; import { createJiti as createJiti5 } from "jiti"; async function unbuildExecutorFn(options, context, config) { writeInfo("\u{1F4E6} Running Storm Unbuild executor on the workspace", config); if (!context.projectsConfigurations?.projects || !context.projectName || !context.projectsConfigurations.projects[context.projectName]) { throw new Error( "The Build process failed because the context is not valid. Please run this command from a workspace root directory." ); } if (!context.projectsConfigurations.projects[context.projectName].root) { throw new Error( "The Build process failed because the project root is not valid. Please run this command from a workspace root directory." ); } if (!context.projectsConfigurations.projects[context.projectName].sourceRoot) { throw new Error( "The Build process failed because the project's source root is not valid. Please run this command from a workspace root directory." ); } const jiti = createJiti5(config.workspaceRoot, { fsCache: config.skipCache ? false : joinPaths( config.workspaceRoot, config.directories.cache || "node_modules/.cache/storm", "jiti" ), interopDefault: true }); const stormUnbuild = await jiti.import( jiti.esmResolve("@storm-software/unbuild/build") ); await stormUnbuild.build( defu3( { ...options, projectRoot: context.projectsConfigurations.projects[context.projectName].root, projectName: context.projectName, sourceRoot: context.projectsConfigurations.projects[context.projectName].sourceRoot, platform: options.platform }, { stubOptions: { jiti: { fsCache: config.skipCache ? false : joinPaths( config.workspaceRoot, config.directories.cache || "node_modules/.cache/storm", "jiti" ) } }, rollup: { emitCJS: true, watch: false, dts: { respectExternal: true }, esbuild: { target: options.target, format: "esm", platform: options.platform, minify: options.minify ?? !options.debug, sourcemap: options.sourcemap ?? options.debug, treeShaking: options.treeShaking } } } ) ); return { success: true }; } var executor_default11 = withRunExecutor( "TypeScript Unbuild build", unbuildExecutorFn, { skipReadingConfig: false, hooks: { applyDefaultOptions: async (options, config) => { options.debug ??= false; options.treeShaking ??= true; options.buildOnly ??= false; options.platform ??= "neutral"; options.entry ??= ["{sourceRoot}"]; options.tsconfig ??= "{projectRoot}/tsconfig.json"; return options; } } } ); // ../workspace-tools/src/generators/browser-library/generator.ts import { formatFiles as formatFiles2, generateFiles, names as names2, offsetFromRoot as offsetFromRoot2 } from "@nx/devkit"; // ../workspace-tools/src/base/base-generator.ts var withRunGenerator = (name, generatorFn, generatorOptions = { skipReadingConfig: false }) => async (tree, _options) => { const stopwatch = getStopwatch(name); let options = _options; let config; try { writeInfo( `${brandIcon(config)} Running the ${name} generator... `, config ); const workspaceRoot2 = findWorkspaceRoot(); if (!generatorOptions.skipReadingConfig) { writeDebug( `Loading the Storm Config from environment variables and storm.config.js file... - workspaceRoot: ${workspaceRoot2}`, config ); config = await getConfig(workspaceRoot2); } if (generatorOptions?.hooks?.applyDefaultOptions) { writeDebug("Running the applyDefaultOptions hook...", config); options = await Promise.resolve( generatorOptions.hooks.applyDefaultOptions(options, config) ); writeDebug("Completed the applyDefaultOptions hook", config); } writeTrace( `Generator schema options \u2699\uFE0F ${Object.keys(options ?? {}).map((key) => ` - ${key}=${JSON.stringify(options[key])}`).join("\n")}`, config ); const tokenized = await applyWorkspaceTokens( options, { workspaceRoot: tree.root, config }, applyWorkspaceBaseTokens ); if (generatorOptions?.hooks?.preProcess) { writeDebug("Running the preProcess hook...", config); await Promise.resolve( generatorOptions.hooks.preProcess(tokenized, config) ); writeDebug("Completed the preProcess hook", config); } const result = await Promise.resolve( generatorFn(tree, tokenized, config) ); if (result) { if (result.success === false || result.error && result?.error?.message && typeof result?.error?.message === "string" && result?.error?.name && typeof result?.error?.name === "string") { throw new Error(`The ${name} generator failed to run`, { cause: result?.error }); } else if (result.success && result.data) { return result; } } if (generatorOptions?.hooks?.postProcess) { writeDebug("Running the postProcess hook...", config); await Promise.resolve(generatorOptions.hooks.postProcess(config)); writeDebug("Completed the postProcess hook", config); } return () => { writeSuccess(`Completed running the ${name} generator! `, config); }; } catc