UNPKG

@storm-stack/core

Version:

A build toolkit and runtime used by Storm Software in TypeScript applications

289 lines (277 loc) 14.8 kB
'use strict'; var chunkONBGOAON_cjs = require('./chunk-ONBGOAON.cjs'); var chunkZC2JNV4B_cjs = require('./chunk-ZC2JNV4B.cjs'); var chunkUTUPUYE6_cjs = require('./chunk-UTUPUYE6.cjs'); var chunkEND3JFY3_cjs = require('./chunk-END3JFY3.cjs'); var chunkEG72EGDV_cjs = require('./chunk-EG72EGDV.cjs'); var chunkZ72ISLE5_cjs = require('./chunk-Z72ISLE5.cjs'); var chunk3ONWID2V_cjs = require('./chunk-3ONWID2V.cjs'); var types = require('@storm-software/config-tools/types'); var helpers = require('@stryke/fs/helpers'); var exists = require('@stryke/path/exists'); var joinPaths = require('@stryke/path/join-paths'); var filePathFns = require('@stryke/path/file-path-fns'); var isParentPath = require('@stryke/path/is-parent-path'); var replace = require('@stryke/path/replace'); var apiExtractor = require('@microsoft/api-extractor'); var resolve = require('@stryke/path/resolve'); var defu = require('defu'); var typescript = require('typescript'); function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } var defu__default = /*#__PURE__*/_interopDefault(defu); async function prepareConfig(context, hooks) { context.log(types.LogLevelLabel.TRACE, `Preparing the configuration for the Storm Stack project.`); await hooks.callHook("prepare:config", context).catch((error) => { context.log(types.LogLevelLabel.ERROR, `An error occurred while preparing the configuration for the Storm Stack project: ${error.message} ${error.stack ?? ""}`); throw new Error("An error occurred while preparing the configuration for the Storm Stack project", { cause: error }); }); } chunk3ONWID2V_cjs.__name(prepareConfig, "prepareConfig"); async function prepareDeploy(context, hooks) { context.log(types.LogLevelLabel.TRACE, `Initializing the deployment configuration for the Storm Stack project.`); await hooks.callHook("prepare:deploy", context).catch((error) => { context.log(types.LogLevelLabel.ERROR, `An error occurred while initializing the deployment configuration for the Storm Stack project: ${error.message} ${error.stack ?? ""}`); throw new Error("An error occurred while initializing the deployment configuration for the Storm Stack project", { cause: error }); }); } chunk3ONWID2V_cjs.__name(prepareDeploy, "prepareDeploy"); async function prepareEntry(context, hooks) { context.log(types.LogLevelLabel.TRACE, `Initializing the reflection data for the Storm Stack project.`); await hooks.callHook("prepare:entry", context).catch((error) => { context.log(types.LogLevelLabel.ERROR, `An error occurred while initializing the reflection data for the Storm Stack project: ${error.message} ${error.stack ?? ""}`); throw new Error("An error occurred while initializing the reflection data for the Storm Stack project", { cause: error }); }); } chunk3ONWID2V_cjs.__name(prepareEntry, "prepareEntry"); async function prepareRuntime(context, hooks) { context.log(types.LogLevelLabel.TRACE, `Preparing the runtime artifacts for the Storm Stack project.`); await context.vfs.rm(context.runtimePath); await hooks.callHook("prepare:runtime", context).catch((error) => { context.log(types.LogLevelLabel.ERROR, `An error occurred while preparing the runtime artifacts for the Storm Stack project: ${error.message} ${error.stack ?? ""}`); throw new Error("An error occurred while preparing the runtime artifacts for the Storm Stack project", { cause: error }); }); context.log(types.LogLevelLabel.TRACE, "Generating runtime barrel file"); await context.vfs.writeRuntimeFile("index", joinPaths.joinPaths(context.runtimePath, "index.ts"), ` ${chunkONBGOAON_cjs.getFileHeader()} ${(await context.vfs.listRuntimeFiles()).filter((file) => !isParentPath.isParentPath(file.path, joinPaths.joinPaths(context.runtimePath, "log")) && !isParentPath.isParentPath(file.path, joinPaths.joinPaths(context.runtimePath, "storage"))).map((file) => `export * from "./${replace.replacePath(file.path, context.runtimePath).replace(filePathFns.findFileExtension(file.path), "")}";`).join("\n")} `); } chunk3ONWID2V_cjs.__name(prepareRuntime, "prepareRuntime"); async function prepareTypes(context, hooks) { context.log(types.LogLevelLabel.TRACE, `Preparing the TypeScript definitions for the Storm Stack project.`); await context.vfs.rm(context.runtimeDtsFilePath); context.log(types.LogLevelLabel.TRACE, "Transforming runtime files."); const runtimeFiles = await Promise.all((await context.vfs.listRuntimeFiles()).filter((file) => !context.vfs.isMatchingRuntimeId("index", file.id)).map(async (file) => { file.contents = await context.compiler.transform(context, file.path, file.contents, { skipTransformUnimport: true, babel: { plugins: [ chunkZC2JNV4B_cjs.ModuleResolverPlugin, ...context.options.babel.plugins ] } }); context.log(types.LogLevelLabel.TRACE, `Writing transformed runtime file ${file.id}.`); await context.vfs.writeRuntimeFile(file.id, file.path, file.contents); return file.path; })); const typescriptPath = await resolve.resolvePackage("typescript"); if (!typescriptPath) { throw new Error("Could not resolve TypeScript package location. Please ensure TypeScript is installed."); } const files = runtimeFiles.reduce( (ret, fileName) => { const formatted = replace.replacePath(fileName, context.options.workspaceRoot); if (!ret.includes(formatted)) { ret.push(formatted); } return ret; }, [ joinPaths.joinPaths(typescriptPath, "lib", "lib.esnext.full.d.ts") ] // await listFiles(joinPaths(typescriptPath, "lib", "lib.*.d.ts")) ); context.log(types.LogLevelLabel.TRACE, "Parsing TypeScript configuration for the Storm Stack project."); const sourceFileDts = chunkEG72EGDV_cjs.getSourceFile(context.runtimeDtsFilePath, `${chunkONBGOAON_cjs.getFileHeader(null, false)} `); await hooks.callHook("prepare:types", context, sourceFileDts).catch((error) => { context.log(types.LogLevelLabel.ERROR, `An error occurred while preparing the TypeScript definitions for the Storm Stack project: ${error.message} ${error.stack ?? ""}`); throw new Error("An error occurred while preparing the TypeScript definitions for the Storm Stack project", { cause: error }); }); await context.vfs.writeFileToDisk(sourceFileDts.id, chunkEG72EGDV_cjs.getString(sourceFileDts.code)); const resolvedTsconfig = chunkZ72ISLE5_cjs.getParsedTypeScriptConfig(context.options.workspaceRoot, context.options.projectRoot, context.tsconfig.tsconfigFilePath, defu__default.default({ compilerOptions: { strict: false, noEmit: false, declaration: true, declarationMap: false, emitDeclarationOnly: true, skipLibCheck: true }, exclude: [ "node_modules", "dist" ], include: files }, context.options.tsconfigRaw ?? {})); resolvedTsconfig.options.configFilePath = joinPaths.joinPaths(context.options.workspaceRoot, context.tsconfig.tsconfigFilePath); resolvedTsconfig.options.pathsBasePath = context.options.workspaceRoot; resolvedTsconfig.options.suppressOutputPathCheck = true; context.log(types.LogLevelLabel.TRACE, "Creating the TypeScript compiler host"); const program = typescript.createProgram(files, resolvedTsconfig.options, typescript.createCompilerHost(resolvedTsconfig.options)); context.log(types.LogLevelLabel.TRACE, `Running TypeScript compiler on ${runtimeFiles.length} runtime files.`); let runtimeModules = ""; const emitResult = program.emit(void 0, (fileName, text, _, __, sourceFiles, _data) => { const sourceFile2 = sourceFiles?.[0]; if (sourceFile2?.fileName && !fileName.endsWith(".map")) { if (context.vfs.isRuntimeFile(sourceFile2.fileName)) { runtimeModules += ` declare module "${context.vfs.resolveId(sourceFile2.fileName)}" { ${text.trim().replace(/^\s*export\s*declare\s*/gm, "export ").replace(/^\s*declare\s*/gm, "")} } `; } } }, void 0, true); const diagnostics = typescript.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); const diagnosticMessages = []; diagnostics.forEach((diagnostic) => { if (diagnostic.file) { const { line, character } = typescript.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); const message = typescript.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); diagnosticMessages.push(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); } else { const message = typescript.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); diagnosticMessages.push(message); } }); const diagnosticMessage = diagnosticMessages.join("\n"); if (diagnosticMessage) { throw new Error(`TypeScript compilation failed: ${diagnosticMessage.length > 5e3 ? `${diagnosticMessage.slice(0, 5e3)}...` : diagnosticMessage}`); } const mainEntryPointFilePath = process.env.STORM_STACK_LOCAL ? joinPaths.joinPaths(context.options.workspaceRoot, "dist/packages/types") : await resolve.resolvePackage("@storm-stack/types"); if (!mainEntryPointFilePath) { throw new Error("Could not resolve @storm-stack/types package location."); } context.log(types.LogLevelLabel.TRACE, `Running API Extractor on the @storm-stack/types package at ${mainEntryPointFilePath}.`); const untrimmedFilePath = joinPaths.joinPaths(context.dtsPath, `${context.meta.projectRootHash}.d.ts`); const extractorResult = apiExtractor.Extractor.invoke(apiExtractor.ExtractorConfig.prepare({ configObject: { mainEntryPointFilePath: joinPaths.joinPaths(mainEntryPointFilePath, "dist/esm/src/index.d.ts"), apiReport: { enabled: false, // `reportFileName` is not been used. It's just to fit the requirement of API Extractor. reportFileName: "report.api.md" }, docModel: { enabled: false }, dtsRollup: { enabled: true, untrimmedFilePath }, tsdocMetadata: { enabled: false }, compiler: { tsconfigFilePath: filePathFns.relativePath(joinPaths.joinPaths(context.options.workspaceRoot, context.options.projectRoot), joinPaths.joinPaths(context.options.workspaceRoot, context.tsconfig.tsconfigFilePath)) }, projectFolder: joinPaths.joinPaths(context.options.workspaceRoot, context.options.projectRoot), newlineKind: "lf" }, configObjectFullPath: void 0, packageJsonFullPath: joinPaths.joinPaths(context.options.workspaceRoot, context.options.projectRoot, "package.json") }), { localBuild: true, showVerboseMessages: true }); if (!extractorResult.succeeded) { throw new Error(`API Extractor completed with ${extractorResult.errorCount} errors and ${extractorResult.warningCount} warnings when processing @storm-stack/types package.`); } context.log(types.LogLevelLabel.TRACE, `Generating TypeScript declaration file in ${context.runtimeDtsFilePath}.`); const sourceFile = chunkEG72EGDV_cjs.getSourceFile(context.runtimeDtsFilePath, `${chunkONBGOAON_cjs.getFileHeader(null, false)} // This file is an augmentation to the built-in StormContext interface // Thus cannot contain any top-level imports // <https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation> ${(await context.vfs.readFile(untrimmedFilePath)).replace(/\s*export.*__Ω.*;/g, "").replace(/^export\s*\{\s*\}\s*$/gm, "").replace(/^export\s*(?:declare\s*)?interface\s*/gm, "interface ").replace(/^export\s*(?:declare\s*)?type\s*/gm, "type ").replace(/^export\s*(?:declare\s*)?const\s*/gm, "declare const ").replace(/: Storage(?:_\d+)?;$/gm, ': import("unstorage").Storage<import("unstorage").StorageValue>;')} ${runtimeModules}`.replace( // eslint-disable-next-line regexp/no-super-linear-backtracking /import\s*(?:type\s*)?\{?[\w,\s]*(?:\}\s*)?from\s*(?:'|")@?[a-zA-Z0-9-\\/.]*(?:'|");?/g, "" ).replaceAll("#private;", "")); await hooks.callHook("prepare:types", context, sourceFile).catch((error) => { context.log(types.LogLevelLabel.ERROR, `An error occurred while preparing the TypeScript definitions for the Storm Stack project: ${error.message} ${error.stack ?? ""}`); throw new Error("An error occurred while preparing the TypeScript definitions for the Storm Stack project", { cause: error }); }); await context.vfs.writeFileToDisk(sourceFile.id, chunkEG72EGDV_cjs.getString(sourceFile.code)); } chunk3ONWID2V_cjs.__name(prepareTypes, "prepareTypes"); // src/commands/prepare/index.ts async function prepare(context, hooks) { await chunkEND3JFY3_cjs.writeFile(context.log, joinPaths.joinPaths(context.dataPath, "meta.json"), JSON.stringify({ ...context.meta, runtimeIdMap: JSON.stringify(context.meta.runtimeIdMap), virtualFiles: JSON.stringify(context.meta.virtualFiles) }, null, 2)); context.persistedMeta = context.meta; await hooks.callHook("prepare:begin", context).catch((error) => { context.log(types.LogLevelLabel.ERROR, `An error occured while starting the prepare process for the Storm Stack project: ${error.message} ${error.stack ?? ""}`); throw new Error("An error occured while starting the prepare process for the Storm Stack project", { cause: error }); }); if (!exists.existsSync(context.cachePath)) { await helpers.createDirectory(context.cachePath); } if (!exists.existsSync(context.dataPath)) { await helpers.createDirectory(context.dataPath); } await prepareConfig(context, hooks); if (context.options.projectType === "application") { await prepareRuntime(context, hooks); } if (context.options.output.dts !== false) { await prepareTypes(context, hooks); } if (context.options.projectType === "application") { await prepareEntry(context, hooks); } await prepareDeploy(context, hooks); context.tsconfig = chunkZ72ISLE5_cjs.getParsedTypeScriptConfig(context.options.workspaceRoot, context.options.projectRoot, context.options.tsconfig); if (!context.tsconfig) { throw new Error("Failed to parse the TypeScript configuration file."); } await hooks.callHook("prepare:complete", context).catch((error) => { context.log(types.LogLevelLabel.ERROR, `An error occured while finishing the prepare process for the Storm Stack project: ${error.message} ${error.stack ?? ""}`); throw new Error("An error occured while finishing the prepare process for the Storm Stack project", { cause: error }); }); await chunkUTUPUYE6_cjs.writeMetaFile(context); } chunk3ONWID2V_cjs.__name(prepare, "prepare"); exports.prepare = prepare; //# sourceMappingURL=chunk-J7ICWR23.cjs.map //# sourceMappingURL=chunk-J7ICWR23.cjs.map