@powerlines/core 0.48.53 → 0.48.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/constants/api.mjs.map +1 -1
- package/dist/constants/commands.mjs.map +1 -1
- package/dist/constants/devtools.mjs.map +1 -1
- package/dist/constants/environments.mjs.map +1 -1
- package/dist/constants/extensions.mjs.map +1 -1
- package/dist/constants/fs.mjs.map +1 -1
- package/dist/constants/hooks.mjs.map +1 -1
- package/dist/constants/log-level.mjs.map +1 -1
- package/dist/constants/meta.mjs.map +1 -1
- package/dist/constants/plugin.mjs.map +1 -1
- package/dist/context/base-context.mjs.map +1 -1
- package/dist/context/context.mjs.map +1 -1
- package/dist/context/environment-context.mjs.map +1 -1
- package/dist/context/execution-context.mjs.map +1 -1
- package/dist/context/plugin-context.mjs.map +1 -1
- package/dist/lib/config.mjs.map +1 -1
- package/dist/lib/context-helpers.mjs.map +1 -1
- package/dist/lib/entry.mjs.map +1 -1
- package/dist/lib/environment.mjs.map +1 -1
- package/dist/lib/events.mjs.map +1 -1
- package/dist/lib/generate-types.mjs.map +1 -1
- package/dist/lib/hooks.mjs.map +1 -1
- package/dist/lib/install-dependencies.mjs.map +1 -1
- package/dist/lib/meta.mjs.map +1 -1
- package/dist/lib/plugins.mjs.map +1 -1
- package/dist/lib/resolver.mjs.map +1 -1
- package/dist/lib/streaming-channel.mjs.map +1 -1
- package/dist/lib/typescript/ts-morph.mjs.map +1 -1
- package/dist/lib/typescript/tsconfig.mjs.map +1 -1
- package/dist/lib/unplugin/helpers.mjs.map +1 -1
- package/dist/lib/unplugin/module-resolution.mjs.map +1 -1
- package/dist/lib/unplugin/plugin.mjs.map +1 -1
- package/dist/lib/utilities/file-header.mjs.map +1 -1
- package/dist/lib/utilities/format.cjs +7 -1
- package/dist/lib/utilities/format.d.cts.map +1 -1
- package/dist/lib/utilities/format.d.mts.map +1 -1
- package/dist/lib/utilities/format.mjs +6 -1
- package/dist/lib/utilities/format.mjs.map +1 -1
- package/dist/lib/utilities/source-file.mjs.map +1 -1
- package/dist/lib/utilities/source-map.mjs.map +1 -1
- package/dist/lib/utilities/write-file.mjs.map +1 -1
- package/dist/lib/vfs.cjs +1 -1
- package/dist/lib/vfs.mjs +1 -1
- package/dist/lib/vfs.mjs.map +1 -1
- package/dist/plugin-base.mjs.map +1 -1
- package/dist/plugin-utils/build-helpers.mjs.map +1 -1
- package/dist/plugin-utils/combine-plugins.mjs.map +1 -1
- package/dist/plugin-utils/context-helpers.mjs.map +1 -1
- package/dist/plugin-utils/docs-helper.mjs.map +1 -1
- package/dist/plugin-utils/enable-plugin.mjs.map +1 -1
- package/dist/plugin-utils/extend.mjs.map +1 -1
- package/dist/plugin-utils/filter.mjs.map +1 -1
- package/dist/plugin-utils/format-package-json.mjs.map +1 -1
- package/dist/plugin-utils/format.mjs.map +1 -1
- package/dist/plugin-utils/get-config-path.mjs.map +1 -1
- package/dist/plugin-utils/helpers.mjs.map +1 -1
- package/dist/plugin-utils/install.mjs.map +1 -1
- package/dist/plugin-utils/logging.mjs.map +1 -1
- package/dist/plugin-utils/merge.mjs.map +1 -1
- package/dist/plugin-utils/modules.mjs.map +1 -1
- package/dist/plugin-utils/paths.mjs.map +1 -1
- package/dist/plugin-utils/virtual.mjs.map +1 -1
- package/dist/storage/base.mjs.map +1 -1
- package/dist/storage/file-system.mjs.map +1 -1
- package/dist/storage/helpers.mjs.map +1 -1
- package/dist/storage/virtual.mjs.map +1 -1
- package/package.json +10 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-types.mjs","names":[],"sources":["../../src/lib/generate-types.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { resolvePackage } from \"@stryke/fs/resolve\";\nimport { getUnique } from \"@stryke/helpers/get-unique\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { findFileName } from \"@stryke/path/file-path-fns\";\nimport { isParentPath } from \"@stryke/path/is-parent-path\";\nimport { replaceExtension, replacePath } from \"@stryke/path/replace\";\nimport { prettyBytes } from \"@stryke/string-format/pretty-bytes\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { DiagnosticCategory, Node, Project, SourceFile } from \"ts-morph\";\nimport { ResolvedConfig } from \"../types/config\";\nimport {\n Context,\n EnvironmentContext,\n ExecutionContext\n} from \"../types/context\";\nimport { TypesResult } from \"../types/plugin\";\nimport { callHook } from \"./hooks\";\nimport { createProgram } from \"./typescript/ts-morph\";\nimport { getTypescriptFileHeader } from \"./utilities/file-header\";\nimport { format } from \"./utilities/format\";\n\ninterface ModuleExportSpecifier {\n name: string;\n alias?: string;\n default?: boolean;\n type?: boolean;\n}\n\ninterface ModuleReference {\n name?: string;\n specifiers?: ModuleExportSpecifier[];\n all?: boolean;\n}\n\ninterface ImportModuleReference extends ModuleReference {\n name: string;\n ambient?: boolean;\n}\n\ninterface ExportModuleReference extends ModuleReference {\n text: string;\n fullText: string;\n comment?: string;\n}\n\ninterface ModuleDeclaration {\n name: string;\n text: string;\n sourceFile: SourceFile;\n comment?: string;\n exports: (ExportModuleReference | string)[];\n imports: ImportModuleReference[];\n}\n\nexport interface TypegenContext {\n context: Context;\n emitted: Map<string, string>;\n modules: ModuleDeclaration[];\n}\n\n/**\n * Formats the generated TypeScript types source code.\n *\n * @param code - The generated TypeScript code.\n * @returns The formatted TypeScript code.\n */\nexport function formatTypes(code = \"\"): string {\n return code.replaceAll(\"#private;\", \"\").replace(/__Ω/g, \"\");\n}\n\nasync function extractModuleDeclarations(\n ctx: TypegenContext,\n filePath: string,\n name: string,\n text: string\n): Promise<ModuleDeclaration> {\n const imports: ImportModuleReference[] = [];\n const exports: (ExportModuleReference | string)[] = [];\n\n const comment = text\n .match(\n new RegExp(\n `\\\\/\\\\*\\\\*(?s:.)*?@module\\\\s+${\n ctx.context.config.framework?.name ?? \"powerlines\"\n }:${name}(?s:.)*?\\\\*\\\\/\\\\s+`\n )\n )\n ?.find(comment => isSetString(comment?.trim()));\n\n // Parse the emitted .d.ts content using an in-memory ts-morph project\n const project = new Project({ useInMemoryFileSystem: true });\n const sourceFile = project.createSourceFile(\"module.d.ts\", text);\n\n // Collect /// <reference types=\"...\" /> directives as ambient dependencies\n for (const ref of sourceFile.getTypeReferenceDirectives()) {\n if (\n ref.getFileName() &&\n !ctx.context.builtins.some(builtin => ref.getFileName().endsWith(builtin))\n ) {\n imports.push({\n name: ref.getFileName(),\n ambient: true\n });\n }\n }\n\n for (const statement of sourceFile.getStatements()) {\n // --- Import declarations ---\n if (Node.isImportDeclaration(statement)) {\n const moduleSpec = statement.getModuleSpecifierValue();\n\n // Namespace import: import * as X from '...'\n if (statement.getNamespaceImport()) {\n imports.push({\n name: moduleSpec,\n specifiers: [\n {\n name: statement.getNamespaceImport()!.getText()\n }\n ],\n all: true\n });\n }\n\n // Named imports: import X from '...' or import { A, B as C } from '...'\n else if (\n statement.getNamedImports().length > 0 ||\n statement.getDefaultImport()\n ) {\n const specifiers: ModuleExportSpecifier[] = [];\n if (statement.getDefaultImport()) {\n specifiers.push({\n name: statement.getDefaultImport()!.getText(),\n default: true,\n type: statement.isTypeOnly()\n });\n }\n\n statement.getNamedImports().forEach(named => {\n specifiers.push({\n name: named.getName(),\n alias: named.getAliasNode()?.getText(),\n type: statement.isTypeOnly()\n });\n });\n\n imports.push({\n name: moduleSpec,\n specifiers\n });\n }\n }\n\n // --- Export declarations ---\n else if (Node.isExportDeclaration(statement)) {\n const moduleSpec = statement.getModuleSpecifierValue();\n if (moduleSpec) {\n // Resolve the module specifier\n let resolvedSpec = moduleSpec;\n if (!ctx.context.builtins.includes(moduleSpec)) {\n if (ctx.emitted.has(moduleSpec)) {\n resolvedSpec = ctx.emitted.get(moduleSpec)!;\n } else {\n const resolvedModule = await ctx.context.resolve(\n moduleSpec,\n filePath\n );\n if (isSetString(resolvedModule?.id)) {\n resolvedSpec = resolvedModule.id;\n }\n }\n }\n\n // Re-export from another module\n const namedExports = statement.getNamedExports();\n if (namedExports.length > 0) {\n exports.push({\n name: resolvedSpec,\n text: statement.getText(),\n fullText: statement.getFullText(),\n specifiers: namedExports.map(named => ({\n name: named.getName(),\n alias: named.getAliasNode()?.getText(),\n type: statement.isTypeOnly()\n })),\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n .trim()\n });\n } else {\n // export * from '...'\n exports.push({\n name: resolvedSpec,\n text: statement.getText(),\n fullText: statement.getFullText(),\n all: true,\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n .trim()\n });\n }\n } else {\n const specifiers = statement.getNamedExports().map(named => ({\n name: named.getName(),\n alias: named.getAliasNode()?.getText(),\n type: statement.isTypeOnly()\n }));\n if (specifiers.length > 0) {\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n specifiers,\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n }\n }\n\n // --- Export assignments (export default ...) ---\n else if (Node.isExportAssignment(statement)) {\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n\n // --- Function declarations (export declare function ...) ---\n else if (\n Node.isFunctionDeclaration(statement) &&\n statement.isExported() &&\n statement.getNameNode()\n ) {\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n specifiers: [\n {\n name: statement.getNameNode()!.getText()\n }\n ],\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n\n // --- Variable statements (export declare const ...) ---\n else if (Node.isVariableStatement(statement) && statement.isExported()) {\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n specifiers: statement\n .getDeclarationList()\n .getDeclarations()\n .filter(\n decl => decl.getNameNode() && Node.isIdentifier(decl.getNameNode())\n )\n .map(decl => ({ name: decl.getNameNode().getText() })),\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n\n // --- Class declarations (export declare class ...) ---\n else if (Node.isClassDeclaration(statement) && statement.isExported()) {\n const nameNode = statement.getNameNode();\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n specifiers: nameNode ? [{ name: nameNode.getText() }] : undefined,\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n\n // --- Interface declarations (export declare interface ...) ---\n else if (Node.isInterfaceDeclaration(statement) && statement.isExported()) {\n const nameNode = statement.getNameNode();\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n specifiers: nameNode ? [{ name: nameNode.getText() }] : undefined,\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n\n // --- Type alias declarations (export declare type ...) ---\n else if (Node.isTypeAliasDeclaration(statement) && statement.isExported()) {\n const nameNode = statement.getNameNode();\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n specifiers: nameNode ? [{ name: nameNode.getText() }] : undefined,\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n\n // --- All other statements (declarations) ---\n else if (\n ctx.context.config.output.sourceMap ||\n !statement.getFullText().includes(\"//# sourceMappingURL=\")\n ) {\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n }\n\n return {\n name,\n text,\n sourceFile,\n comment,\n imports,\n exports\n };\n}\n\n/**\n * Emits TypeScript declaration types for the provided files using the given TypeScript configuration.\n *\n * @param context - The context containing options and environment paths.\n * @param files - The list of files to generate types for.\n * @returns A promise that resolves to the generated TypeScript declaration types.\n */\nexport async function emitBuiltinTypes<TContext extends Context>(\n context: TContext,\n files: string[]\n): Promise<{ code: string; directives: string[] }> {\n if (files.length === 0) {\n context.debug(\n \"No files provided for TypeScript types generation. Typescript compilation for built-in modules will be skipped.\"\n );\n return { code: \"\", directives: [] };\n }\n\n context.debug(\n `Running the TypeScript compiler for ${\n files.length\n } generated built-in module files.`\n );\n\n const program = createProgram(context, {\n skipAddingFilesFromTsConfig: true,\n compilerOptions: {\n declaration: true,\n declarationMap: false,\n emitDeclarationOnly: true,\n sourceMap: false,\n outDir: replacePath(context.builtinsPath, context.config.cwd),\n composite: false,\n incremental: false,\n tsBuildInfoFile: undefined\n }\n });\n\n program.addSourceFilesAtPaths(files);\n const emitResult = program.emitToMemory({ emitOnlyDtsFiles: true });\n\n const diagnostics = emitResult.getDiagnostics();\n if (diagnostics && diagnostics.length > 0) {\n if (diagnostics.some(d => d.getCategory() === DiagnosticCategory.Error)) {\n throw new Error(\n `The Typescript emit process failed while generating built-in types: \\n ${diagnostics\n .filter(d => d.getCategory() === DiagnosticCategory.Error)\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n } else if (\n diagnostics.some(d => d.getCategory() === DiagnosticCategory.Warning)\n ) {\n context.warn(\n `The Typescript emit process completed with warnings while generating built-in types: \\n ${diagnostics\n .filter(d => d.getCategory() === DiagnosticCategory.Warning)\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n } else {\n context.debug(\n `The Typescript emit process completed with diagnostic messages while generating built-in types: \\n ${diagnostics\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n }\n }\n\n const emittedFiles = emitResult.getFiles();\n context.debug(\n `The TypeScript compiler emitted ${\n emittedFiles.length\n } files for built-in types.`\n );\n\n if (emittedFiles.length === 0) {\n context.warn(\n \"The TypeScript compiler did not emit any files for built-in types. This may indicate an issue with the TypeScript configuration or the provided files.\"\n );\n return { code: \"\", directives: [] };\n }\n\n const ctx = {\n context,\n modules: [] as ModuleDeclaration[],\n emitted: new Map<string, string>()\n };\n\n await Promise.all(\n emittedFiles.map(async emittedFile => {\n const filePath = appendPath(emittedFile.filePath, context.config.cwd);\n if (\n !filePath.endsWith(\".map\") &&\n findFileName(filePath) !== \"tsconfig.tsbuildinfo\" &&\n isParentPath(filePath, context.builtinsPath)\n ) {\n const moduleName = replaceExtension(\n replacePath(\n replacePath(filePath, context.builtinsPath),\n replacePath(context.builtinsPath, context.config.cwd)\n ),\n \"\",\n {\n fullExtension: true\n }\n );\n if (context.builtins.includes(moduleName)) {\n ctx.emitted.set(filePath, moduleName);\n ctx.modules.push(\n await extractModuleDeclarations(\n ctx,\n filePath,\n moduleName,\n emittedFile.text\n )\n );\n }\n }\n })\n );\n\n const commonDeclarations = [] as ExportModuleReference[];\n for (const mod of ctx.modules) {\n for (const importRef of mod.imports.filter(importRef =>\n context.builtins.some(builtin => importRef.name.endsWith(`:${builtin}`))\n )) {\n const moduleRef = ctx.modules.find(moduleRef =>\n importRef.name.endsWith(`:${moduleRef.name}`)\n );\n if (moduleRef) {\n let declaration: ExportModuleReference | undefined;\n for (const decl of moduleRef.exports.filter(decl =>\n isSetObject(decl)\n )) {\n const specifiers = decl.specifiers?.filter(specifier =>\n importRef.specifiers?.some(\n s =>\n (specifier.alias ? specifier.alias : specifier.name) ===\n (s.alias ? s.alias : s.name)\n )\n );\n if (specifiers && specifiers.length > 0) {\n importRef.specifiers = importRef.specifiers?.filter(\n s =>\n !specifiers.some(\n specifier =>\n (specifier.alias ? specifier.alias : specifier.name) ===\n (s.alias ? s.alias : s.name)\n )\n );\n if (\n importRef.specifiers &&\n importRef.specifiers.length === 0 &&\n !importRef.all &&\n !importRef.ambient\n ) {\n mod.imports = mod.imports.filter(\n imp => imp.name !== importRef.name\n );\n }\n\n declaration = decl;\n break;\n }\n }\n\n if (declaration) {\n for (const decl of moduleRef.exports.filter(\n decl =>\n isSetObject(decl) &&\n !decl.specifiers?.some(s =>\n declaration?.specifiers?.some(\n specifier =>\n (specifier.alias ? specifier.alias : specifier.name) ===\n (s.alias ? s.alias : s.name)\n )\n )\n )) {\n const exportModuleRef = decl as ExportModuleReference;\n if (\n (exportModuleRef.specifiers?.some(s => s.alias || s.name) ||\n exportModuleRef.name) &&\n new RegExp(\n `(^|\\\\s|\\\\n|\\\\r\\\\n|\\\\(|\\\\)|<|>|{|}|\\\\[|\\\\]|\\\\!|\\\\?|\\\\.|,|\\\\*|&|:)(${\n exportModuleRef.specifiers\n ?.map(s => `${s.alias ? `${s.alias}|` : \"\"}${s.name}`)\n .join(\"|\") || exportModuleRef.name\n })($|\\\\s|\\\\n|\\\\r\\\\n|\\\\(|\\\\)|<|>|{|}|\\\\[|\\\\]|\\\\!|\\\\?|\\\\.|,|\\\\*|&|:|;)`\n ).test(declaration.text)\n ) {\n commonDeclarations.push(exportModuleRef);\n }\n }\n commonDeclarations.push(declaration);\n }\n }\n }\n }\n\n let code = \"\";\n const directives: string[] = [];\n\n for (const commonDeclaration of commonDeclarations) {\n code += formatTypes(\n `${\n commonDeclaration.comment?.trim()\n ? commonDeclaration.comment.trim()\n : \"\"\n }${commonDeclaration.comment?.trim() ? \"\\n\" : \"\"}${formatTypes(\n commonDeclaration.text\n .replace(/\\s*export\\s*/, \"\")\n .replace(/\\s*declare\\s*interface\\s*/, \"interface \")\n .replace(/\\s*declare\\s*type\\s*/, \"type \")\n )}`\n );\n code += \"\\n\\n\";\n }\n\n for (const mod of ctx.modules) {\n code += mod.comment ? `${mod.comment.trim()}\\n` : \"\";\n code += `declare module \"${context.config.framework?.name ?? \"powerlines\"}:${mod.name}\" { \\n`;\n for (const importRef of mod.imports) {\n if (importRef.ambient) {\n code += directives.push(importRef.name);\n } else if (importRef.all) {\n code += `\\timport * as ${findFileName(importRef.name)} from \"${importRef.name}\";\\n`;\n } else if (importRef.specifiers) {\n const typeOnly = importRef.specifiers.every(s => s.type) ? \" type\" : \"\";\n const specifiers = importRef.specifiers\n .map(s => (s.alias ? `${s.name} as ${s.alias}` : s.name))\n .join(\", \");\n code += `\\timport${typeOnly} { ${specifiers} } from \"${importRef.name}\";\\n`;\n }\n }\n\n if (mod.imports.length > 0) {\n code += \"\\n\";\n }\n\n for (const exportRef of mod.exports.filter(\n e =>\n isString(e) ||\n !e.specifiers ||\n !commonDeclarations.some(\n commonDecl =>\n commonDecl.specifiers &&\n commonDecl.specifiers.some(specifier =>\n e.specifiers?.some(\n s =>\n (s.alias ? s.alias : s.name) ===\n (specifier.alias ? specifier.alias : specifier.name)\n )\n )\n )\n )) {\n if (isSetString(exportRef)) {\n code += `${exportRef}\\n`;\n } else if (exportRef.name) {\n if (exportRef.all) {\n code += `${\n exportRef.comment?.trim() ? exportRef.comment.trim() : \"\"\n }${\n exportRef.comment?.trim() ? \"\\n\" : \"\"\n }export * from \"${exportRef.name}\";\\n`;\n } else if (exportRef.specifiers) {\n if (exportRef.comment?.trim()) {\n code += `${exportRef.comment.trim()}\\n`;\n }\n\n code += `\\texport${\n exportRef.specifiers.every(s => s.type) ? \" type\" : \"\"\n } { ${exportRef.specifiers\n .map(s => (s.alias ? `${s.name} as ${s.alias}` : s.name))\n .join(\", \")} } from \"${exportRef.name}\";\\n`;\n }\n } else {\n code += `${exportRef.comment?.trim() ? exportRef.comment.trim() : \"\"}${\n exportRef.comment?.trim() ? \"\\n\" : \"\"\n }${formatTypes(\n exportRef.text\n .replace(/\\s*export\\s*declare\\s*/, \"export \")\n .replace(/\\s*declare\\s*/, \" \")\n )}\\n`;\n }\n }\n\n mod.exports\n .filter(\n e =>\n !isString(e) &&\n e.specifiers &&\n commonDeclarations.some(\n commonDeclaration =>\n commonDeclaration.specifiers &&\n commonDeclaration.specifiers.some(specifier =>\n e.specifiers?.some(\n s =>\n (s.alias ? s.alias : s.name) ===\n (specifier.alias ? specifier.alias : specifier.name)\n )\n )\n )\n )\n .forEach((e, i, arr) => {\n if (i === 0) {\n code += \"\\nexport { \";\n } else {\n code += \", \";\n }\n\n code += `${\n (e as ExportModuleReference)?.specifiers\n ?.filter(s =>\n commonDeclarations.some(\n commonDeclaration =>\n commonDeclaration.specifiers &&\n commonDeclaration.specifiers.some(\n specifier =>\n (s.alias ? s.alias : s.name) ===\n (specifier.alias ? specifier.alias : specifier.name)\n )\n )\n )\n .map(s => (s.alias ? `${s.name} as ${s.alias}` : s.name))\n .join(\", \") || \"\"\n }`;\n\n if (i === arr.length - 1) {\n code += ` };\\n`;\n }\n });\n\n code += \"}\";\n code += \"\\n\\n\";\n }\n\n code = await format(context, context.typesPath, code);\n\n context.debug(\n `A TypeScript declaration file (size: ${prettyBytes(\n new Blob(toArray(code)).size\n )}) emitted for the built-in modules types.`\n );\n\n return { code, directives };\n}\n\n/**\n * Generate the Powerlines TypeScript declaration file\n *\n * @param context - The execution context for generating the TypeScript declaration file, which provides access to the project configuration, environment, and utility functions for performing the generation. The context is used to manage the state and behavior of the generation process, allowing for hooks to be called at different stages and for environment-specific configurations to be applied.\n * @param env - The environment context to use for generating the TypeScript declaration file\n */\nexport async function handleTypes<\n TResolvedConfig extends ResolvedConfig,\n TSystemContext = unknown\n>(\n context: ExecutionContext<TResolvedConfig, TSystemContext>,\n env: EnvironmentContext<TResolvedConfig, TSystemContext>\n) {\n env.debug(`Preparing the TypeScript definitions for the Powerlines project.`);\n\n if (env.fs.existsSync(env.typesPath)) {\n await env.fs.remove(env.typesPath);\n }\n\n const typescriptPath = await resolvePackage(\"typescript\");\n if (!typescriptPath) {\n throw new Error(\n \"Could not resolve TypeScript package location. Please ensure TypeScript is installed.\"\n );\n }\n\n env.debug(\"Running TypeScript compiler for built-in runtime module files.\");\n\n let { code, directives } = await emitBuiltinTypes(\n env,\n (await env.getBuiltins()).reduce<string[]>((ret, builtin) => {\n const formatted = replacePath(builtin.path, env.config.cwd);\n if (!ret.includes(formatted)) {\n ret.push(formatted);\n }\n\n return ret;\n }, [])\n );\n\n env.debug(\n `Generating TypeScript declaration file ${replacePath(\n env.typesPath,\n context.config.cwd\n )}.`\n );\n\n const merge = async (\n currentResult: string | TypesResult,\n previousResult: string | TypesResult\n ): Promise<string | TypesResult> => {\n if (\n !isSetString(currentResult) &&\n !isSetObject(currentResult) &&\n !isSetString(previousResult) &&\n !isSetObject(previousResult)\n ) {\n return { code, directives };\n }\n\n const previous = (\n await format(\n env,\n env.typesPath,\n isSetString(previousResult)\n ? previousResult\n : isSetObject(previousResult)\n ? previousResult.code\n : \"\"\n )\n )\n .trim()\n .replace(code, \"\")\n .trim();\n const current = (\n await format(\n env,\n env.typesPath,\n isSetString(currentResult)\n ? currentResult\n : isSetObject(currentResult)\n ? currentResult.code\n : \"\"\n )\n )\n .trim()\n .replace(previous, \"\")\n .trim()\n .replace(code, \"\")\n .trim();\n\n return {\n directives: [\n ...(isSetObject(currentResult) && currentResult.directives\n ? currentResult.directives\n : []),\n ...(isSetObject(previousResult) && previousResult.directives\n ? previousResult.directives\n : [])\n ],\n code: await format(\n env,\n env.typesPath,\n `${\n !previous.includes(getTypescriptFileHeader(env)) &&\n !current.includes(getTypescriptFileHeader(env))\n ? `${code}\\n`\n : \"\"\n }${previous}\\n${current}`.trim()\n )\n };\n };\n const asNextParam = (\n previousResult: string | TypesResult | null | undefined\n ) => (isObject(previousResult) ? previousResult.code : previousResult);\n\n let result = await callHook(\n context,\n \"types\",\n {\n environment: env,\n sequential: true,\n order: \"pre\",\n result: \"merge\",\n merge,\n asNextParam\n },\n code\n );\n if (result) {\n if (isSetObject(result)) {\n code = result.code;\n if (Array.isArray(result.directives) && result.directives.length > 0) {\n directives = getUnique([...directives, ...result.directives]).filter(\n Boolean\n );\n }\n } else if (isSetString(result)) {\n code = result;\n }\n }\n\n result = await callHook(\n context,\n \"types\",\n {\n environment: env,\n sequential: true,\n order: \"normal\",\n result: \"merge\",\n merge,\n asNextParam\n },\n code\n );\n if (result) {\n if (isSetObject(result)) {\n code = result.code;\n if (Array.isArray(result.directives) && result.directives.length > 0) {\n directives = getUnique([...directives, ...result.directives]).filter(\n Boolean\n );\n }\n } else if (isSetString(result)) {\n code = result;\n }\n }\n\n result = await callHook(\n context,\n \"types\",\n {\n environment: env,\n sequential: true,\n order: \"post\",\n result: \"merge\",\n merge,\n asNextParam\n },\n code\n );\n if (result) {\n if (isSetObject(result)) {\n code = result.code;\n if (Array.isArray(result.directives) && result.directives.length > 0) {\n directives = getUnique([...directives, ...result.directives]).filter(\n Boolean\n );\n }\n } else if (isSetString(result)) {\n code = result;\n }\n }\n\n if (isSetString(code?.trim()) || directives.length > 0) {\n await env.fs.write(\n env.typesPath,\n `${\n directives.length > 0\n ? `${directives.map(directive => `/// <reference types=\"${directive}\" />`).join(\"\\n\")}\n\n`\n : \"\"\n }${getTypescriptFileHeader(env, { directive: null, prettierIgnore: false })}\n\n${formatTypes(code)}\n`\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwFA,SAAgB,YAAY,OAAO,IAAY;CAC7C,OAAO,KAAK,WAAW,aAAa,EAAE,CAAC,CAAC,QAAQ,QAAQ,EAAE;AAC5D;AAEA,eAAe,0BACb,KACA,UACA,MACA,MAC4B;CAC5B,MAAM,UAAmC,CAAC;CAC1C,MAAM,UAA8C,CAAC;CAErD,MAAM,UAAU,KACb,MACC,IAAI,OACF,+BACE,IAAI,QAAQ,OAAO,WAAW,QAAQ,aACvC,GAAG,KAAK,mBACX,CACF,CAAC,EACC,MAAK,YAAW,YAAY,SAAS,KAAK,CAAC,CAAC;CAIhD,MAAM,aAAa,IADC,QAAQ,EAAE,uBAAuB,KAAK,CACjC,CAAC,CAAC,iBAAiB,eAAe,IAAI;CAG/D,KAAK,MAAM,OAAO,WAAW,2BAA2B,GACtD,IACE,IAAI,YAAY,KAChB,CAAC,IAAI,QAAQ,SAAS,MAAK,YAAW,IAAI,YAAY,CAAC,CAAC,SAAS,OAAO,CAAC,GAEzE,QAAQ,KAAK;EACX,MAAM,IAAI,YAAY;EACtB,SAAS;CACX,CAAC;CAIL,KAAK,MAAM,aAAa,WAAW,cAAc,GAE/C,IAAI,KAAK,oBAAoB,SAAS,GAAG;EACvC,MAAM,aAAa,UAAU,wBAAwB;EAGrD,IAAI,UAAU,mBAA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OAAO;CACT;CAGF,IAAI,YAAY,MAAM,KAAK,CAAC,KAAK,WAAW,SAAS,GACnD,MAAM,IAAI,GAAG,MACX,IAAI,WACJ,GACE,WAAW,SAAS,IAChB,GAAG,WAAW,KAAI,cAAa,yBAAyB,UAAU,KAAK,CAAC,CAAC,KAAK,IAAI,EAAE;;IAGpF,KACH,wBAAwB,KAAK;EAAE,WAAW;EAAM,gBAAgB;CAAM,CAAC,EAAE;;EAEhF,YAAY,IAAI,EAAE;CAEhB;AAEJ"}
|
|
1
|
+
{"version":3,"file":"generate-types.mjs","names":[],"sources":["../../src/lib/generate-types.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { resolvePackage } from \"@stryke/fs/resolve\";\nimport { getUnique } from \"@stryke/helpers/get-unique\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { findFileName } from \"@stryke/path/file-path-fns\";\nimport { isParentPath } from \"@stryke/path/is-parent-path\";\nimport { replaceExtension, replacePath } from \"@stryke/path/replace\";\nimport { prettyBytes } from \"@stryke/string-format/pretty-bytes\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { DiagnosticCategory, Node, Project, SourceFile } from \"ts-morph\";\nimport { ResolvedConfig } from \"../types/config\";\nimport {\n Context,\n EnvironmentContext,\n ExecutionContext\n} from \"../types/context\";\nimport { TypesResult } from \"../types/plugin\";\nimport { callHook } from \"./hooks\";\nimport { createProgram } from \"./typescript/ts-morph\";\nimport { getTypescriptFileHeader } from \"./utilities/file-header\";\nimport { format } from \"./utilities/format\";\n\ninterface ModuleExportSpecifier {\n name: string;\n alias?: string;\n default?: boolean;\n type?: boolean;\n}\n\ninterface ModuleReference {\n name?: string;\n specifiers?: ModuleExportSpecifier[];\n all?: boolean;\n}\n\ninterface ImportModuleReference extends ModuleReference {\n name: string;\n ambient?: boolean;\n}\n\ninterface ExportModuleReference extends ModuleReference {\n text: string;\n fullText: string;\n comment?: string;\n}\n\ninterface ModuleDeclaration {\n name: string;\n text: string;\n sourceFile: SourceFile;\n comment?: string;\n exports: (ExportModuleReference | string)[];\n imports: ImportModuleReference[];\n}\n\nexport interface TypegenContext {\n context: Context;\n emitted: Map<string, string>;\n modules: ModuleDeclaration[];\n}\n\n/**\n * Formats the generated TypeScript types source code.\n *\n * @param code - The generated TypeScript code.\n * @returns The formatted TypeScript code.\n */\nexport function formatTypes(code = \"\"): string {\n return code.replaceAll(\"#private;\", \"\").replace(/__Ω/g, \"\");\n}\n\nasync function extractModuleDeclarations(\n ctx: TypegenContext,\n filePath: string,\n name: string,\n text: string\n): Promise<ModuleDeclaration> {\n const imports: ImportModuleReference[] = [];\n const exports: (ExportModuleReference | string)[] = [];\n\n const comment = text\n .match(\n new RegExp(\n `\\\\/\\\\*\\\\*(?s:.)*?@module\\\\s+${\n ctx.context.config.framework?.name ?? \"powerlines\"\n }:${name}(?s:.)*?\\\\*\\\\/\\\\s+`\n )\n )\n ?.find(comment => isSetString(comment?.trim()));\n\n // Parse the emitted .d.ts content using an in-memory ts-morph project\n const project = new Project({ useInMemoryFileSystem: true });\n const sourceFile = project.createSourceFile(\"module.d.ts\", text);\n\n // Collect /// <reference types=\"...\" /> directives as ambient dependencies\n for (const ref of sourceFile.getTypeReferenceDirectives()) {\n if (\n ref.getFileName() &&\n !ctx.context.builtins.some(builtin => ref.getFileName().endsWith(builtin))\n ) {\n imports.push({\n name: ref.getFileName(),\n ambient: true\n });\n }\n }\n\n for (const statement of sourceFile.getStatements()) {\n // --- Import declarations ---\n if (Node.isImportDeclaration(statement)) {\n const moduleSpec = statement.getModuleSpecifierValue();\n\n // Namespace import: import * as X from '...'\n if (statement.getNamespaceImport()) {\n imports.push({\n name: moduleSpec,\n specifiers: [\n {\n name: statement.getNamespaceImport()!.getText()\n }\n ],\n all: true\n });\n }\n\n // Named imports: import X from '...' or import { A, B as C } from '...'\n else if (\n statement.getNamedImports().length > 0 ||\n statement.getDefaultImport()\n ) {\n const specifiers: ModuleExportSpecifier[] = [];\n if (statement.getDefaultImport()) {\n specifiers.push({\n name: statement.getDefaultImport()!.getText(),\n default: true,\n type: statement.isTypeOnly()\n });\n }\n\n statement.getNamedImports().forEach(named => {\n specifiers.push({\n name: named.getName(),\n alias: named.getAliasNode()?.getText(),\n type: statement.isTypeOnly()\n });\n });\n\n imports.push({\n name: moduleSpec,\n specifiers\n });\n }\n }\n\n // --- Export declarations ---\n else if (Node.isExportDeclaration(statement)) {\n const moduleSpec = statement.getModuleSpecifierValue();\n if (moduleSpec) {\n // Resolve the module specifier\n let resolvedSpec = moduleSpec;\n if (!ctx.context.builtins.includes(moduleSpec)) {\n if (ctx.emitted.has(moduleSpec)) {\n resolvedSpec = ctx.emitted.get(moduleSpec)!;\n } else {\n const resolvedModule = await ctx.context.resolve(\n moduleSpec,\n filePath\n );\n if (isSetString(resolvedModule?.id)) {\n resolvedSpec = resolvedModule.id;\n }\n }\n }\n\n // Re-export from another module\n const namedExports = statement.getNamedExports();\n if (namedExports.length > 0) {\n exports.push({\n name: resolvedSpec,\n text: statement.getText(),\n fullText: statement.getFullText(),\n specifiers: namedExports.map(named => ({\n name: named.getName(),\n alias: named.getAliasNode()?.getText(),\n type: statement.isTypeOnly()\n })),\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n .trim()\n });\n } else {\n // export * from '...'\n exports.push({\n name: resolvedSpec,\n text: statement.getText(),\n fullText: statement.getFullText(),\n all: true,\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n .trim()\n });\n }\n } else {\n const specifiers = statement.getNamedExports().map(named => ({\n name: named.getName(),\n alias: named.getAliasNode()?.getText(),\n type: statement.isTypeOnly()\n }));\n if (specifiers.length > 0) {\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n specifiers,\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n }\n }\n\n // --- Export assignments (export default ...) ---\n else if (Node.isExportAssignment(statement)) {\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n\n // --- Function declarations (export declare function ...) ---\n else if (\n Node.isFunctionDeclaration(statement) &&\n statement.isExported() &&\n statement.getNameNode()\n ) {\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n specifiers: [\n {\n name: statement.getNameNode()!.getText()\n }\n ],\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n\n // --- Variable statements (export declare const ...) ---\n else if (Node.isVariableStatement(statement) && statement.isExported()) {\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n specifiers: statement\n .getDeclarationList()\n .getDeclarations()\n .filter(\n decl => decl.getNameNode() && Node.isIdentifier(decl.getNameNode())\n )\n .map(decl => ({ name: decl.getNameNode().getText() })),\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n\n // --- Class declarations (export declare class ...) ---\n else if (Node.isClassDeclaration(statement) && statement.isExported()) {\n const nameNode = statement.getNameNode();\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n specifiers: nameNode ? [{ name: nameNode.getText() }] : undefined,\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n\n // --- Interface declarations (export declare interface ...) ---\n else if (Node.isInterfaceDeclaration(statement) && statement.isExported()) {\n const nameNode = statement.getNameNode();\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n specifiers: nameNode ? [{ name: nameNode.getText() }] : undefined,\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n\n // --- Type alias declarations (export declare type ...) ---\n else if (Node.isTypeAliasDeclaration(statement) && statement.isExported()) {\n const nameNode = statement.getNameNode();\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n specifiers: nameNode ? [{ name: nameNode.getText() }] : undefined,\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n\n // --- All other statements (declarations) ---\n else if (\n ctx.context.config.output.sourceMap ||\n !statement.getFullText().includes(\"//# sourceMappingURL=\")\n ) {\n exports.push({\n text: statement.getText(),\n fullText: statement.getFullText(),\n comment: statement\n .getLeadingCommentRanges()\n .filter(\n c =>\n isSetString(c.getText().trim()) &&\n !c.getText().includes(\"@module\")\n )\n .map(c => c.getText().trim())\n .join(\"\\n\")\n });\n }\n }\n\n return {\n name,\n text,\n sourceFile,\n comment,\n imports,\n exports\n };\n}\n\n/**\n * Emits TypeScript declaration types for the provided files using the given TypeScript configuration.\n *\n * @param context - The context containing options and environment paths.\n * @param files - The list of files to generate types for.\n * @returns A promise that resolves to the generated TypeScript declaration types.\n */\nexport async function emitBuiltinTypes<TContext extends Context>(\n context: TContext,\n files: string[]\n): Promise<{ code: string; directives: string[] }> {\n if (files.length === 0) {\n context.debug(\n \"No files provided for TypeScript types generation. Typescript compilation for built-in modules will be skipped.\"\n );\n return { code: \"\", directives: [] };\n }\n\n context.debug(\n `Running the TypeScript compiler for ${\n files.length\n } generated built-in module files.`\n );\n\n const program = createProgram(context, {\n skipAddingFilesFromTsConfig: true,\n compilerOptions: {\n declaration: true,\n declarationMap: false,\n emitDeclarationOnly: true,\n sourceMap: false,\n outDir: replacePath(context.builtinsPath, context.config.cwd),\n composite: false,\n incremental: false,\n tsBuildInfoFile: undefined\n }\n });\n\n program.addSourceFilesAtPaths(files);\n const emitResult = program.emitToMemory({ emitOnlyDtsFiles: true });\n\n const diagnostics = emitResult.getDiagnostics();\n if (diagnostics && diagnostics.length > 0) {\n if (diagnostics.some(d => d.getCategory() === DiagnosticCategory.Error)) {\n throw new Error(\n `The Typescript emit process failed while generating built-in types: \\n ${diagnostics\n .filter(d => d.getCategory() === DiagnosticCategory.Error)\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n } else if (\n diagnostics.some(d => d.getCategory() === DiagnosticCategory.Warning)\n ) {\n context.warn(\n `The Typescript emit process completed with warnings while generating built-in types: \\n ${diagnostics\n .filter(d => d.getCategory() === DiagnosticCategory.Warning)\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n } else {\n context.debug(\n `The Typescript emit process completed with diagnostic messages while generating built-in types: \\n ${diagnostics\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n }\n }\n\n const emittedFiles = emitResult.getFiles();\n context.debug(\n `The TypeScript compiler emitted ${\n emittedFiles.length\n } files for built-in types.`\n );\n\n if (emittedFiles.length === 0) {\n context.warn(\n \"The TypeScript compiler did not emit any files for built-in types. This may indicate an issue with the TypeScript configuration or the provided files.\"\n );\n return { code: \"\", directives: [] };\n }\n\n const ctx = {\n context,\n modules: [] as ModuleDeclaration[],\n emitted: new Map<string, string>()\n };\n\n await Promise.all(\n emittedFiles.map(async emittedFile => {\n const filePath = appendPath(emittedFile.filePath, context.config.cwd);\n if (\n !filePath.endsWith(\".map\") &&\n findFileName(filePath) !== \"tsconfig.tsbuildinfo\" &&\n isParentPath(filePath, context.builtinsPath)\n ) {\n const moduleName = replaceExtension(\n replacePath(\n replacePath(filePath, context.builtinsPath),\n replacePath(context.builtinsPath, context.config.cwd)\n ),\n \"\",\n {\n fullExtension: true\n }\n );\n if (context.builtins.includes(moduleName)) {\n ctx.emitted.set(filePath, moduleName);\n ctx.modules.push(\n await extractModuleDeclarations(\n ctx,\n filePath,\n moduleName,\n emittedFile.text\n )\n );\n }\n }\n })\n );\n\n const commonDeclarations = [] as ExportModuleReference[];\n for (const mod of ctx.modules) {\n for (const importRef of mod.imports.filter(importRef =>\n context.builtins.some(builtin => importRef.name.endsWith(`:${builtin}`))\n )) {\n const moduleRef = ctx.modules.find(moduleRef =>\n importRef.name.endsWith(`:${moduleRef.name}`)\n );\n if (moduleRef) {\n let declaration: ExportModuleReference | undefined;\n for (const decl of moduleRef.exports.filter(decl =>\n isSetObject(decl)\n )) {\n const specifiers = decl.specifiers?.filter(specifier =>\n importRef.specifiers?.some(\n s =>\n (specifier.alias ? specifier.alias : specifier.name) ===\n (s.alias ? s.alias : s.name)\n )\n );\n if (specifiers && specifiers.length > 0) {\n importRef.specifiers = importRef.specifiers?.filter(\n s =>\n !specifiers.some(\n specifier =>\n (specifier.alias ? specifier.alias : specifier.name) ===\n (s.alias ? s.alias : s.name)\n )\n );\n if (\n importRef.specifiers &&\n importRef.specifiers.length === 0 &&\n !importRef.all &&\n !importRef.ambient\n ) {\n mod.imports = mod.imports.filter(\n imp => imp.name !== importRef.name\n );\n }\n\n declaration = decl;\n break;\n }\n }\n\n if (declaration) {\n for (const decl of moduleRef.exports.filter(\n decl =>\n isSetObject(decl) &&\n !decl.specifiers?.some(s =>\n declaration?.specifiers?.some(\n specifier =>\n (specifier.alias ? specifier.alias : specifier.name) ===\n (s.alias ? s.alias : s.name)\n )\n )\n )) {\n const exportModuleRef = decl as ExportModuleReference;\n if (\n (exportModuleRef.specifiers?.some(s => s.alias || s.name) ||\n exportModuleRef.name) &&\n new RegExp(\n `(^|\\\\s|\\\\n|\\\\r\\\\n|\\\\(|\\\\)|<|>|{|}|\\\\[|\\\\]|\\\\!|\\\\?|\\\\.|,|\\\\*|&|:)(${\n exportModuleRef.specifiers\n ?.map(s => `${s.alias ? `${s.alias}|` : \"\"}${s.name}`)\n .join(\"|\") || exportModuleRef.name\n })($|\\\\s|\\\\n|\\\\r\\\\n|\\\\(|\\\\)|<|>|{|}|\\\\[|\\\\]|\\\\!|\\\\?|\\\\.|,|\\\\*|&|:|;)`\n ).test(declaration.text)\n ) {\n commonDeclarations.push(exportModuleRef);\n }\n }\n commonDeclarations.push(declaration);\n }\n }\n }\n }\n\n let code = \"\";\n const directives: string[] = [];\n\n for (const commonDeclaration of commonDeclarations) {\n code += formatTypes(\n `${\n commonDeclaration.comment?.trim()\n ? commonDeclaration.comment.trim()\n : \"\"\n }${commonDeclaration.comment?.trim() ? \"\\n\" : \"\"}${formatTypes(\n commonDeclaration.text\n .replace(/\\s*export\\s*/, \"\")\n .replace(/\\s*declare\\s*interface\\s*/, \"interface \")\n .replace(/\\s*declare\\s*type\\s*/, \"type \")\n )}`\n );\n code += \"\\n\\n\";\n }\n\n for (const mod of ctx.modules) {\n code += mod.comment ? `${mod.comment.trim()}\\n` : \"\";\n code += `declare module \"${context.config.framework?.name ?? \"powerlines\"}:${mod.name}\" { \\n`;\n for (const importRef of mod.imports) {\n if (importRef.ambient) {\n code += directives.push(importRef.name);\n } else if (importRef.all) {\n code += `\\timport * as ${findFileName(importRef.name)} from \"${importRef.name}\";\\n`;\n } else if (importRef.specifiers) {\n const typeOnly = importRef.specifiers.every(s => s.type) ? \" type\" : \"\";\n const specifiers = importRef.specifiers\n .map(s => (s.alias ? `${s.name} as ${s.alias}` : s.name))\n .join(\", \");\n code += `\\timport${typeOnly} { ${specifiers} } from \"${importRef.name}\";\\n`;\n }\n }\n\n if (mod.imports.length > 0) {\n code += \"\\n\";\n }\n\n for (const exportRef of mod.exports.filter(\n e =>\n isString(e) ||\n !e.specifiers ||\n !commonDeclarations.some(\n commonDecl =>\n commonDecl.specifiers &&\n commonDecl.specifiers.some(specifier =>\n e.specifiers?.some(\n s =>\n (s.alias ? s.alias : s.name) ===\n (specifier.alias ? specifier.alias : specifier.name)\n )\n )\n )\n )) {\n if (isSetString(exportRef)) {\n code += `${exportRef}\\n`;\n } else if (exportRef.name) {\n if (exportRef.all) {\n code += `${\n exportRef.comment?.trim() ? exportRef.comment.trim() : \"\"\n }${\n exportRef.comment?.trim() ? \"\\n\" : \"\"\n }export * from \"${exportRef.name}\";\\n`;\n } else if (exportRef.specifiers) {\n if (exportRef.comment?.trim()) {\n code += `${exportRef.comment.trim()}\\n`;\n }\n\n code += `\\texport${\n exportRef.specifiers.every(s => s.type) ? \" type\" : \"\"\n } { ${exportRef.specifiers\n .map(s => (s.alias ? `${s.name} as ${s.alias}` : s.name))\n .join(\", \")} } from \"${exportRef.name}\";\\n`;\n }\n } else {\n code += `${exportRef.comment?.trim() ? exportRef.comment.trim() : \"\"}${\n exportRef.comment?.trim() ? \"\\n\" : \"\"\n }${formatTypes(\n exportRef.text\n .replace(/\\s*export\\s*declare\\s*/, \"export \")\n .replace(/\\s*declare\\s*/, \" \")\n )}\\n`;\n }\n }\n\n mod.exports\n .filter(\n e =>\n !isString(e) &&\n e.specifiers &&\n commonDeclarations.some(\n commonDeclaration =>\n commonDeclaration.specifiers &&\n commonDeclaration.specifiers.some(specifier =>\n e.specifiers?.some(\n s =>\n (s.alias ? s.alias : s.name) ===\n (specifier.alias ? specifier.alias : specifier.name)\n )\n )\n )\n )\n .forEach((e, i, arr) => {\n if (i === 0) {\n code += \"\\nexport { \";\n } else {\n code += \", \";\n }\n\n code += `${\n (e as ExportModuleReference)?.specifiers\n ?.filter(s =>\n commonDeclarations.some(\n commonDeclaration =>\n commonDeclaration.specifiers &&\n commonDeclaration.specifiers.some(\n specifier =>\n (s.alias ? s.alias : s.name) ===\n (specifier.alias ? specifier.alias : specifier.name)\n )\n )\n )\n .map(s => (s.alias ? `${s.name} as ${s.alias}` : s.name))\n .join(\", \") || \"\"\n }`;\n\n if (i === arr.length - 1) {\n code += ` };\\n`;\n }\n });\n\n code += \"}\";\n code += \"\\n\\n\";\n }\n\n code = await format(context, context.typesPath, code);\n\n context.debug(\n `A TypeScript declaration file (size: ${prettyBytes(\n new Blob(toArray(code)).size\n )}) emitted for the built-in modules types.`\n );\n\n return { code, directives };\n}\n\n/**\n * Generate the Powerlines TypeScript declaration file\n *\n * @param context - The execution context for generating the TypeScript declaration file, which provides access to the project configuration, environment, and utility functions for performing the generation. The context is used to manage the state and behavior of the generation process, allowing for hooks to be called at different stages and for environment-specific configurations to be applied.\n * @param env - The environment context to use for generating the TypeScript declaration file\n */\nexport async function handleTypes<\n TResolvedConfig extends ResolvedConfig,\n TSystemContext = unknown\n>(\n context: ExecutionContext<TResolvedConfig, TSystemContext>,\n env: EnvironmentContext<TResolvedConfig, TSystemContext>\n) {\n env.debug(`Preparing the TypeScript definitions for the Powerlines project.`);\n\n if (env.fs.existsSync(env.typesPath)) {\n await env.fs.remove(env.typesPath);\n }\n\n const typescriptPath = await resolvePackage(\"typescript\");\n if (!typescriptPath) {\n throw new Error(\n \"Could not resolve TypeScript package location. Please ensure TypeScript is installed.\"\n );\n }\n\n env.debug(\"Running TypeScript compiler for built-in runtime module files.\");\n\n let { code, directives } = await emitBuiltinTypes(\n env,\n (await env.getBuiltins()).reduce<string[]>((ret, builtin) => {\n const formatted = replacePath(builtin.path, env.config.cwd);\n if (!ret.includes(formatted)) {\n ret.push(formatted);\n }\n\n return ret;\n }, [])\n );\n\n env.debug(\n `Generating TypeScript declaration file ${replacePath(\n env.typesPath,\n context.config.cwd\n )}.`\n );\n\n const merge = async (\n currentResult: string | TypesResult,\n previousResult: string | TypesResult\n ): Promise<string | TypesResult> => {\n if (\n !isSetString(currentResult) &&\n !isSetObject(currentResult) &&\n !isSetString(previousResult) &&\n !isSetObject(previousResult)\n ) {\n return { code, directives };\n }\n\n const previous = (\n await format(\n env,\n env.typesPath,\n isSetString(previousResult)\n ? previousResult\n : isSetObject(previousResult)\n ? previousResult.code\n : \"\"\n )\n )\n .trim()\n .replace(code, \"\")\n .trim();\n const current = (\n await format(\n env,\n env.typesPath,\n isSetString(currentResult)\n ? currentResult\n : isSetObject(currentResult)\n ? currentResult.code\n : \"\"\n )\n )\n .trim()\n .replace(previous, \"\")\n .trim()\n .replace(code, \"\")\n .trim();\n\n return {\n directives: [\n ...(isSetObject(currentResult) && currentResult.directives\n ? currentResult.directives\n : []),\n ...(isSetObject(previousResult) && previousResult.directives\n ? previousResult.directives\n : [])\n ],\n code: await format(\n env,\n env.typesPath,\n `${\n !previous.includes(getTypescriptFileHeader(env)) &&\n !current.includes(getTypescriptFileHeader(env))\n ? `${code}\\n`\n : \"\"\n }${previous}\\n${current}`.trim()\n )\n };\n };\n const asNextParam = (\n previousResult: string | TypesResult | null | undefined\n ) => (isObject(previousResult) ? previousResult.code : previousResult);\n\n let result = await callHook(\n context,\n \"types\",\n {\n environment: env,\n sequential: true,\n order: \"pre\",\n result: \"merge\",\n merge,\n asNextParam\n },\n code\n );\n if (result) {\n if (isSetObject(result)) {\n code = result.code;\n if (Array.isArray(result.directives) && result.directives.length > 0) {\n directives = getUnique([...directives, ...result.directives]).filter(\n Boolean\n );\n }\n } else if (isSetString(result)) {\n code = result;\n }\n }\n\n result = await callHook(\n context,\n \"types\",\n {\n environment: env,\n sequential: true,\n order: \"normal\",\n result: \"merge\",\n merge,\n asNextParam\n },\n code\n );\n if (result) {\n if (isSetObject(result)) {\n code = result.code;\n if (Array.isArray(result.directives) && result.directives.length > 0) {\n directives = getUnique([...directives, ...result.directives]).filter(\n Boolean\n );\n }\n } else if (isSetString(result)) {\n code = result;\n }\n }\n\n result = await callHook(\n context,\n \"types\",\n {\n environment: env,\n sequential: true,\n order: \"post\",\n result: \"merge\",\n merge,\n asNextParam\n },\n code\n );\n if (result) {\n if (isSetObject(result)) {\n code = result.code;\n if (Array.isArray(result.directives) && result.directives.length > 0) {\n directives = getUnique([...directives, ...result.directives]).filter(\n Boolean\n );\n }\n } else if (isSetString(result)) {\n code = result;\n }\n }\n\n if (isSetString(code?.trim()) || directives.length > 0) {\n await env.fs.write(\n env.typesPath,\n `${\n directives.length > 0\n ? `${directives.map(directive => `/// <reference types=\"${directive}\" />`).join(\"\\n\")}\n\n`\n : \"\"\n }${getTypescriptFileHeader(env, { directive: null, prettierIgnore: false })}\n\n${formatTypes(code)}\n`\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwFA,SAAgB,YAAY,OAAO,IAAY;CAC7C,OAAO,KAAK,WAAW,aAAa,EAAE,CAAC,CAAC,QAAQ,QAAQ,EAAE;AAC5D;AAEA,eAAe,0BACb,KACA,UACA,MACA,MAC4B;CAC5B,MAAM,UAAmC,CAAC;CAC1C,MAAM,UAA8C,CAA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ACF;CACA,IAAI,QACF;MAAI,YAAY,MAAM,GAAG;GACvB,OAAO,OAAO;GACd,IAAI,MAAM,QAAQ,OAAO,UAAU,KAAK,OAAO,WAAW,SAAS,GACjE,aAAa,UAAU,CAAC,GAAG,YAAY,GAAG,OAAO,UAAU,CAAC,CAAC,CAAC,OAC5D,OACF;EAEJ,OAAO,IAAI,YAAY,MAAM,GAC3B,OAAO;CACT;CAGF,SAAS,MAAM,SACb,SACA,SACA;EACE,aAAa;EACb,YAAY;EACZ,OAAO;EACP,QAAQ;EACR;EACA;CACF,GACA,IACF;CACA,IAAI,QACF;MAAI,YAAY,MAAM,GAAG;GACvB,OAAO,OAAO;GACd,IAAI,MAAM,QAAQ,OAAO,UAAU,KAAK,OAAO,WAAW,SAAS,GACjE,aAAa,UAAU,CAAC,GAAG,YAAY,GAAG,OAAO,UAAU,CAAC,CAAC,CAAC,OAC5D,OACF;EAEJ,OAAO,IAAI,YAAY,MAAM,GAC3B,OAAO;CACT;CAGF,IAAI,YAAY,MAAM,KAAK,CAAC,KAAK,WAAW,SAAS,GACnD,MAAM,IAAI,GAAG,MACX,IAAI,WACJ,GACE,WAAW,SAAS,IAChB,GAAG,WAAW,KAAI,cAAa,yBAAyB,UAAU,KAAK,CAAC,CAAC,KAAK,IAAI,EAAE;;IAGpF,KACH,wBAAwB,KAAK;EAAE,WAAW;EAAM,gBAAgB;CAAM,CAAC,EAAE;;EAEhF,YAAY,IAAI,EAAE;CAEhB;AAEJ"}
|
package/dist/lib/hooks.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.mjs","names":["defu"],"sources":["../../src/lib/hooks.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { getField } from \"@stryke/helpers/get-field\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isSet } from \"@stryke/type-checks/is-set\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { ArrayValues } from \"@stryke/types/array\";\nimport { AnyFunction } from \"@stryke/types/base\";\nimport chalk from \"chalk\";\nimport { defu } from \"defu\";\nimport {\n addPluginHook,\n colorText,\n isPluginHook,\n isPluginHookField,\n mergeConfig\n} from \"../plugin-utils\";\nimport type {\n CallHookOptions,\n EnvironmentContext,\n ExecutionContext,\n HookListOrders,\n HooksList,\n HooksListItem,\n InferHookParameters,\n InferHookReturnType,\n Plugin,\n PluginContext,\n PluginHookFields,\n ResolvedConfig\n} from \"../types\";\n\n/**\n * Merges the current hook result with the previous results based on their types.\n *\n * @param currentResult - The current hook result to merge with the previous results.\n * @param previousResults - The previous hook results to merge with the current result.\n * @returns The merged result.\n */\nexport function mergeResults<\n T extends Record<string | number | symbol, any> | string\n>(currentResult: T, previousResults: T[]): T[] {\n if (!previousResults || previousResults.length === 0) {\n return [currentResult];\n }\n\n if (isSetString(currentResult)) {\n previousResults = [\n `${isSetString(previousResults[0]) ? previousResults[0] || \"\" : \"\"}\\n${\n isSetString(previousResults[0])\n ? currentResult.replace(previousResults[0], \"\")\n : currentResult\n }`.trim() as T\n ];\n } else if (isObject(currentResult)) {\n previousResults =\n previousResults.length > 0\n ? [defu(currentResult, previousResults[0])]\n : [currentResult];\n }\n\n return previousResults;\n}\n\n/**\n * Merges multiple hook results together, with special handling for string values and object values.\n *\n * @param currentResult - The current hook result to merge with the previous results.\n * @param previousResults - The previous hook results to merge with the current result.\n * @returns The merged result.\n */\nexport function mergeConfigs<T>(currentResult: T, previousResults: T): T {\n if (isString(currentResult)) {\n previousResults =\n `${isString(previousResults) ? previousResults || \"\" : \"\"}\\n${\n currentResult || \"\"\n }`.trim() as T;\n } else if (isObject(currentResult)) {\n previousResults = mergeConfig(currentResult, previousResults ?? {}) as T;\n }\n\n return previousResults;\n}\n\n/**\n * Calls a hook with the given context, options, and arguments.\n *\n * @param context - The context to use when calling the hook.\n * @param key - The hook to call.\n * @param options - Options for calling the hook.\n * @param args - Arguments to pass to the hook.\n * @returns The return value of the hook.\n */\nasync function _callHook<\n TResolvedConfig extends ResolvedConfig,\n TSystemContext,\n TKey extends string\n>(\n context: EnvironmentContext<TResolvedConfig, TSystemContext>,\n key: TKey,\n options: CallHookOptions,\n ...args: InferHookParameters<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >\n): Promise<\n | InferHookReturnType<PluginContext<TResolvedConfig, TSystemContext>, TKey>\n | undefined\n> {\n const hooks = context.selectHooks(key, options);\n if (hooks.length > 0) {\n const logger = context.extendLogger({ category: \"hooks\" });\n const pluginNumberWidth =\n hooks.length >= 10 ? String(hooks.length).length : 1;\n\n logger.debug(\n `🧩 Calling ${hooks.length} ${chalk.bold.cyanBright(\n `${key}${options?.order ? ` (${options.order})` : \"\"}`\n )} plugin hook${hooks.length > 1 ? \"s\" : \"\"}:\\n${hooks\n .map(\n (hook, index) =>\n `${String(index + 1).padStart(\n pluginNumberWidth,\n \"0\"\n )}. ${colorText(hook.plugin.name)}`\n )\n .join(\"\\n\")}`\n );\n\n const invokeHook = async (\n hook: ArrayValues<typeof hooks>,\n hookArgs: InferHookParameters<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >\n ) => {\n return Reflect.apply(hook.handler as AnyFunction, hook.context, hookArgs);\n };\n\n let results = [] as InferHookReturnType<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >[];\n if (options?.sequential === false) {\n results = (await Promise.all(\n hooks.map(async hook => {\n if (!isFunction(hook.handler)) {\n throw new Error(\n `Plugin hook handler for hook \"${key}\" is not a function.`\n );\n }\n\n return invokeHook(hook, [...args]);\n })\n )) as InferHookReturnType<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >[];\n } else {\n for (const hook of hooks) {\n if (!isFunction(hook.handler)) {\n throw new Error(\n `Plugin hook handler for hook \"${key}\" is not a function.`\n );\n }\n\n if (options?.result === \"first\" || options?.asNextParam === false) {\n results.push(\n (await Promise.resolve(\n invokeHook(hook, [...args])\n )) as InferHookReturnType<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >\n );\n if (\n options?.result === \"first\" &&\n isSet(results[results.length - 1])\n ) {\n break;\n }\n } else {\n const sequenceArgs = [...args];\n if (results.length > 0 && sequenceArgs.length > 0) {\n sequenceArgs[0] = isFunction(options.asNextParam)\n ? await Promise.resolve(options.asNextParam(results[0]))\n : results[0];\n }\n\n const result = await Promise.resolve(\n invokeHook(hook, [...sequenceArgs] as InferHookParameters<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >)\n );\n if (result) {\n if (options.result === \"last\") {\n results = [result];\n } else if (options.result === \"merge\" && options.merge) {\n results = [\n results.length > 0 && results[0]\n ? await Promise.resolve(options.merge(result, results[0]))\n : result\n ];\n } else {\n results = mergeResults(result, results);\n }\n }\n }\n }\n }\n\n const definedResults = results.filter(\n (\n result\n ): result is NonNullable<\n InferHookReturnType<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >\n > => isSet(result)\n );\n\n if (definedResults.length > 0) {\n let mergedResult = undefined as\n | InferHookReturnType<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >\n | undefined;\n\n for (const result of definedResults) {\n mergedResult = defu(\n result as Record<string, unknown>,\n mergedResult ?? {}\n ) as InferHookReturnType<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >;\n }\n\n return mergedResult;\n }\n }\n\n return undefined;\n}\n\nexport function extractHooks<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TSystemContext = unknown\n>(\n context: PluginContext<TResolvedConfig, TSystemContext>,\n hooks: Record<\n string,\n HooksList<PluginContext<TResolvedConfig, TSystemContext>>\n >,\n plugin: Plugin<PluginContext<TResolvedConfig, TSystemContext>>,\n key: string,\n parentKey?: string\n): Record<string, HooksList<PluginContext<TResolvedConfig, TSystemContext>>> {\n const combinedKey = parentKey ? `${parentKey}:${key}` : key;\n const pluginField = getField(plugin, combinedKey.replace(/:/g, \".\"));\n if (\n isPluginHookField<PluginContext<TResolvedConfig, TSystemContext>>(\n combinedKey\n ) &&\n isPluginHook(pluginField)\n ) {\n const pluginHook = pluginField;\n if (!isPluginHook(pluginHook)) {\n return hooks;\n }\n\n hooks[combinedKey] ??= {\n preEnforced: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n preOrdered: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n normal: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n postEnforced: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n postOrdered: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[]\n };\n\n if (plugin.enforce) {\n const hookListOrder = `${plugin.enforce}Enforced` as HookListOrders;\n hooks[combinedKey][hookListOrder] ??= [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[];\n\n hooks[combinedKey][hookListOrder] = addPluginHook<\n PluginContext<TResolvedConfig, TSystemContext>,\n PluginHookFields<PluginContext<TResolvedConfig, TSystemContext>>\n >(context, plugin, pluginHook, hooks[combinedKey][hookListOrder]);\n\n return hooks;\n }\n\n if (isFunction(pluginHook) || !pluginHook.order) {\n hooks[combinedKey].normal ??= [];\n\n hooks[combinedKey].normal = addPluginHook<\n PluginContext<TResolvedConfig, TSystemContext>,\n PluginHookFields<PluginContext<TResolvedConfig, TSystemContext>>\n >(context, plugin, pluginHook, hooks[combinedKey].normal);\n\n return hooks;\n }\n\n const hookListOrder = `${pluginHook.order}Ordered` as HookListOrders;\n hooks[combinedKey][hookListOrder] ??= [];\n\n hooks[combinedKey][hookListOrder] = addPluginHook<\n PluginContext<TResolvedConfig, TSystemContext>,\n PluginHookFields<PluginContext<TResolvedConfig, TSystemContext>>\n >(context, plugin, pluginHook, hooks[combinedKey][hookListOrder]);\n\n return hooks;\n } else if (isSetObject(pluginField)) {\n return Object.keys(pluginField)\n .map(pluginKey =>\n extractHooks(context, hooks, plugin, pluginKey, combinedKey)\n )\n .reduce((ret, current) => {\n Object.keys(current).forEach(key => {\n ret[key] ??= {\n preEnforced: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n preOrdered: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n normal: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n postEnforced: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n postOrdered: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[]\n };\n\n [\n \"preEnforced\",\n \"preOrdered\",\n \"normal\",\n \"postEnforced\",\n \"postOrdered\"\n ].forEach(order => {\n if (\n current[key]?.[\n order as keyof HooksList<\n PluginContext<TResolvedConfig, TSystemContext>\n >\n ]\n ) {\n ret[key]![\n order as keyof HooksList<\n PluginContext<TResolvedConfig, TSystemContext>\n >\n ] ??= [];\n ret[key]![\n order as keyof HooksList<\n PluginContext<TResolvedConfig, TSystemContext>\n >\n ] = ret[key]![\n order as keyof HooksList<\n PluginContext<TResolvedConfig, TSystemContext>\n >\n ]!.concat(\n current[key][\n order as keyof HooksList<\n PluginContext<TResolvedConfig, TSystemContext>\n >\n ]!\n );\n }\n });\n });\n\n return ret;\n }, hooks);\n }\n\n return hooks;\n}\n\nexport async function callHook<\n TKey extends string,\n TResolvedConfig extends ResolvedConfig,\n TSystemContext = unknown\n>(\n context: ExecutionContext<TResolvedConfig, TSystemContext>,\n key: TKey,\n options: CallHookOptions & {\n environment?: string | EnvironmentContext<TResolvedConfig, TSystemContext>;\n },\n ...args: InferHookParameters<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >\n) {\n return _callHook<TResolvedConfig, TSystemContext, TKey>(\n isSetObject(options?.environment)\n ? options.environment\n : await context.getEnvironment(options?.environment),\n key,\n { sequential: true, ...options },\n ...args\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAgB,aAEd,eAAkB,iBAA2B;CAC7C,IAAI,CAAC,mBAAmB,gBAAgB,WAAW,GACjD,OAAO,CAAC,aAAa;CAGvB,IAAI,YAAY,aAAa,GAC3B,kBAAkB,CAChB,GAAG,YAAY,gBAAgB,EAAE,IAAI,gBAAgB,MAAM,KAAK,GAAG,IACjE,YAAY,gBAAgB,EAAE,IAC1B,cAAc,QAAQ,gBAAgB,IAAI,EAAE,IAC5C,gBACH,KAAK,CACV;MACK,IAAI,SAAS,aAAa,GAC/B,kBACE,gBAAgB,SAAS,IACrB,CAACA,OAAK,eAAe,gBAAgB,EAAE,CAAC,IACxC,CAAC,aAAa;CAGtB,OAAO;AACT;;;;;;;;AASA,SAAgB,aAAgB,eAAkB,iBAAuB;CACvE,IAAI,SAAS,aAAa,GACxB,kBACE,GAAG,SAAS,eAAe,IAAI,mBAAmB,KAAK,GAAG,IACxD,iBAAiB,KAChB,KAAK;MACL,IAAI,SAAS,aAAa,GAC/B,kBAAkB,YAAY,eAAe,mBAAmB,CAAC,CAAC;CAGpE,OAAO;AACT;;;;;;;;;;AAWA,eAAe,UAKb,SACA,KACA,SACA,GAAG,MAOH;CACA,MAAM,QAAQ,QAAQ,YAAY,KAAK,OAAO;CAC9C,IAAI,MAAM,SAAS,GAAG;EACpB,MAAM,SAAS,QAAQ,aAAa,EAAE,UAAU,QAAQ,CAAC;EACzD,MAAM,oBACJ,MAAM,UAAU,KAAK,OAAO,MAAM,MAAM,CAAC,CAAC,S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AY,MAAM,YAAY,CAAC,MAAM;GAExD,OAAO;EACT;EAEA,MAAM,gBAAgB,GAAG,WAAW,MAAM;EAC1C,MAAM,YAAY,CAAC,mBAAmB,CAAC;EAEvC,MAAM,YAAY,CAAC,iBAAiB,cAGlC,SAAS,QAAQ,YAAY,MAAM,YAAY,CAAC,cAAc;EAEhE,OAAO;CACT,OAAO,IAAI,YAAY,WAAW,GAChC,OAAO,OAAO,KAAK,WAAW,CAAC,CAC5B,KAAI,cACH,aAAa,SAAS,OAAO,QAAQ,WAAW,WAAW,CAC7D,CAAC,CACA,QAAQ,KAAK,YAAY;EACxB,OAAO,KAAK,OAAO,CAAC,CAAC,SAAQ,QAAO;GAClC,IAAI,SAAS;IACX,aAAa,CAAC;IAGd,YAAY,CAAC;IAGb,QAAQ,CAAC;IAGT,cAAc,CAAC;IAGf,aAAa,CAAC;GAGhB;GAEA;IACE;IACA;IACA;IACA;IACA;GACF,CAAC,CAAC,SAAQ,UAAS;IACjB,IACE,QAAQ,IAAI,GACV,QAIF;KACA,IAAI,IAAI,CACN,WAGI,CAAC;KACP,IAAI,IAAI,CACN,SAGE,IAAI,IAAI,CACV,MAGD,CAAE,OACD,QAAQ,IAAI,CACV,MAIJ;IACF;GACF,CAAC;EACH,CAAC;EAED,OAAO;CACT,GAAG,KAAK;CAGZ,OAAO;AACT;AAEA,eAAsB,SAKpB,SACA,KACA,SAGA,GAAG,MAIH;CACA,OAAO,UACL,YAAY,SAAS,WAAW,IAC5B,QAAQ,cACR,MAAM,QAAQ,eAAe,SAAS,WAAW,GACrD,KACA;EAAE,YAAY;EAAM,GAAG;CAAQ,GAC/B,GAAG,IACL;AACF"}
|
|
1
|
+
{"version":3,"file":"hooks.mjs","names":["defu"],"sources":["../../src/lib/hooks.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { getField } from \"@stryke/helpers/get-field\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isSet } from \"@stryke/type-checks/is-set\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { ArrayValues } from \"@stryke/types/array\";\nimport { AnyFunction } from \"@stryke/types/base\";\nimport chalk from \"chalk\";\nimport { defu } from \"defu\";\nimport {\n addPluginHook,\n colorText,\n isPluginHook,\n isPluginHookField,\n mergeConfig\n} from \"../plugin-utils\";\nimport type {\n CallHookOptions,\n EnvironmentContext,\n ExecutionContext,\n HookListOrders,\n HooksList,\n HooksListItem,\n InferHookParameters,\n InferHookReturnType,\n Plugin,\n PluginContext,\n PluginHookFields,\n ResolvedConfig\n} from \"../types\";\n\n/**\n * Merges the current hook result with the previous results based on their types.\n *\n * @param currentResult - The current hook result to merge with the previous results.\n * @param previousResults - The previous hook results to merge with the current result.\n * @returns The merged result.\n */\nexport function mergeResults<\n T extends Record<string | number | symbol, any> | string\n>(currentResult: T, previousResults: T[]): T[] {\n if (!previousResults || previousResults.length === 0) {\n return [currentResult];\n }\n\n if (isSetString(currentResult)) {\n previousResults = [\n `${isSetString(previousResults[0]) ? previousResults[0] || \"\" : \"\"}\\n${\n isSetString(previousResults[0])\n ? currentResult.replace(previousResults[0], \"\")\n : currentResult\n }`.trim() as T\n ];\n } else if (isObject(currentResult)) {\n previousResults =\n previousResults.length > 0\n ? [defu(currentResult, previousResults[0])]\n : [currentResult];\n }\n\n return previousResults;\n}\n\n/**\n * Merges multiple hook results together, with special handling for string values and object values.\n *\n * @param currentResult - The current hook result to merge with the previous results.\n * @param previousResults - The previous hook results to merge with the current result.\n * @returns The merged result.\n */\nexport function mergeConfigs<T>(currentResult: T, previousResults: T): T {\n if (isString(currentResult)) {\n previousResults =\n `${isString(previousResults) ? previousResults || \"\" : \"\"}\\n${\n currentResult || \"\"\n }`.trim() as T;\n } else if (isObject(currentResult)) {\n previousResults = mergeConfig(currentResult, previousResults ?? {}) as T;\n }\n\n return previousResults;\n}\n\n/**\n * Calls a hook with the given context, options, and arguments.\n *\n * @param context - The context to use when calling the hook.\n * @param key - The hook to call.\n * @param options - Options for calling the hook.\n * @param args - Arguments to pass to the hook.\n * @returns The return value of the hook.\n */\nasync function _callHook<\n TResolvedConfig extends ResolvedConfig,\n TSystemContext,\n TKey extends string\n>(\n context: EnvironmentContext<TResolvedConfig, TSystemContext>,\n key: TKey,\n options: CallHookOptions,\n ...args: InferHookParameters<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >\n): Promise<\n | InferHookReturnType<PluginContext<TResolvedConfig, TSystemContext>, TKey>\n | undefined\n> {\n const hooks = context.selectHooks(key, options);\n if (hooks.length > 0) {\n const logger = context.extendLogger({ category: \"hooks\" });\n const pluginNumberWidth =\n hooks.length >= 10 ? String(hooks.length).length : 1;\n\n logger.debug(\n `🧩 Calling ${hooks.length} ${chalk.bold.cyanBright(\n `${key}${options?.order ? ` (${options.order})` : \"\"}`\n )} plugin hook${hooks.length > 1 ? \"s\" : \"\"}:\\n${hooks\n .map(\n (hook, index) =>\n `${String(index + 1).padStart(\n pluginNumberWidth,\n \"0\"\n )}. ${colorText(hook.plugin.name)}`\n )\n .join(\"\\n\")}`\n );\n\n const invokeHook = async (\n hook: ArrayValues<typeof hooks>,\n hookArgs: InferHookParameters<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >\n ) => {\n return Reflect.apply(hook.handler as AnyFunction, hook.context, hookArgs);\n };\n\n let results = [] as InferHookReturnType<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >[];\n if (options?.sequential === false) {\n results = (await Promise.all(\n hooks.map(async hook => {\n if (!isFunction(hook.handler)) {\n throw new Error(\n `Plugin hook handler for hook \"${key}\" is not a function.`\n );\n }\n\n return invokeHook(hook, [...args]);\n })\n )) as InferHookReturnType<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >[];\n } else {\n for (const hook of hooks) {\n if (!isFunction(hook.handler)) {\n throw new Error(\n `Plugin hook handler for hook \"${key}\" is not a function.`\n );\n }\n\n if (options?.result === \"first\" || options?.asNextParam === false) {\n results.push(\n (await Promise.resolve(\n invokeHook(hook, [...args])\n )) as InferHookReturnType<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >\n );\n if (\n options?.result === \"first\" &&\n isSet(results[results.length - 1])\n ) {\n break;\n }\n } else {\n const sequenceArgs = [...args];\n if (results.length > 0 && sequenceArgs.length > 0) {\n sequenceArgs[0] = isFunction(options.asNextParam)\n ? await Promise.resolve(options.asNextParam(results[0]))\n : results[0];\n }\n\n const result = await Promise.resolve(\n invokeHook(hook, [...sequenceArgs] as InferHookParameters<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >)\n );\n if (result) {\n if (options.result === \"last\") {\n results = [result];\n } else if (options.result === \"merge\" && options.merge) {\n results = [\n results.length > 0 && results[0]\n ? await Promise.resolve(options.merge(result, results[0]))\n : result\n ];\n } else {\n results = mergeResults(result, results);\n }\n }\n }\n }\n }\n\n const definedResults = results.filter(\n (\n result\n ): result is NonNullable<\n InferHookReturnType<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >\n > => isSet(result)\n );\n\n if (definedResults.length > 0) {\n let mergedResult = undefined as\n | InferHookReturnType<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >\n | undefined;\n\n for (const result of definedResults) {\n mergedResult = defu(\n result as Record<string, unknown>,\n mergedResult ?? {}\n ) as InferHookReturnType<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >;\n }\n\n return mergedResult;\n }\n }\n\n return undefined;\n}\n\nexport function extractHooks<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TSystemContext = unknown\n>(\n context: PluginContext<TResolvedConfig, TSystemContext>,\n hooks: Record<\n string,\n HooksList<PluginContext<TResolvedConfig, TSystemContext>>\n >,\n plugin: Plugin<PluginContext<TResolvedConfig, TSystemContext>>,\n key: string,\n parentKey?: string\n): Record<string, HooksList<PluginContext<TResolvedConfig, TSystemContext>>> {\n const combinedKey = parentKey ? `${parentKey}:${key}` : key;\n const pluginField = getField(plugin, combinedKey.replace(/:/g, \".\"));\n if (\n isPluginHookField<PluginContext<TResolvedConfig, TSystemContext>>(\n combinedKey\n ) &&\n isPluginHook(pluginField)\n ) {\n const pluginHook = pluginField;\n if (!isPluginHook(pluginHook)) {\n return hooks;\n }\n\n hooks[combinedKey] ??= {\n preEnforced: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n preOrdered: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n normal: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n postEnforced: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n postOrdered: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[]\n };\n\n if (plugin.enforce) {\n const hookListOrder = `${plugin.enforce}Enforced` as HookListOrders;\n hooks[combinedKey][hookListOrder] ??= [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[];\n\n hooks[combinedKey][hookListOrder] = addPluginHook<\n PluginContext<TResolvedConfig, TSystemContext>,\n PluginHookFields<PluginContext<TResolvedConfig, TSystemContext>>\n >(context, plugin, pluginHook, hooks[combinedKey][hookListOrder]);\n\n return hooks;\n }\n\n if (isFunction(pluginHook) || !pluginHook.order) {\n hooks[combinedKey].normal ??= [];\n\n hooks[combinedKey].normal = addPluginHook<\n PluginContext<TResolvedConfig, TSystemContext>,\n PluginHookFields<PluginContext<TResolvedConfig, TSystemContext>>\n >(context, plugin, pluginHook, hooks[combinedKey].normal);\n\n return hooks;\n }\n\n const hookListOrder = `${pluginHook.order}Ordered` as HookListOrders;\n hooks[combinedKey][hookListOrder] ??= [];\n\n hooks[combinedKey][hookListOrder] = addPluginHook<\n PluginContext<TResolvedConfig, TSystemContext>,\n PluginHookFields<PluginContext<TResolvedConfig, TSystemContext>>\n >(context, plugin, pluginHook, hooks[combinedKey][hookListOrder]);\n\n return hooks;\n } else if (isSetObject(pluginField)) {\n return Object.keys(pluginField)\n .map(pluginKey =>\n extractHooks(context, hooks, plugin, pluginKey, combinedKey)\n )\n .reduce((ret, current) => {\n Object.keys(current).forEach(key => {\n ret[key] ??= {\n preEnforced: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n preOrdered: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n normal: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n postEnforced: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[],\n postOrdered: [] as HooksListItem<\n PluginContext<TResolvedConfig, TSystemContext>\n >[]\n };\n\n [\n \"preEnforced\",\n \"preOrdered\",\n \"normal\",\n \"postEnforced\",\n \"postOrdered\"\n ].forEach(order => {\n if (\n current[key]?.[\n order as keyof HooksList<\n PluginContext<TResolvedConfig, TSystemContext>\n >\n ]\n ) {\n ret[key]![\n order as keyof HooksList<\n PluginContext<TResolvedConfig, TSystemContext>\n >\n ] ??= [];\n ret[key]![\n order as keyof HooksList<\n PluginContext<TResolvedConfig, TSystemContext>\n >\n ] = ret[key]![\n order as keyof HooksList<\n PluginContext<TResolvedConfig, TSystemContext>\n >\n ]!.concat(\n current[key][\n order as keyof HooksList<\n PluginContext<TResolvedConfig, TSystemContext>\n >\n ]!\n );\n }\n });\n });\n\n return ret;\n }, hooks);\n }\n\n return hooks;\n}\n\nexport async function callHook<\n TKey extends string,\n TResolvedConfig extends ResolvedConfig,\n TSystemContext = unknown\n>(\n context: ExecutionContext<TResolvedConfig, TSystemContext>,\n key: TKey,\n options: CallHookOptions & {\n environment?: string | EnvironmentContext<TResolvedConfig, TSystemContext>;\n },\n ...args: InferHookParameters<\n PluginContext<TResolvedConfig, TSystemContext>,\n TKey\n >\n) {\n return _callHook<TResolvedConfig, TSystemContext, TKey>(\n isSetObject(options?.environment)\n ? options.environment\n : await context.getEnvironment(options?.environment),\n key,\n { sequential: true, ...options },\n ...args\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAgB,aAEd,eAAkB,iBAA2B;CAC7C,IAAI,CAAC,mBAAmB,gBAAgB,WAAW,GACjD,OAAO,CAAC,aAAa;CAGvB,IAAI,YAAY,aAAa,GAC3B,kBAAkB,CAChB,GAAG,YAAY,gBAAgB,EAAE,IAAI,gBAAgB,MAAM,KAAK,GAAG,IACjE,YAAY,gBAAgB,EAAE,IAC1B,cAAc,QAAQ,gBAAgB,IAAI,EAAE,IAC5C,gBACH,KAAK,CACV;MACK,IAAI,SAAS,aAAa,GAC/B,kBACE,gBAAgB,SAAS,IACrB,CAACA,OAAK,eAAe,gBAAgB,EAAE,CAAC,IACxC,CAAC,aAAa;CAGtB,OAAO;AACT;;;;;;;;AASA,SAAgB,aAAgB,eAAkB,iBAAuB;CACvE,IAAI,SAAS,aAAa,GACxB,kBACE,GAAG,SAAS,eAAe,IAAI,mBAAmB,KAAK,GAAG,IACxD,iBAAiB,KAChB,KAAK;MACL,IAAI,SAAS,aAAa,GAC/B,kBAAkB,YAAY,eAAe,mBAAmB,CAAC,CAAC;CAGpE,OAAO;AACT;;;;;;;;;;AAWA,eAAe,UAKb,SACA,KACA,SACA,GAAG,MAOH;CACA,MAAM,QAAQ,QAAQ,YAAY,KAAK,OAAO;CAC9C,IAAI,MAAM,SAAS,GAAG;EACpB,MAAM,SAAS,QAAQ,aAAa,EAAE,UAAU,QAAQ,CAAC;EACzD,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W,CAAC;GAE/B,MAAM,YAAY,CAAC,SAAS,cAG1B,SAAS,QAAQ,YAAY,MAAM,YAAY,CAAC,MAAM;GAExD,OAAO;EACT;EAEA,MAAM,gBAAgB,GAAG,WAAW,MAAM;EAC1C,MAAM,YAAY,CAAC,mBAAmB,CAAC;EAEvC,MAAM,YAAY,CAAC,iBAAiB,cAGlC,SAAS,QAAQ,YAAY,MAAM,YAAY,CAAC,cAAc;EAEhE,OAAO;CACT,OAAO,IAAI,YAAY,WAAW,GAChC,OAAO,OAAO,KAAK,WAAW,CAAC,CAC5B,KAAI,cACH,aAAa,SAAS,OAAO,QAAQ,WAAW,WAAW,CAC7D,CAAC,CACA,QAAQ,KAAK,YAAY;EACxB,OAAO,KAAK,OAAO,CAAC,CAAC,SAAQ,QAAO;GAClC,IAAI,SAAS;IACX,aAAa,CAAC;IAGd,YAAY,CAAC;IAGb,QAAQ,CAAC;IAGT,cAAc,CAAC;IAGf,aAAa,CAAC;GAGhB;GAEA;IACE;IACA;IACA;IACA;IACA;GACF,CAAC,CAAC,SAAQ,UAAS;IACjB,IACE,QAAQ,IAAI,GACV,QAIF;KACA,IAAI,IAAI,CACN,WAGI,CAAC;KACP,IAAI,IAAI,CACN,SAGE,IAAI,IAAI,CACV,MAGD,CAAE,OACD,QAAQ,IAAI,CACV,MAIJ;IACF;GACF,CAAC;EACH,CAAC;EAED,OAAO;CACT,GAAG,KAAK;CAGZ,OAAO;AACT;AAEA,eAAsB,SAKpB,SACA,KACA,SAGA,GAAG,MAIH;CACA,OAAO,UACL,YAAY,SAAS,WAAW,IAC5B,QAAQ,cACR,MAAM,QAAQ,eAAe,SAAS,WAAW,GACrD,KACA;EAAE,YAAY;EAAM,GAAG;CAAQ,GAC/B,GAAG,IACL;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"install-dependencies.mjs","names":[],"sources":["../../src/lib/install-dependencies.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n
|
|
1
|
+
{"version":3,"file":"install-dependencies.mjs","names":[],"sources":["../../src/lib/install-dependencies.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { getPackageName } from \"@stryke/string-format/package\";\nimport { installPackage } from \"../plugin-utils/install\";\nimport type { Context } from \"../types/context\";\n\n/**\n * Install missing project dependencies.\n *\n * @param context - The build context.\n */\nexport async function installDependencies<TContext extends Context = Context>(\n context: TContext\n): Promise<void> {\n context.debug(`Checking and installing missing project dependencies.`);\n\n context.dependencies ??= {};\n context.devDependencies ??= {};\n\n if (\n Object.keys(context.dependencies).length === 0 &&\n Object.keys(context.devDependencies).length === 0\n ) {\n context.debug(\n `No dependencies or devDependencies to install. Skipping installation step.`\n );\n return;\n }\n\n context.debug(\n `The following packages are required: \\nDependencies: \\n${Object.entries(\n context.dependencies\n )\n .map(([name, version]) => `- ${name}@${String(version)}`)\n .join(\" \\n\")}\\n\\nDevDependencies: \\n${Object.entries(\n context.devDependencies\n )\n .map(([name, version]) => `- ${name}@${String(version)}`)\n .join(\" \\n\")}`\n );\n\n await Promise.all([\n Promise.all(\n Object.entries(context.dependencies).map(async ([name, version]) =>\n installPackage(\n context,\n `${getPackageName(name)}@${String(version)}`,\n false\n )\n )\n ),\n Promise.all(\n Object.entries(context.devDependencies).map(async ([name, version]) =>\n installPackage(\n context,\n `${getPackageName(name)}@${String(version)}`,\n true\n )\n )\n )\n ]);\n}\n"],"mappings":";;;;;;;;;AA2BA,eAAsB,oBACpB,SACe;CACf,QAAQ,MAAM,uDAAuD;CAErE,QAAQ,iBAAiB,CAAC;CAC1B,QAAQ,oBAAoB,CAAC;CAE7B,IACE,OAAO,KAAK,QAAQ,YAAY,CAAC,CAAC,WAAW,KAC7C,OAAO,KAAK,QAAQ,eAAe,CAAC,CAAC,WAAW,GAChD;EACA,QAAQ,MACN,4EACF;EACA;CACF;CAEA,QAAQ,MACN,0DAA0D,OAAO,QAC/D,QAAQ,YACV,CAAC,CACE,KAAK,CAAC,MAAM,aAAa,KAAK,KAAK,GAAG,OAAO,OAAO,GAAG,CAAC,CACxD,KAAK,KAAK,EAAE,yBAAyB,OAAO,QAC7C,QAAQ,eACV,CAAC,CACE,KAAK,CAAC,MAAM,aAAa,KAAK,KAAK,GAAG,OAAO,OAAO,GAAG,CAAC,CACxD,KAAK,KAAK,GACf;CAEA,MAAM,QAAQ,IAAI,CAChB,QAAQ,IACN,OAAO,QAAQ,QAAQ,YAAY,CAAC,CAAC,IAAI,OAAO,CAAC,MAAM,aACrD,eACE,SACA,GAAG,eAAe,IAAI,EAAE,GAAG,OAAO,OAAO,KACzC,KACF,CACF,CACF,GACA,QAAQ,IACN,OAAO,QAAQ,QAAQ,eAAe,CAAC,CAAC,IAAI,OAAO,CAAC,MAAM,aACxD,eACE,SACA,GAAG,eAAe,IAAI,EAAE,GAAG,OAAO,OAAO,KACzC,IACF,CACF,CACF,CACF,CAAC;AACH"}
|
package/dist/lib/meta.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"meta.mjs","names":[],"sources":["../../src/lib/meta.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n
|
|
1
|
+
{"version":3,"file":"meta.mjs","names":[],"sources":["../../src/lib/meta.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { removeFile } from \"@stryke/fs/remove-file\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { replacePath } from \"@stryke/path/replace\";\nimport { kebabCase } from \"@stryke/string-format/kebab-case\";\nimport { ROOT_HASH_LENGTH } from \"../constants\";\nimport type { Context, MetaInfo } from \"../types\";\n\nexport interface CreateContextOptions {\n name?: string;\n}\n\n/**\n * Generates a prefixed project root hash object.\n *\n * @remarks\n * This function returns a string where the project root hash is prefixed with the project name plus a hyphen. If the total length of this string combination exceeds 45 characters, it will truncate the hash.\n *\n * @param name - The name of the project.\n * @param rootHash - The hash of the project root.\n * @returns An object containing the name and project root hash.\n */\nexport function getPrefixedRootHash(name: string, rootHash: string): string {\n const combined = `${kebabCase(name)}_${rootHash}`;\n\n return combined.length > ROOT_HASH_LENGTH\n ? combined.slice(0, ROOT_HASH_LENGTH)\n : combined;\n}\n\n/**\n * Retrieves the persisted meta information from the context's data path.\n *\n * @param context - The build context.\n * @returns A promise that resolves to the persisted meta information, or undefined if not found.\n */\nexport async function getPersistedMeta(\n context: Context\n): Promise<MetaInfo | undefined> {\n const metaFilePath = joinPaths(context.dataPath, \"meta.json\");\n if (existsSync(metaFilePath)) {\n try {\n return await readJsonFile<MetaInfo>(metaFilePath);\n } catch {\n context.warn(\n `Failed to read meta file at ${metaFilePath}. It may be corrupted.`\n );\n await removeFile(metaFilePath);\n\n context.persistedMeta = undefined;\n }\n }\n\n return undefined;\n}\n\n/**\n * Writes the meta file for the context.\n *\n * @param context - The context to write the meta file for.\n * @returns A promise that resolves when the meta file has been written.\n */\nexport async function writeMetaFile(context: Context): Promise<void> {\n const metaFilePath = joinPaths(context.dataPath, \"meta.json\");\n\n context.debug(\n `Writing runtime metadata to ${replacePath(\n metaFilePath,\n context.config.cwd\n )}`\n );\n\n await context.fs.write(metaFilePath, JSON.stringify(context.meta, null, 2));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,oBAAoB,MAAc,UAA0B;CAC1E,MAAM,WAAW,GAAG,UAAU,IAAI,EAAE,GAAG;CAEvC,OAAO,SAAS,cACZ,SAAS,MAAM,KAAmB,IAClC;AACN;;;;;;;AAQA,eAAsB,iBACpB,SAC+B;CAC/B,MAAM,eAAe,UAAU,QAAQ,UAAU,WAAW;CAC5D,IAAI,WAAW,YAAY,GACzB,IAAI;EACF,OAAO,MAAM,aAAuB,YAAY;CAClD,QAAQ;EACN,QAAQ,KACN,+BAA+B,aAAa,uBAC9C;EACA,MAAM,WAAW,YAAY;EAE7B,QAAQ,gBAAgB;CAC1B;AAIJ;;;;;;;AAQA,eAAsB,cAAc,SAAiC;CACnE,MAAM,eAAe,UAAU,QAAQ,UAAU,WAAW;CAE5D,QAAQ,MACN,+BAA+B,YAC7B,cACA,QAAQ,OAAO,GACjB,GACF;CAEA,MAAM,QAAQ,GAAG,MAAM,cAAc,KAAK,UAAU,QAAQ,MAAM,MAAM,CAAC,CAAC;AAC5E"}
|
package/dist/lib/plugins.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugins.mjs","names":[],"sources":["../../src/lib/plugins.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { install } from \"@stryke/fs/install\";\nimport { isPackageExists } from \"@stryke/fs/package-fns\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { isError } from \"@stryke/type-checks/is-error\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isNumber } from \"@stryke/type-checks/is-number\";\nimport { isPromiseLike } from \"@stryke/type-checks/is-promise\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { MaybePromise } from \"@stryke/types/base\";\nimport chalk from \"chalk\";\nimport {\n findInvalidPluginConfig,\n isDuplicate,\n isPlugin,\n isPluginConfig,\n isPluginConfigObject,\n isPluginConfigTuple\n} from \"../plugin-utils\";\nimport type {\n EnvironmentContext,\n ExecutionContext,\n Plugin,\n PluginConfig,\n PluginConfigTuple,\n PluginContext,\n PluginFactory,\n ResolvedConfig\n} from \"../types\";\n\n/**\n * Resolve a plugin module based on the provided plugin path. This function checks if the plugin package is installed, attempts to import the plugin module, and handles various error cases such as missing packages or invalid module exports. It supports both direct plugin exports and plugins exported from a \"plugin\" subdirectory within the package.\n *\n * @param context - The execution context in which the plugin will be initialized. This context provides access to configuration, logging, and other utilities that may be needed during plugin initialization.\n * @param pluginPath - The path to the plugin module. This can be a package name, a scoped package name, or a path to a local module.\n * @returns A promise that resolves to the plugin module, which can be a plugin instance, a factory function that returns a plugin, or an array of plugins.\n */\nexport async function resolvePlugin<\n TResolvedConfig extends ResolvedConfig,\n TSystemContext,\n TContext extends\n | EnvironmentContext<TResolvedConfig, TSystemContext>\n | ExecutionContext<TResolvedConfig, TSystemContext> =\n | EnvironmentContext<TResolvedConfig, TSystemContext>\n | ExecutionContext<TResolvedConfig, TSystemContext>,\n TPluginContext extends PluginContext<TResolvedConfig, TSystemContext> =\n PluginContext<TResolvedConfig, TSystemContext>\n>(\n context: TContext,\n pluginPath: string\n): Promise<\n | Plugin<TPluginContext>\n | Plugin<TPluginContext>[]\n | ((\n options?: any\n ) => MaybePromise<Plugin<TPluginContext> | Plugin<TPluginContext>[]>)\n> {\n if (\n pluginPath.startsWith(\"@\") &&\n pluginPath.split(\"/\").filter(Boolean).length > 2\n ) {\n const splits = pluginPath.split(\"/\").filter(Boolean);\n pluginPath = `${splits[0]}/${splits[1]}`;\n }\n\n const isInstalled = isPackageExists(pluginPath, {\n paths: [context.config.cwd, context.config.root]\n });\n if (!isInstalled && context.config.autoInstall) {\n context.warn(\n `The plugin package \"${\n pluginPath\n }\" is not installed. It will be installed automatically.`\n );\n\n const result = await install(pluginPath, {\n cwd: context.config.root\n });\n if (isNumber(result.exitCode) && result.exitCode > 0) {\n context.error(result.stderr);\n\n throw new Error(\n `An error occurred while installing the build plugin package \"${\n pluginPath\n }\" `\n );\n }\n }\n\n try {\n // First check if the package has a \"plugin\" subdirectory - @scope/package/plugin\n const module = await context.resolver.plugin.import<{\n plugin?:\n | Plugin<TPluginContext>\n | ((options?: any) => MaybePromise<Plugin<TPluginContext>>);\n default?:\n | Plugin<TPluginContext>\n | ((options?: any) => MaybePromise<Plugin<TPluginContext>>);\n }>(context.resolver.plugin.esmResolve(joinPaths(pluginPath, \"plugin\")));\n\n const result = module.plugin ?? module.default;\n if (!result) {\n throw new Error(\n `The plugin package \"${pluginPath}\" does not export a valid module.`\n );\n }\n\n return result;\n } catch (error) {\n try {\n const module = await context.resolver.plugin.import<{\n plugin?:\n | Plugin<TPluginContext>\n | ((options?: any) => MaybePromise<Plugin<TPluginContext>>);\n default?:\n | Plugin<TPluginContext>\n | ((options?: any) => MaybePromise<Plugin<TPluginContext>>);\n }>(context.resolver.plugin.esmResolve(pluginPath));\n\n const result = module.plugin ?? module.default;\n if (!result) {\n throw new Error(\n `The plugin package \"${pluginPath}\" does not export a valid module.`\n );\n }\n\n return result;\n } catch {\n if (!isInstalled) {\n throw new Error(\n `The plugin package \"${\n pluginPath\n }\" is not installed. Please install the package using the command: \"npm install ${\n pluginPath\n } --save-dev\"`\n );\n } else {\n throw new Error(\n `An error occurred while importing the build plugin package \"${\n pluginPath\n }\":\n${isError(error) ? error.message : String(error)}\n\nNote: Please ensure the plugin package's default export is a class that extends \\`Plugin\\` with a constructor that excepts a single arguments of type \\`PluginOptions\\`.`\n );\n }\n }\n }\n}\n\n/**\n * Initialize a plugin based on the provided plugin configuration. This function handles various forms of plugin configurations, including direct plugin instances, factory functions, string paths to plugins, and arrays of plugins or plugin configurations. It validates the plugin configuration, resolves any plugin paths, and returns an array of initialized plugins.\n *\n * @param context - The execution context in which the plugin will be initialized. This context provides access to configuration, logging, and other utilities that may be needed during plugin initialization.\n * @param config - The plugin configuration, which can be in various forms such as a direct plugin instance, a string path to a plugin, a factory function that returns a plugin, or an array of plugins or plugin configurations. This configuration will be processed and validated to initialize the appropriate plugins.\n * @returns A promise that resolves to an array of initialized plugins based on the provided configuration. If the configuration is invalid, an error will be thrown with details about the issue.\n */\nexport async function initPlugin<\n TResolvedConfig extends ResolvedConfig,\n TSystemContext,\n TContext extends\n | EnvironmentContext<TResolvedConfig, TSystemContext>\n | ExecutionContext<TResolvedConfig, TSystemContext> =\n | EnvironmentContext<TResolvedConfig, TSystemContext>\n | ExecutionContext<TResolvedConfig, TSystemContext>,\n TPluginContext extends PluginContext<TResolvedConfig, TSystemContext> =\n PluginContext<TResolvedConfig, TSystemContext>\n>(\n context: TContext,\n config: PluginConfig<TPluginContext>,\n options: ResolvePluginsOptions = {}\n): Promise<Plugin<TPluginContext>[] | null> {\n const { skipLogging = false } = options;\n\n let awaited = config;\n if (isPromiseLike(config)) {\n awaited = (await Promise.resolve(\n config as Promise<any>\n )) as PluginConfig<TPluginContext>;\n }\n\n if (!isPluginConfig<TPluginContext>(awaited)) {\n const invalid = findInvalidPluginConfig(awaited);\n\n throw new Error(\n `Invalid ${\n invalid && invalid.length > 1 ? \"plugins\" : \"plugin\"\n } specified in the configuration - ${\n invalid && invalid.length > 0\n ? JSON.stringify(awaited)\n : invalid?.join(\"\\n\\n\")\n } \\n\\nPlease ensure the value is one of the following: \\n - an instance of \\`Plugin\\` \\n - a plugin name \\n - an object with the \\`plugin\\` and \\`options\\` properties \\n - a tuple array with the plugin and options \\n - a factory function that returns a plugin or array of plugins \\n - an array of plugins or plugin configurations`\n );\n }\n\n let plugins!: Plugin<TPluginContext>[];\n if (isPlugin<TPluginContext>(awaited)) {\n plugins = [awaited];\n } else if (isFunction(awaited)) {\n plugins = toArray(await Promise.resolve(awaited()));\n } else if (isString(awaited)) {\n const resolved = await resolvePlugin<\n TResolvedConfig,\n TSystemContext,\n TContext\n >(context, awaited);\n if (isFunction(resolved)) {\n plugins = toArray(await Promise.resolve(resolved()));\n } else {\n plugins = toArray(resolved);\n }\n } else if (\n Array.isArray(awaited) &&\n (awaited as TPluginContext[]).every(isPlugin<TPluginContext>)\n ) {\n plugins = awaited as Plugin<TPluginContext>[];\n } else if (\n Array.isArray(awaited) &&\n (awaited as PluginConfig<TPluginContext>[]).every(\n isPluginConfig<TPluginContext>\n )\n ) {\n plugins = [];\n for (const pluginConfig of awaited as PluginConfig<TPluginContext>[]) {\n const initialized = await initPlugin<\n TResolvedConfig,\n TSystemContext,\n TContext,\n TPluginContext\n >(context, pluginConfig);\n if (initialized) {\n plugins.push(...initialized);\n }\n }\n } else if (\n isPluginConfigTuple<TPluginContext>(awaited) ||\n isPluginConfigObject<TPluginContext>(awaited)\n ) {\n let pluginConfig!:\n | string\n | PluginFactory<TPluginContext>\n | Plugin<TPluginContext>;\n let pluginOptions: any;\n\n if (isPluginConfigTuple<TPluginContext>(awaited)) {\n pluginConfig = awaited[0] as Plugin<TPluginContext>;\n pluginOptions =\n (awaited as PluginConfigTuple)?.length === 2 ? awaited[1] : undefined;\n } else {\n pluginConfig = awaited.plugin as Plugin<TPluginContext>;\n pluginOptions = awaited.options;\n }\n\n if (isSetString(pluginConfig)) {\n const resolved = await resolvePlugin<\n TResolvedConfig,\n TSystemContext,\n TContext,\n TPluginContext\n >(context, pluginConfig);\n if (isFunction(resolved)) {\n plugins = toArray(\n await Promise.resolve(\n pluginOptions ? resolved(pluginOptions) : resolved()\n )\n );\n } else {\n plugins = toArray(resolved);\n }\n } else if (isFunction(pluginConfig)) {\n plugins = toArray(await Promise.resolve(pluginConfig(pluginOptions)));\n } else if (\n Array.isArray(pluginConfig) &&\n pluginConfig.every(isPlugin<TPluginContext>)\n ) {\n plugins = pluginConfig;\n } else if (isPlugin<TPluginContext>(pluginConfig)) {\n plugins = toArray(pluginConfig);\n }\n }\n\n if (!plugins) {\n throw new Error(\n `The plugin configuration ${JSON.stringify(awaited)} is invalid. This configuration must point to a valid Powerlines plugin module.`\n );\n }\n\n if (plugins.length > 0 && !plugins.every(isPlugin<TPluginContext>)) {\n throw new Error(\n `The plugin option ${JSON.stringify(plugins)} does not export a valid module. This configuration must point to a valid Powerlines plugin module.`\n );\n }\n\n const result = [] as Plugin<TPluginContext>[];\n for (const plugin of plugins) {\n if (isDuplicate<TPluginContext>(plugin, context.plugins)) {\n if (!skipLogging) {\n context.trace({\n meta: {\n category: \"plugins\"\n },\n message: `Duplicate ${chalk.bold.cyanBright(\n plugin.name\n )} plugin dependency detected - Skipping initialization.`\n });\n }\n } else {\n result.push(plugin);\n\n if (!skipLogging) {\n context.trace({\n meta: {\n category: \"plugins\"\n },\n message: `Initializing the ${chalk.bold.cyanBright(plugin.name)} plugin...`\n });\n }\n }\n }\n\n return result;\n}\n\nexport interface ResolvePluginsOptions {\n /**\n * If true, the plugin resolution process will skip logging messages about the plugin initialization. This can be useful in scenarios where you want to suppress plugin-related logs, such as when running in a non-interactive environment or when you want to reduce log verbosity. By default, this option is false, and plugin initialization messages will be logged using the context's logger.\n */\n skipLogging?: boolean;\n}\n\n/**\n * Initialize a plugin based on the provided plugin configuration. This function handles various forms of plugin configurations, including direct plugin instances, plugin names, factory functions, and arrays of plugins. It validates the configuration, resolves plugin modules if necessary, and returns an array of initialized plugins ready to be added to the execution context.\n *\n * @param context - The execution context in which the plugin will be initialized. This context provides access to configuration, logging, and other utilities that may be needed during plugin initialization.\n * @param config - The plugin configuration, which can be in various forms such as a plugin instance, a plugin name string, a factory function that returns a plugin or an array of plugins, or an array of plugin configurations. The function will handle the resolution and initialization of the plugin(s) based on the provided configuration.\n * @returns A promise that resolves to an array of initialized plugins that can be added to the execution context, or null if the configuration is invalid or results in no plugins being initialized.\n */\nexport async function resolvePlugins<\n TResolvedConfig extends ResolvedConfig,\n TSystemContext,\n TContext extends\n | EnvironmentContext<TResolvedConfig, TSystemContext>\n | ExecutionContext<TResolvedConfig, TSystemContext> =\n | EnvironmentContext<TResolvedConfig, TSystemContext>\n | ExecutionContext<TResolvedConfig, TSystemContext>,\n TPluginContext extends PluginContext<TResolvedConfig, TSystemContext> =\n PluginContext<TResolvedConfig, TSystemContext>\n>(\n context: TContext,\n config: PluginConfig<TPluginContext>,\n options: ResolvePluginsOptions = {}\n) {\n const { skipLogging = false } = options;\n\n const plugins = [] as Plugin<TPluginContext>[];\n if (config) {\n const result = await initPlugin<\n TResolvedConfig,\n TSystemContext,\n TContext,\n TPluginContext\n >(context, config);\n if (result) {\n for (const plugin of result) {\n if (!skipLogging) {\n context.trace({\n meta: {\n category: \"plugins\"\n },\n message: `Successfully initialized the ${chalk.bold.cyanBright(\n plugin.name\n )} plugin`\n });\n }\n\n plugins.push(plugin);\n }\n }\n }\n\n return plugins;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,cAWpB,SACA,YAOA;CACA,IACE,WAAW,WAAW,GAAG,KACzB,WAAW,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,SAAS,GAC/C;EACA,MAAM,SAAS,WAAW,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;EACnD,aAAa,GAAG,OAAO,GAAG,GAAG,OAAO;CACtC;CAEA,MAAM,cAAc,gBAAgB,YAAY,EAC9C,OAAO,CAAC,QAAQ,OAAO,KAAK,QAAQ,OAAO,IAAI,EACjD,CAAC;CACD,IAAI,CAAC,eAAe,QAAQ,O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QAAQ,YAAY,KAC1B,aAAa,MAAM,QAAwB,GAE3C,UAAU;OACL,IAAI,SAAyB,YAAY,GAC9C,UAAU,QAAQ,YAAY;CAElC;CAEA,IAAI,CAAC,SACH,MAAM,IAAI,MACR,4BAA4B,KAAK,UAAU,OAAO,EAAE,gFACtD;CAGF,IAAI,QAAQ,SAAS,KAAK,CAAC,QAAQ,MAAM,QAAwB,GAC/D,MAAM,IAAI,MACR,qBAAqB,KAAK,UAAU,OAAO,EAAE,oGAC/C;CAGF,MAAM,SAAS,CAAC;CAChB,KAAK,MAAM,UAAU,SACnB,IAAI,YAA4B,QAAQ,QAAQ,OAAO,GACrD;MAAI,CAAC,aACH,QAAQ,MAAM;GACZ,MAAM,EACJ,UAAU,UACZ;GACA,SAAS,aAAa,MAAM,KAAK,WAC/B,OAAO,IACT,EAAE;EACJ,CAAC;CACH,OACK;EACL,OAAO,KAAK,MAAM;EAElB,IAAI,CAAC,aACH,QAAQ,MAAM;GACZ,MAAM,EACJ,UAAU,UACZ;GACA,SAAS,oBAAoB,MAAM,KAAK,WAAW,OAAO,IAAI,EAAE;EAClE,CAAC;CAEL;CAGF,OAAO;AACT;;;;;;;;AAgBA,eAAsB,eAWpB,SACA,QACA,UAAiC,CAAC,GAClC;CACA,MAAM,EAAE,cAAc,UAAU;CAEhC,MAAM,UAAU,CAAC;CACjB,IAAI,QAAQ;EACV,MAAM,SAAS,MAAM,WAKnB,SAAS,MAAM;EACjB,IAAI,QACF,KAAK,MAAM,UAAU,QAAQ;GAC3B,IAAI,CAAC,aACH,QAAQ,MAAM;IACZ,MAAM,EACJ,UAAU,UACZ;IACA,SAAS,gCAAgC,MAAM,KAAK,WAClD,OAAO,IACT,EAAE;GACJ,CAAC;GAGH,QAAQ,KAAK,MAAM;EACrB;CAEJ;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"plugins.mjs","names":[],"sources":["../../src/lib/plugins.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { install } from \"@stryke/fs/install\";\nimport { isPackageExists } from \"@stryke/fs/package-fns\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { isError } from \"@stryke/type-checks/is-error\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isNumber } from \"@stryke/type-checks/is-number\";\nimport { isPromiseLike } from \"@stryke/type-checks/is-promise\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { MaybePromise } from \"@stryke/types/base\";\nimport chalk from \"chalk\";\nimport {\n findInvalidPluginConfig,\n isDuplicate,\n isPlugin,\n isPluginConfig,\n isPluginConfigObject,\n isPluginConfigTuple\n} from \"../plugin-utils\";\nimport type {\n EnvironmentContext,\n ExecutionContext,\n Plugin,\n PluginConfig,\n PluginConfigTuple,\n PluginContext,\n PluginFactory,\n ResolvedConfig\n} from \"../types\";\n\n/**\n * Resolve a plugin module based on the provided plugin path. This function checks if the plugin package is installed, attempts to import the plugin module, and handles various error cases such as missing packages or invalid module exports. It supports both direct plugin exports and plugins exported from a \"plugin\" subdirectory within the package.\n *\n * @param context - The execution context in which the plugin will be initialized. This context provides access to configuration, logging, and other utilities that may be needed during plugin initialization.\n * @param pluginPath - The path to the plugin module. This can be a package name, a scoped package name, or a path to a local module.\n * @returns A promise that resolves to the plugin module, which can be a plugin instance, a factory function that returns a plugin, or an array of plugins.\n */\nexport async function resolvePlugin<\n TResolvedConfig extends ResolvedConfig,\n TSystemContext,\n TContext extends\n | EnvironmentContext<TResolvedConfig, TSystemContext>\n | ExecutionContext<TResolvedConfig, TSystemContext> =\n | EnvironmentContext<TResolvedConfig, TSystemContext>\n | ExecutionContext<TResolvedConfig, TSystemContext>,\n TPluginContext extends PluginContext<TResolvedConfig, TSystemContext> =\n PluginContext<TResolvedConfig, TSystemContext>\n>(\n context: TContext,\n pluginPath: string\n): Promise<\n | Plugin<TPluginContext>\n | Plugin<TPluginContext>[]\n | ((\n options?: any\n ) => MaybePromise<Plugin<TPluginContext> | Plugin<TPluginContext>[]>)\n> {\n if (\n pluginPath.startsWith(\"@\") &&\n pluginPath.split(\"/\").filter(Boolean).length > 2\n ) {\n const splits = pluginPath.split(\"/\").filter(Boolean);\n pluginPath = `${splits[0]}/${splits[1]}`;\n }\n\n const isInstalled = isPackageExists(pluginPath, {\n paths: [context.config.cwd, context.config.root]\n });\n if (!isInstalled && context.config.autoInstall) {\n context.warn(\n `The plugin package \"${\n pluginPath\n }\" is not installed. It will be installed automatically.`\n );\n\n const result = await install(pluginPath, {\n cwd: context.config.root\n });\n if (isNumber(result.exitCode) && result.exitCode > 0) {\n context.error(result.stderr);\n\n throw new Error(\n `An error occurred while installing the build plugin package \"${\n pluginPath\n }\" `\n );\n }\n }\n\n try {\n // First check if the package has a \"plugin\" subdirectory - @scope/package/plugin\n const module = await context.resolver.plugin.import<{\n plugin?:\n | Plugin<TPluginContext>\n | ((options?: any) => MaybePromise<Plugin<TPluginContext>>);\n default?:\n | Plugin<TPluginContext>\n | ((options?: any) => MaybePromise<Plugin<TPluginContext>>);\n }>(context.resolver.plugin.esmResolve(joinPaths(pluginPath, \"plugin\")));\n\n const result = module.plugin ?? module.default;\n if (!result) {\n throw new Error(\n `The plugin package \"${pluginPath}\" does not export a valid module.`\n );\n }\n\n return result;\n } catch (error) {\n try {\n const module = await context.resolver.plugin.import<{\n plugin?:\n | Plugin<TPluginContext>\n | ((options?: any) => MaybePromise<Plugin<TPluginContext>>);\n default?:\n | Plugin<TPluginContext>\n | ((options?: any) => MaybePromise<Plugin<TPluginContext>>);\n }>(context.resolver.plugin.esmResolve(pluginPath));\n\n const result = module.plugin ?? module.default;\n if (!result) {\n throw new Error(\n `The plugin package \"${pluginPath}\" does not export a valid module.`\n );\n }\n\n return result;\n } catch {\n if (!isInstalled) {\n throw new Error(\n `The plugin package \"${\n pluginPath\n }\" is not installed. Please install the package using the command: \"npm install ${\n pluginPath\n } --save-dev\"`\n );\n } else {\n throw new Error(\n `An error occurred while importing the build plugin package \"${\n pluginPath\n }\":\n${isError(error) ? error.message : String(error)}\n\nNote: Please ensure the plugin package's default export is a class that extends \\`Plugin\\` with a constructor that excepts a single arguments of type \\`PluginOptions\\`.`\n );\n }\n }\n }\n}\n\n/**\n * Initialize a plugin based on the provided plugin configuration. This function handles various forms of plugin configurations, including direct plugin instances, factory functions, string paths to plugins, and arrays of plugins or plugin configurations. It validates the plugin configuration, resolves any plugin paths, and returns an array of initialized plugins.\n *\n * @param context - The execution context in which the plugin will be initialized. This context provides access to configuration, logging, and other utilities that may be needed during plugin initialization.\n * @param config - The plugin configuration, which can be in various forms such as a direct plugin instance, a string path to a plugin, a factory function that returns a plugin, or an array of plugins or plugin configurations. This configuration will be processed and validated to initialize the appropriate plugins.\n * @returns A promise that resolves to an array of initialized plugins based on the provided configuration. If the configuration is invalid, an error will be thrown with details about the issue.\n */\nexport async function initPlugin<\n TResolvedConfig extends ResolvedConfig,\n TSystemContext,\n TContext extends\n | EnvironmentContext<TResolvedConfig, TSystemContext>\n | ExecutionContext<TResolvedConfig, TSystemContext> =\n | EnvironmentContext<TResolvedConfig, TSystemContext>\n | ExecutionContext<TResolvedConfig, TSystemContext>,\n TPluginContext extends PluginContext<TResolvedConfig, TSystemContext> =\n PluginContext<TResolvedConfig, TSystemContext>\n>(\n context: TContext,\n config: PluginConfig<TPluginContext>,\n options: ResolvePluginsOptions = {}\n): Promise<Plugin<TPluginContext>[] | null> {\n const { skipLogging = false } = options;\n\n let awaited = config;\n if (isPromiseLike(config)) {\n awaited = (await Promise.resolve(\n config as Promise<any>\n )) as PluginConfig<TPluginContext>;\n }\n\n if (!isPluginConfig<TPluginContext>(awaited)) {\n const invalid = findInvalidPluginConfig(awaited);\n\n throw new Error(\n `Invalid ${\n invalid && invalid.length > 1 ? \"plugins\" : \"plugin\"\n } specified in the configuration - ${\n invalid && invalid.length > 0\n ? JSON.stringify(awaited)\n : invalid?.join(\"\\n\\n\")\n } \\n\\nPlease ensure the value is one of the following: \\n - an instance of \\`Plugin\\` \\n - a plugin name \\n - an object with the \\`plugin\\` and \\`options\\` properties \\n - a tuple array with the plugin and options \\n - a factory function that returns a plugin or array of plugins \\n - an array of plugins or plugin configurations`\n );\n }\n\n let plugins!: Plugin<TPluginContext>[];\n if (isPlugin<TPluginContext>(awaited)) {\n plugins = [awaited];\n } else if (isFunction(awaited)) {\n plugins = toArray(await Promise.resolve(awaited()));\n } else if (isString(awaited)) {\n const resolved = await resolvePlugin<\n TResolvedConfig,\n TSystemContext,\n TContext\n >(context, awaited);\n if (isFunction(resolved)) {\n plugins = toArray(await Promise.resolve(resolved()));\n } else {\n plugins = toArray(resolved);\n }\n } else if (\n Array.isArray(awaited) &&\n (awaited as TPluginContext[]).every(isPlugin<TPluginContext>)\n ) {\n plugins = awaited as Plugin<TPluginContext>[];\n } else if (\n Array.isArray(awaited) &&\n (awaited as PluginConfig<TPluginContext>[]).every(\n isPluginConfig<TPluginContext>\n )\n ) {\n plugins = [];\n for (const pluginConfig of awaited as PluginConfig<TPluginContext>[]) {\n const initialized = await initPlugin<\n TResolvedConfig,\n TSystemContext,\n TContext,\n TPluginContext\n >(context, pluginConfig);\n if (initialized) {\n plugins.push(...initialized);\n }\n }\n } else if (\n isPluginConfigTuple<TPluginContext>(awaited) ||\n isPluginConfigObject<TPluginContext>(awaited)\n ) {\n let pluginConfig!:\n | string\n | PluginFactory<TPluginContext>\n | Plugin<TPluginContext>;\n let pluginOptions: any;\n\n if (isPluginConfigTuple<TPluginContext>(awaited)) {\n pluginConfig = awaited[0] as Plugin<TPluginContext>;\n pluginOptions =\n (awaited as PluginConfigTuple)?.length === 2 ? awaited[1] : undefined;\n } else {\n pluginConfig = awaited.plugin as Plugin<TPluginContext>;\n pluginOptions = awaited.options;\n }\n\n if (isSetString(pluginConfig)) {\n const resolved = await resolvePlugin<\n TResolvedConfig,\n TSystemContext,\n TContext,\n TPluginContext\n >(context, pluginConfig);\n if (isFunction(resolved)) {\n plugins = toArray(\n await Promise.resolve(\n pluginOptions ? resolved(pluginOptions) : resolved()\n )\n );\n } else {\n plugins = toArray(resolved);\n }\n } else if (isFunction(pluginConfig)) {\n plugins = toArray(await Promise.resolve(pluginConfig(pluginOptions)));\n } else if (\n Array.isArray(pluginConfig) &&\n pluginConfig.every(isPlugin<TPluginContext>)\n ) {\n plugins = pluginConfig;\n } else if (isPlugin<TPluginContext>(pluginConfig)) {\n plugins = toArray(pluginConfig);\n }\n }\n\n if (!plugins) {\n throw new Error(\n `The plugin configuration ${JSON.stringify(awaited)} is invalid. This configuration must point to a valid Powerlines plugin module.`\n );\n }\n\n if (plugins.length > 0 && !plugins.every(isPlugin<TPluginContext>)) {\n throw new Error(\n `The plugin option ${JSON.stringify(plugins)} does not export a valid module. This configuration must point to a valid Powerlines plugin module.`\n );\n }\n\n const result = [] as Plugin<TPluginContext>[];\n for (const plugin of plugins) {\n if (isDuplicate<TPluginContext>(plugin, context.plugins)) {\n if (!skipLogging) {\n context.trace({\n meta: {\n category: \"plugins\"\n },\n message: `Duplicate ${chalk.bold.cyanBright(\n plugin.name\n )} plugin dependency detected - Skipping initialization.`\n });\n }\n } else {\n result.push(plugin);\n\n if (!skipLogging) {\n context.trace({\n meta: {\n category: \"plugins\"\n },\n message: `Initializing the ${chalk.bold.cyanBright(plugin.name)} plugin...`\n });\n }\n }\n }\n\n return result;\n}\n\nexport interface ResolvePluginsOptions {\n /**\n * If true, the plugin resolution process will skip logging messages about the plugin initialization. This can be useful in scenarios where you want to suppress plugin-related logs, such as when running in a non-interactive environment or when you want to reduce log verbosity. By default, this option is false, and plugin initialization messages will be logged using the context's logger.\n */\n skipLogging?: boolean;\n}\n\n/**\n * Initialize a plugin based on the provided plugin configuration. This function handles various forms of plugin configurations, including direct plugin instances, plugin names, factory functions, and arrays of plugins. It validates the configuration, resolves plugin modules if necessary, and returns an array of initialized plugins ready to be added to the execution context.\n *\n * @param context - The execution context in which the plugin will be initialized. This context provides access to configuration, logging, and other utilities that may be needed during plugin initialization.\n * @param config - The plugin configuration, which can be in various forms such as a plugin instance, a plugin name string, a factory function that returns a plugin or an array of plugins, or an array of plugin configurations. The function will handle the resolution and initialization of the plugin(s) based on the provided configuration.\n * @returns A promise that resolves to an array of initialized plugins that can be added to the execution context, or null if the configuration is invalid or results in no plugins being initialized.\n */\nexport async function resolvePlugins<\n TResolvedConfig extends ResolvedConfig,\n TSystemContext,\n TContext extends\n | EnvironmentContext<TResolvedConfig, TSystemContext>\n | ExecutionContext<TResolvedConfig, TSystemContext> =\n | EnvironmentContext<TResolvedConfig, TSystemContext>\n | ExecutionContext<TResolvedConfig, TSystemContext>,\n TPluginContext extends PluginContext<TResolvedConfig, TSystemContext> =\n PluginContext<TResolvedConfig, TSystemContext>\n>(\n context: TContext,\n config: PluginConfig<TPluginContext>,\n options: ResolvePluginsOptions = {}\n) {\n const { skipLogging = false } = options;\n\n const plugins = [] as Plugin<TPluginContext>[];\n if (config) {\n const result = await initPlugin<\n TResolvedConfig,\n TSystemContext,\n TContext,\n TPluginContext\n >(context, config);\n if (result) {\n for (const plugin of result) {\n if (!skipLogging) {\n context.trace({\n meta: {\n category: \"plugins\"\n },\n message: `Successfully initialized the ${chalk.bold.cyanBright(\n plugin.name\n )} plugin`\n });\n }\n\n plugins.push(plugin);\n }\n }\n }\n\n return plugins;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,cAWpB,SACA,YAOA;CACA,IACE,WAAW,WAAW,GAAG,KACzB,WAAW,MAAM,GAAG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B,IAAI,CAAC,aACH,QAAQ,MAAM;IACZ,MAAM,EACJ,UAAU,UACZ;IACA,SAAS,gCAAgC,MAAM,KAAK,WAClD,OAAO,IACT,EAAE;GACJ,CAAC;GAGH,QAAQ,KAAK,MAAM;EACrB;CAEJ;CAEA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolver.mjs","names":[],"sources":["../../src/lib/resolver.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n
|
|
1
|
+
{"version":3,"file":"resolver.mjs","names":[],"sources":["../../src/lib/resolver.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport defu from \"defu\";\nimport { JitiOptions, createJiti } from \"jiti\";\nimport { ResolvedConfig } from \"../types/config\";\nimport { Resolver } from \"../types/context\";\n\nexport type CreateResolverOptions = Omit<\n JitiOptions,\n \"fsCache\" | \"moduleCache\" | \"interopDefault\"\n> &\n Partial<Pick<ResolvedConfig, \"mode\" | \"skipCache\">> & {\n cwd: string;\n root: string;\n cacheDir: string;\n };\n\n/**\n * Create a Jiti resolver for the given workspace and project root.\n *\n * @param options - The options for creating the resolver.\n * @returns A Jiti instance configured for the specified workspace and project root.\n */\nfunction resolveOptions(options: CreateResolverOptions): JitiOptions {\n return defu(options, {\n interopDefault: true,\n fsCache:\n options.mode !== \"development\"\n ? joinPaths(options.cacheDir, \"jiti\")\n : false,\n moduleCache: options.mode !== \"development\"\n });\n}\n\n/**\n * Create a Jiti resolver for the given workspace and project root.\n *\n * @param options - The options for creating the resolver.\n * @returns A Jiti instance configured for the specified workspace and project root.\n */\nexport function createResolver(options: CreateResolverOptions): Resolver {\n const baseResolver = createJiti(\n joinPaths(options.cwd, options.root),\n resolveOptions(options)\n ) as Resolver;\n baseResolver.plugin = createJiti(\n joinPaths(options.cwd, options.root),\n resolveOptions(options)\n );\n\n return baseResolver;\n}\n"],"mappings":";;;;;;;;;;;AAwCA,SAAS,eAAe,SAA6C;CACnE,OAAO,KAAK,SAAS;EACnB,gBAAgB;EAChB,SACE,QAAQ,SAAS,gBACb,UAAU,QAAQ,UAAU,MAAM,IAClC;EACN,aAAa,QAAQ,SAAS;CAChC,CAAC;AACH;;;;;;;AAQA,SAAgB,eAAe,SAA0C;CACvE,MAAM,eAAe,WACnB,UAAU,QAAQ,KAAK,QAAQ,IAAI,GACnC,eAAe,OAAO,CACxB;CACA,aAAa,SAAS,WACpB,UAAU,QAAQ,KAAK,QAAQ,IAAI,GACnC,eAAe,OAAO,CACxB;CAEA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streaming-channel.mjs","names":[],"sources":["../../src/lib/streaming-channel.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { nanoid } from \"@stryke/unique-id/nanoid-client\";\nimport type { EventEmitter } from \"devframe/types\";\nimport { createEventEmitter } from \"./events\";\n\n/**\n * Serialized error shape sent over the wire when a stream ends with a failure.\n * Stays JSON-safe so the strict-JSON encoder can carry it without coercion.\n */\nexport interface StreamErrorPayload {\n name: string;\n message: string;\n}\n\n/**\n * Single buffered chunk in the server-side ring buffer.\n *\n * Sequence numbers start at 1 and increment per write. Subscribers track\n * `lastSeenSeq` and ask for `afterSeq` on resubscribe so the server can\n * replay any chunks the client missed during a brief disconnect.\n */\nexport interface BufferedChunk<T> {\n seq: number;\n chunk: T;\n}\n\nexport interface StreamSinkEvents<T> {\n /** Fired for each `write()`. The RPC layer subscribes and broadcasts. */\n chunk: (seq: number, chunk: T) => void;\n /** Terminal — fired exactly once per sink lifetime. */\n end: (error?: StreamErrorPayload) => void;\n}\n\nexport interface CreateStreamSinkOptions {\n id?: string;\n /**\n * Size of the per-stream ring buffer kept for replay-on-resubscribe.\n * `0` (default) disables replay.\n */\n replayWindow?: number;\n}\n\n/**\n * Server-side producer handle. Two equivalent surfaces share one piece of\n * state: the imperative `write/error/close` triple, and a `WritableStream<T>`\n * for `pipeTo`-style consumption.\n */\nexport interface StreamSink<T> {\n /** Stable id used by clients to subscribe. */\n readonly id: string;\n /**\n * Aborts when the consumer cancels (server-side) or when the transport\n * loses every subscriber. Producers should poll `signal.aborted` and exit\n * cleanly.\n */\n readonly signal: AbortSignal;\n /** `true` after `close()` / `error()`. Further writes throw. */\n readonly closed: boolean;\n /** Last allocated sequence number. `0` until the first write. */\n readonly lastSeq: number;\n\n write: (chunk: T) => void;\n error: (reason: unknown) => void;\n close: () => void;\n /** External-cancel path. Aborts the signal so handlers can short-circuit. */\n abort: (reason?: unknown) => void;\n\n /** `WritableStream<T>` adapter — same in-memory state as the imperative API. */\n readonly writable: WritableStream<T>;\n\n /**\n * Internal — RPC layer subscribes to receive chunk/end notifications.\n * Not part of the public contract; do not call directly.\n *\n * @internal\n */\n readonly events: EventEmitter<StreamSinkEvents<T>>;\n\n /**\n * Internal — replay buffer. RPC layer reads on (re)subscribe to feed\n * missed chunks before going live.\n *\n * @internal\n */\n readonly buffer: ReadonlyArray<BufferedChunk<T>>;\n}\n\nexport interface CreateStreamReaderOptions {\n id?: string;\n /**\n * Maximum number of buffered chunks held client-side while the consumer\n * isn't draining. On overflow, the oldest chunk is dropped.\n */\n highWaterMark?: number;\n /**\n * Called when the chunk queue overflows the high-water mark. The RPC\n * layer wires this to a coded warning; the primitive itself is\n * RPC-agnostic.\n */\n onOverflow?: (dropped: number) => void;\n /** Called when the consumer cancels — the RPC layer sends `:cancel` upstream. */\n onCancel?: () => void;\n}\n\n/**\n * Client-side consumer handle. Both an `AsyncIterable<T>` (for `for await`)\n * and exposes `readable: ReadableStream<T>` (for `pipeTo`). Pick one — they\n * share a single internal queue, so concurrent draining will race.\n */\nexport interface StreamReader<T> extends AsyncIterable<T> {\n readonly id: string;\n readonly cancelled: boolean;\n readonly done: boolean;\n /** Highest `seq` observed. Used for replay on reconnect. */\n readonly lastSeenSeq: number;\n /** `ReadableStream<T>` adapter for `pipeTo`-style consumption. */\n readonly readable: ReadableStream<T>;\n\n cancel: () => void;\n\n /** @internal */\n _push: (seq: number, chunk: T) => void;\n /** @internal */\n _end: (error?: StreamErrorPayload) => void;\n}\n\nconst DEFAULT_HIGH_WATER_MARK = 256;\n\nclass StreamClosedError extends Error {\n override name = \"StreamClosedError\";\n}\n\n/**\n * Build a server-side stream sink. RPC-agnostic — the RPC host wires\n * `events.on('chunk' | 'end')` to broadcast, and reads `buffer` to replay\n * for late or reconnecting subscribers.\n */\nexport function createStreamSink<T>(\n options: CreateStreamSinkOptions = {}\n): StreamSink<T> {\n const id = options.id ?? nanoid();\n const replayWindow = Math.max(0, options.replayWindow ?? 0);\n const events = createEventEmitter<StreamSinkEvents<T>>();\n const controller = new AbortController();\n const buffer: BufferedChunk<T>[] = [];\n\n let closed = false;\n let lastSeq = 0;\n\n function write(chunk: T): void {\n if (closed) {\n throw new StreamClosedError(`Cannot write to a closed stream \"${id}\"`);\n }\n lastSeq += 1;\n if (replayWindow > 0) {\n buffer.push({ seq: lastSeq, chunk });\n if (buffer.length > replayWindow)\n buffer.splice(0, buffer.length - replayWindow);\n }\n events.emit(\"chunk\", lastSeq, chunk);\n }\n\n function error(reason: unknown): void {\n if (closed) return;\n closed = true;\n const payload = toErrorPayload(reason);\n controller.abort(reason);\n events.emit(\"end\", payload);\n }\n\n function close(): void {\n if (closed) return;\n closed = true;\n if (!controller.signal.aborted) controller.abort(\"stream closed\");\n events.emit(\"end\", undefined);\n }\n\n function abort(reason?: unknown): void {\n if (closed) return;\n if (!controller.signal.aborted) controller.abort(reason ?? \"aborted\");\n }\n\n const writable = new WritableStream<T>({\n write(chunk) {\n write(chunk);\n },\n close() {\n close();\n },\n abort(reason) {\n error(reason);\n }\n });\n\n return {\n id,\n signal: controller.signal,\n get closed() {\n return closed;\n },\n get lastSeq() {\n return lastSeq;\n },\n write,\n error,\n close,\n abort,\n writable,\n events,\n buffer\n };\n}\n\n/**\n * Build a client-side stream reader. RPC-agnostic — the RPC host calls\n * `_push(seq, chunk)` on each incoming chunk and `_end(error?)` on the\n * terminal frame. Consumers iterate with `for await` or pipe `readable`.\n */\nexport function createStreamReader<T>(\n options: CreateStreamReaderOptions = {}\n): StreamReader<T> {\n const id = options.id ?? nanoid();\n const highWaterMark = Math.max(\n 1,\n options.highWaterMark ?? DEFAULT_HIGH_WATER_MARK\n );\n\n const queue: T[] = [];\n let lastSeenSeq = 0;\n let done = false;\n let cancelled = false;\n let endError: StreamErrorPayload | undefined;\n let pending:\n | {\n resolve: (r: IteratorResult<T>) => void;\n reject: (err: unknown) => void;\n }\n | undefined;\n // Lazily created — accessing `reader.readable` claims the queue for\n // `pipeTo` consumption. While inactive, `_push` only feeds the\n // AsyncIterator path. Mixing the two surfaces is undefined behavior.\n let pullController: ReadableStreamDefaultController<T> | undefined;\n let readableInstance: ReadableStream<T> | undefined;\n\n function drainNext(): void {\n if (!pending) return;\n if (queue.length > 0) {\n const value = queue.shift()!;\n const r = pending;\n pending = undefined;\n r.resolve({ value, done: false });\n return;\n }\n if (done) {\n const r = pending;\n pending = undefined;\n if (endError) {\n const err = new Error(endError.message);\n err.name = endError.name;\n r.reject(err);\n } else {\n r.resolve({ value: undefined, done: true });\n }\n }\n }\n\n function feedReadable(): void {\n if (!pullController) return;\n while (queue.length > 0) {\n const v = queue.shift()!;\n try {\n pullController.enqueue(v);\n } catch {\n // controller closed/errored under us — drop silently; the\n // ReadableStream consumer is gone and we can't push further.\n break;\n }\n }\n if (done && pullController) {\n try {\n if (endError) {\n const err = new Error(endError.message);\n err.name = endError.name;\n pullController.error(err);\n } else {\n pullController.close();\n }\n } catch {\n // already closed\n }\n pullController = undefined;\n }\n }\n\n function push(seq: number, chunk: T): void {\n if (done || cancelled) return;\n if (seq <= lastSeenSeq) return; // dedupe replays we've already seen\n lastSeenSeq = seq;\n queue.push(chunk);\n if (queue.length > highWaterMark) {\n const overflow = queue.length - highWaterMark;\n queue.splice(0, overflow);\n options.onOverflow?.(overflow);\n }\n drainNext();\n if (readableInstance) feedReadable();\n }\n\n function end(error?: StreamErrorPayload): void {\n if (done) return;\n done = true;\n endError = error;\n drainNext();\n if (readableInstance) feedReadable();\n }\n\n function cancel(): void {\n if (cancelled || done) return;\n cancelled = true;\n options.onCancel?.();\n end(undefined);\n }\n\n function getReadable(): ReadableStream<T> {\n if (readableInstance) return readableInstance;\n readableInstance = new ReadableStream<T>({\n start(controller) {\n pullController = controller;\n feedReadable();\n },\n cancel() {\n cancel();\n }\n });\n return readableInstance;\n }\n\n const reader: StreamReader<T> = {\n id,\n get cancelled() {\n return cancelled;\n },\n get done() {\n return done;\n },\n get lastSeenSeq() {\n return lastSeenSeq;\n },\n get readable() {\n return getReadable();\n },\n cancel,\n _push: push,\n _end: end,\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n async next(): Promise<IteratorResult<T>> {\n if (queue.length > 0) {\n return Promise.resolve({ value: queue.shift()!, done: false });\n }\n if (done) {\n if (endError) {\n const err = new Error(endError.message);\n err.name = endError.name;\n return Promise.reject(err);\n }\n return Promise.resolve({\n value: undefined as unknown as T,\n done: true\n });\n }\n return new Promise<IteratorResult<T>>((resolve, reject) => {\n pending = { resolve, reject };\n });\n },\n async return(): Promise<IteratorResult<T>> {\n cancel();\n return Promise.resolve({\n value: undefined as unknown as T,\n done: true\n });\n }\n };\n }\n };\n\n return reader;\n}\n\nfunction toErrorPayload(reason: unknown): StreamErrorPayload {\n if (reason instanceof Error) {\n return { name: reason.name || \"Error\", message: reason.message };\n }\n if (typeof reason === \"string\") {\n return { name: \"Error\", message: reason };\n }\n try {\n return { name: \"Error\", message: JSON.stringify(reason) };\n } catch {\n return { name: \"Error\", message: String(reason) };\n }\n}\n"],"mappings":";;;;AA+IA,MAAM,0BAA0B;AAEhC,IAAM,oBAAN,cAAgC,MAAM;CACpC,AAAS,OAAO;AAClB;;;;;;AAOA,SAAgB,iBACd,UAAmC,CAAC,GACrB;CACf,MAAM,KAAK,QAAQ,MAAM,OAAO;CAChC,MAAM,eAAe,KAAK,IAAI,GAAG,QAAQ,gBAAgB,CAAC;CAC1D,MAAM,SAAS,mBAAwC;CACvD,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,SAA6B,CAAC;CAEpC,IAAI,SAAS;CACb,IAAI,UAAU;CAEd,SAAS,MAAM,OAAgB;EAC7B,IAAI,QACF,MAAM,IAAI,kBAAkB,oCAAoC,GAAG,EAAE;EAEvE,WAAW;EACX,IAAI,eAAe,GAAG;GACpB,OAAO,KAAK;IAAE,KAAK;IAAS;GAAM,CAAC;GACnC,IAAI,OAAO,SAAS,cAClB,OAAO,OAAO,GAAG,OAAO,SAAS,YAAY;EACjD;EACA,OAAO,KAAK,SAAS,SAAS,KAAK;CACrC;CAEA,SAAS,MAAM,QAAuB;EACpC,IAAI,QAAQ;EACZ,SAAS;EACT,MAAM,UAAU,eAAe,MAAM;EACrC,WAAW,MAAM,MAAM;EACvB,OAAO,KAAK,OAAO,OAAO;CAC5B;CAEA,SAAS,QAAc;EACrB,IAAI,QAAQ;EACZ,SAAS;EACT,IAAI,CAAC,WAAW,OAAO,SAAS,WAAW,M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O,QAAQ,QAAQ;MAAE,OAAO,MAAM,MAAM;MAAI,MAAM;KAAM,CAAC;KAE/D,IAAI,MAAM;MACR,IAAI,UAAU;OACZ,MAAM,MAAM,IAAI,MAAM,SAAS,OAAO;OACtC,IAAI,OAAO,SAAS;OACpB,OAAO,QAAQ,OAAO,GAAG;MAC3B;MACA,OAAO,QAAQ,QAAQ;OACrB,OAAO;OACP,MAAM;MACR,CAAC;KACH;KACA,OAAO,IAAI,SAA4B,SAAS,WAAW;MACzD,UAAU;OAAE;OAAS;MAAO;KAC9B,CAAC;IACH;IACA,MAAM,SAAqC;KACzC,OAAO;KACP,OAAO,QAAQ,QAAQ;MACrB,OAAO;MACP,MAAM;KACR,CAAC;IACH;GACF;EACF;CAGU;AACd;AAEA,SAAS,eAAe,QAAqC;CAC3D,IAAI,kBAAkB,OACpB,OAAO;EAAE,MAAM,OAAO,QAAQ;EAAS,SAAS,OAAO;CAAQ;CAEjE,IAAI,OAAO,WAAW,UACpB,OAAO;EAAE,MAAM;EAAS,SAAS;CAAO;CAE1C,IAAI;EACF,OAAO;GAAE,MAAM;GAAS,SAAS,KAAK,UAAU,MAAM;EAAE;CAC1D,QAAQ;EACN,OAAO;GAAE,MAAM;GAAS,SAAS,OAAO,MAAM;EAAE;CAClD;AACF"}
|
|
1
|
+
{"version":3,"file":"streaming-channel.mjs","names":[],"sources":["../../src/lib/streaming-channel.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n 🗲 Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { nanoid } from \"@stryke/unique-id/nanoid-client\";\nimport type { EventEmitter } from \"devframe/types\";\nimport { createEventEmitter } from \"./events\";\n\n/**\n * Serialized error shape sent over the wire when a stream ends with a failure.\n * Stays JSON-safe so the strict-JSON encoder can carry it without coercion.\n */\nexport interface StreamErrorPayload {\n name: string;\n message: string;\n}\n\n/**\n * Single buffered chunk in the server-side ring buffer.\n *\n * Sequence numbers start at 1 and increment per write. Subscribers track\n * `lastSeenSeq` and ask for `afterSeq` on resubscribe so the server can\n * replay any chunks the client missed during a brief disconnect.\n */\nexport interface BufferedChunk<T> {\n seq: number;\n chunk: T;\n}\n\nexport interface StreamSinkEvents<T> {\n /** Fired for each `write()`. The RPC layer subscribes and broadcasts. */\n chunk: (seq: number, chunk: T) => void;\n /** Terminal — fired exactly once per sink lifetime. */\n end: (error?: StreamErrorPayload) => void;\n}\n\nexport interface CreateStreamSinkOptions {\n id?: string;\n /**\n * Size of the per-stream ring buffer kept for replay-on-resubscribe.\n * `0` (default) disables replay.\n */\n replayWindow?: number;\n}\n\n/**\n * Server-side producer handle. Two equivalent surfaces share one piece of\n * state: the imperative `write/error/close` triple, and a `WritableStream<T>`\n * for `pipeTo`-style consumption.\n */\nexport interface StreamSink<T> {\n /** Stable id used by clients to subscribe. */\n readonly id: string;\n /**\n * Aborts when the consumer cancels (server-side) or when the transport\n * loses every subscriber. Producers should poll `signal.aborted` and exit\n * cleanly.\n */\n readonly signal: AbortSignal;\n /** `true` after `close()` / `error()`. Further writes throw. */\n readonly closed: boolean;\n /** Last allocated sequence number. `0` until the first write. */\n readonly lastSeq: number;\n\n write: (chunk: T) => void;\n error: (reason: unknown) => void;\n close: () => void;\n /** External-cancel path. Aborts the signal so handlers can short-circuit. */\n abort: (reason?: unknown) => void;\n\n /** `WritableStream<T>` adapter — same in-memory state as the imperative API. */\n readonly writable: WritableStream<T>;\n\n /**\n * Internal — RPC layer subscribes to receive chunk/end notifications.\n * Not part of the public contract; do not call directly.\n *\n * @internal\n */\n readonly events: EventEmitter<StreamSinkEvents<T>>;\n\n /**\n * Internal — replay buffer. RPC layer reads on (re)subscribe to feed\n * missed chunks before going live.\n *\n * @internal\n */\n readonly buffer: ReadonlyArray<BufferedChunk<T>>;\n}\n\nexport interface CreateStreamReaderOptions {\n id?: string;\n /**\n * Maximum number of buffered chunks held client-side while the consumer\n * isn't draining. On overflow, the oldest chunk is dropped.\n */\n highWaterMark?: number;\n /**\n * Called when the chunk queue overflows the high-water mark. The RPC\n * layer wires this to a coded warning; the primitive itself is\n * RPC-agnostic.\n */\n onOverflow?: (dropped: number) => void;\n /** Called when the consumer cancels — the RPC layer sends `:cancel` upstream. */\n onCancel?: () => void;\n}\n\n/**\n * Client-side consumer handle. Both an `AsyncIterable<T>` (for `for await`)\n * and exposes `readable: ReadableStream<T>` (for `pipeTo`). Pick one — they\n * share a single internal queue, so concurrent draining will race.\n */\nexport interface StreamReader<T> extends AsyncIterable<T> {\n readonly id: string;\n readonly cancelled: boolean;\n readonly done: boolean;\n /** Highest `seq` observed. Used for replay on reconnect. */\n readonly lastSeenSeq: number;\n /** `ReadableStream<T>` adapter for `pipeTo`-style consumption. */\n readonly readable: ReadableStream<T>;\n\n cancel: () => void;\n\n /** @internal */\n _push: (seq: number, chunk: T) => void;\n /** @internal */\n _end: (error?: StreamErrorPayload) => void;\n}\n\nconst DEFAULT_HIGH_WATER_MARK = 256;\n\nclass StreamClosedError extends Error {\n override name = \"StreamClosedError\";\n}\n\n/**\n * Build a server-side stream sink. RPC-agnostic — the RPC host wires\n * `events.on('chunk' | 'end')` to broadcast, and reads `buffer` to replay\n * for late or reconnecting subscribers.\n */\nexport function createStreamSink<T>(\n options: CreateStreamSinkOptions = {}\n): StreamSink<T> {\n const id = options.id ?? nanoid();\n const replayWindow = Math.max(0, options.replayWindow ?? 0);\n const events = createEventEmitter<StreamSinkEvents<T>>();\n const controller = new AbortController();\n const buffer: BufferedChunk<T>[] = [];\n\n let closed = false;\n let lastSeq = 0;\n\n function write(chunk: T): void {\n if (closed) {\n throw new StreamClosedError(`Cannot write to a closed stream \"${id}\"`);\n }\n lastSeq += 1;\n if (replayWindow > 0) {\n buffer.push({ seq: lastSeq, chunk });\n if (buffer.length > replayWindow)\n buffer.splice(0, buffer.length - replayWindow);\n }\n events.emit(\"chunk\", lastSeq, chunk);\n }\n\n function error(reason: unknown): void {\n if (closed) return;\n closed = true;\n const payload = toErrorPayload(reason);\n controller.abort(reason);\n events.emit(\"end\", payload);\n }\n\n function close(): void {\n if (closed) return;\n closed = true;\n if (!controller.signal.aborted) controller.abort(\"stream closed\");\n events.emit(\"end\", undefined);\n }\n\n function abort(reason?: unknown): void {\n if (closed) return;\n if (!controller.signal.aborted) controller.abort(reason ?? \"aborted\");\n }\n\n const writable = new WritableStream<T>({\n write(chunk) {\n write(chunk);\n },\n close() {\n close();\n },\n abort(reason) {\n error(reason);\n }\n });\n\n return {\n id,\n signal: controller.signal,\n get closed() {\n return closed;\n },\n get lastSeq() {\n return lastSeq;\n },\n write,\n error,\n close,\n abort,\n writable,\n events,\n buffer\n };\n}\n\n/**\n * Build a client-side stream reader. RPC-agnostic — the RPC host calls\n * `_push(seq, chunk)` on each incoming chunk and `_end(error?)` on the\n * terminal frame. Consumers iterate with `for await` or pipe `readable`.\n */\nexport function createStreamReader<T>(\n options: CreateStreamReaderOptions = {}\n): StreamReader<T> {\n const id = options.id ?? nanoid();\n const highWaterMark = Math.max(\n 1,\n options.highWaterMark ?? DEFAULT_HIGH_WATER_MARK\n );\n\n const queue: T[] = [];\n let lastSeenSeq = 0;\n let done = false;\n let cancelled = false;\n let endError: StreamErrorPayload | undefined;\n let pending:\n | {\n resolve: (r: IteratorResult<T>) => void;\n reject: (err: unknown) => void;\n }\n | undefined;\n // Lazily created — accessing `reader.readable` claims the queue for\n // `pipeTo` consumption. While inactive, `_push` only feeds the\n // AsyncIterator path. Mixing the two surfaces is undefined behavior.\n let pullController: ReadableStreamDefaultController<T> | undefined;\n let readableInstance: ReadableStream<T> | undefined;\n\n function drainNext(): void {\n if (!pending) return;\n if (queue.length > 0) {\n const value = queue.shift()!;\n const r = pending;\n pending = undefined;\n r.resolve({ value, done: false });\n return;\n }\n if (done) {\n const r = pending;\n pending = undefined;\n if (endError) {\n const err = new Error(endError.message);\n err.name = endError.name;\n r.reject(err);\n } else {\n r.resolve({ value: undefined, done: true });\n }\n }\n }\n\n function feedReadable(): void {\n if (!pullController) return;\n while (queue.length > 0) {\n const v = queue.shift()!;\n try {\n pullController.enqueue(v);\n } catch {\n // controller closed/errored under us — drop silently; the\n // ReadableStream consumer is gone and we can't push further.\n break;\n }\n }\n if (done && pullController) {\n try {\n if (endError) {\n const err = new Error(endError.message);\n err.name = endError.name;\n pullController.error(err);\n } else {\n pullController.close();\n }\n } catch {\n // already closed\n }\n pullController = undefined;\n }\n }\n\n function push(seq: number, chunk: T): void {\n if (done || cancelled) return;\n if (seq <= lastSeenSeq) return; // dedupe replays we've already seen\n lastSeenSeq = seq;\n queue.push(chunk);\n if (queue.length > highWaterMark) {\n const overflow = queue.length - highWaterMark;\n queue.splice(0, overflow);\n options.onOverflow?.(overflow);\n }\n drainNext();\n if (readableInstance) feedReadable();\n }\n\n function end(error?: StreamErrorPayload): void {\n if (done) return;\n done = true;\n endError = error;\n drainNext();\n if (readableInstance) feedReadable();\n }\n\n function cancel(): void {\n if (cancelled || done) return;\n cancelled = true;\n options.onCancel?.();\n end(undefined);\n }\n\n function getReadable(): ReadableStream<T> {\n if (readableInstance) return readableInstance;\n readableInstance = new ReadableStream<T>({\n start(controller) {\n pullController = controller;\n feedReadable();\n },\n cancel() {\n cancel();\n }\n });\n return readableInstance;\n }\n\n const reader: StreamReader<T> = {\n id,\n get cancelled() {\n return cancelled;\n },\n get done() {\n return done;\n },\n get lastSeenSeq() {\n return lastSeenSeq;\n },\n get readable() {\n return getReadable();\n },\n cancel,\n _push: push,\n _end: end,\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n async next(): Promise<IteratorResult<T>> {\n if (queue.length > 0) {\n return Promise.resolve({ value: queue.shift()!, done: false });\n }\n if (done) {\n if (endError) {\n const err = new Error(endError.message);\n err.name = endError.name;\n return Promise.reject(err);\n }\n return Promise.resolve({\n value: undefined as unknown as T,\n done: true\n });\n }\n return new Promise<IteratorResult<T>>((resolve, reject) => {\n pending = { resolve, reject };\n });\n },\n async return(): Promise<IteratorResult<T>> {\n cancel();\n return Promise.resolve({\n value: undefined as unknown as T,\n done: true\n });\n }\n };\n }\n };\n\n return reader;\n}\n\nfunction toErrorPayload(reason: unknown): StreamErrorPayload {\n if (reason instanceof Error) {\n return { name: reason.name || \"Error\", message: reason.message };\n }\n if (typeof reason === \"string\") {\n return { name: \"Error\", message: reason };\n }\n try {\n return { name: \"Error\", message: JSON.stringify(reason) };\n } catch {\n return { name: \"Error\", message: String(reason) };\n }\n}\n"],"mappings":";;;;AA+IA,MAAM,0BAA0B;AAEhC,IAAM,oBAAN,cAAgC,MAAM;CACpC,AAAS,OAAO;AAClB;;;;;;AAOA,SAAgB,iBACd,UAAmC,CAAC,GACrB;CACf,MAAM,KAAK,QAAQ,MAAM,OAAO;CAChC,MAAM,eAAe,KAAK,IAAI,GAAG,QAAQ,gBAAgB,CAAC;CAC1D,MAAM,SAAS,mBAAwC;CACvD,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,SAA6B,CAAC;CAEpC,IAAI,SAAS;CACb,IAAI,UAAU;CAEd,SAAS,MAAM,OAAgB;EAC7B,IAAI,QACF,MAAM,IAAI,kBAAkB,oCAAoC,GAAG,EAAE;EAEvE,WAAW;EACX,IAAI,eAAe,GAAG;GACpB,OAAO,KAAK;IAAE,KAAK;IAAS;GAAM,CAAC;GACnC,IAAI,OAAO,SAAS,cAClB,OAAO,OAAO,GAAG,OAAO,SAAS,YAAY;EACjD;EACA,OAAO,KAAK,SAAS,SAAS,KAAK;CACrC;CAEA,SAAS,MAAM,QAAuB;EACpC,IAAI,QAAQ;EACZ,SAAS;EACT,MAAM,UAAU,eAAe,MAAM;EACrC,WAAW,MAAM,MAAM;EACvB,OAA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