every-plugin
Version:
1 lines • 15.2 kB
Source Map (JSON)
{"version":3,"file":"plugin.mjs","names":[],"sources":["../../../src/build/rspack/plugin.ts"],"sourcesContent":["import crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { ModuleFederationPlugin } from \"@module-federation/enhanced/rspack\";\nimport type { Compiler, RspackPluginInstance } from \"@rspack/core\";\nimport { setupPluginMiddleware } from \"./dev-server-middleware\";\nimport { buildSharedDependencies } from \"./module-federation\";\nimport { getPluginInfo, loadDevConfig } from \"./utils\";\n\nexport interface EveryPluginOptions {\n devConfigPath?: string;\n port?: number;\n pluginId?: string;\n dts?: boolean;\n}\n\nexport interface AdditionalExport {\n srcPath: string;\n exportNames: string[];\n}\n\nexport interface PluginManifestEmitterOptions {\n manifestFileName?: string;\n contractFileName?: string;\n additionalExports?: AdditionalExport[];\n}\n\nexport class EmitPluginManifest implements RspackPluginInstance {\n name = \"EmitPluginManifest\";\n\n constructor(private options: PluginManifestEmitterOptions = {}) {}\n\n apply(compiler: Compiler) {\n compiler.hooks.thisCompilation.tap(this.name, (compilation) => {\n const webpack = (compiler as Compiler & { webpack?: any }).webpack;\n const rawSource = webpack?.sources?.RawSource;\n const stage = webpack?.Compilation?.PROCESS_ASSETS_STAGE_ADDITIONS ?? 1000;\n\n compilation.hooks.processAssets.tapPromise({ name: this.name, stage }, async () => {\n const context = compiler.options.context || process.cwd();\n const pluginInfo = getPluginInfo(context);\n const contractFileName = this.options.contractFileName ?? \"contract.d.ts\";\n const manifestFileName = this.options.manifestFileName ?? \"plugin.manifest.json\";\n\n const sourceContractPath = path.join(context, \"types\", contractFileName);\n\n let contractTypes: string;\n\n const tryReadFile = async (filePath: string): Promise<string | null> => {\n if (!fs.existsSync(filePath)) {\n return null;\n }\n const stats = fs.statSync(filePath);\n if (!stats.isFile()) {\n return null;\n }\n try {\n return await fs.promises.readFile(filePath, \"utf8\");\n } catch {\n return null;\n }\n };\n\n contractTypes = (await tryReadFile(sourceContractPath)) ?? \"\";\n\n if (!contractTypes) {\n const packageDir = context.split(\"/\").pop();\n const nestedPath = path.join(context, \"types\", packageDir ?? \"\", \"src\", contractFileName);\n\n contractTypes = (await tryReadFile(nestedPath)) ?? \"\";\n\n if (!contractTypes) {\n console.warn(\n `[EmitPluginManifest] Contract file not found at ${sourceContractPath} or ${nestedPath}. ` +\n `Skipping manifest generation.`,\n );\n return;\n }\n }\n\n const contractSha256 = crypto.createHash(\"sha256\").update(contractTypes).digest(\"hex\");\n const manifest: Record<string, unknown> = {\n schemaVersion: 1,\n kind: \"every-plugin/manifest\",\n plugin: {\n name: pluginInfo.name,\n version: pluginInfo.version,\n },\n runtime: {\n remoteEntry: \"./remoteEntry.js\",\n },\n contract: {\n kind: \"orpc\",\n types: {\n path: `./types/${contractFileName}`,\n exportName: \"contract\",\n typeName: \"ContractType\",\n sha256: contractSha256,\n },\n },\n };\n\n const additionalExportsEntries: Array<{ path: string; exports: string[]; sha256: string }> =\n [];\n\n if (this.options.additionalExports?.length) {\n for (const additional of this.options.additionalExports) {\n const sourcePath = path.join(context, \"types\", additional.srcPath);\n const content = await tryReadFile(sourcePath);\n if (!content) {\n console.warn(\n `[EmitPluginManifest] Additional export file not found at ${sourcePath}. Skipping.`,\n );\n continue;\n }\n const sha256 = crypto.createHash(\"sha256\").update(content).digest(\"hex\");\n const distPath = `./types/${additional.srcPath}`;\n additionalExportsEntries.push({\n path: distPath,\n exports: additional.exportNames,\n sha256,\n });\n\n if (rawSource) {\n compilation.emitAsset(`types/${additional.srcPath}`, new rawSource(content));\n }\n }\n\n if (additionalExportsEntries.length > 0) {\n manifest.additionalExports = additionalExportsEntries;\n }\n }\n\n if (rawSource) {\n compilation.emitAsset(\n manifestFileName,\n new rawSource(`${JSON.stringify(manifest, null, 2)}\\n`),\n );\n compilation.emitAsset(`types/${contractFileName}`, new rawSource(`${contractTypes}`));\n }\n });\n });\n }\n}\n\nexport class EveryPluginDevServer implements RspackPluginInstance {\n name = \"EveryPluginDevServer\";\n\n constructor(private options: EveryPluginOptions = {}) {}\n\n apply(compiler: Compiler) {\n const pluginInfo = getPluginInfo(compiler.options.context || process.cwd());\n const devConfig = loadDevConfig(this.options.devConfigPath || \"./plugin.dev.ts\");\n const port = Number(process.env.PORT) || this.options.port || devConfig?.port || 3999;\n\n this.configureDefaults(compiler, pluginInfo);\n\n if (!compiler.options.devServer) {\n compiler.options.devServer = {};\n }\n\n this.configureDevServer(compiler, pluginInfo, devConfig, port);\n\n new ModuleFederationPlugin({\n name: pluginInfo.normalizedName,\n filename: \"remoteEntry.js\",\n dts: this.options.dts !== false,\n manifest: {},\n runtimePlugins: [require.resolve(\"@module-federation/node/runtimePlugin\")],\n library: { type: \"commonjs-module\" },\n exposes: {\n \"./plugin\": \"./src/index.ts\",\n },\n shared: buildSharedDependencies(pluginInfo),\n shareStrategy: \"version-first\",\n }).apply(compiler);\n\n if (this.options.dts === false) {\n compiler.options.plugins = (compiler.options.plugins ?? []).filter(\n (p) =>\n !p ||\n typeof p !== \"object\" ||\n ((p as any).name !== \"MFDevPlugin\" && (p as any).name !== \"ModuleFederationDtsPlugin\"),\n );\n }\n }\n\n private configureDefaults(compiler: Compiler, pluginInfo: any) {\n const context = compiler.options.context || process.cwd();\n\n if (!compiler.options.output) {\n compiler.options.output = {};\n }\n compiler.options.output.uniqueName = pluginInfo.normalizedName;\n compiler.options.output.publicPath = \"auto\";\n compiler.options.output.path = path.resolve(context, \"dist\");\n compiler.options.output.clean = true;\n compiler.options.output.library = { type: \"commonjs-module\" };\n\n if (!compiler.options.target) {\n compiler.options.target = \"async-node\";\n }\n\n if (!compiler.options.mode) {\n compiler.options.mode = process.env.NODE_ENV === \"development\" ? \"development\" : \"production\";\n }\n\n if (compiler.options.devtool === undefined) {\n compiler.options.devtool = \"source-map\";\n }\n\n if (!compiler.options.infrastructureLogging) {\n compiler.options.infrastructureLogging = {\n level: \"warn\",\n };\n }\n\n this.ensureTypeScriptLoader(compiler);\n\n if (!compiler.options.resolve) {\n compiler.options.resolve = {};\n }\n compiler.options.resolve.extensions = [\"...\", \".tsx\", \".ts\"];\n compiler.options.resolve.conditionNames = [\n \"webpack\",\n \"import\",\n \"module\",\n \"require\",\n \"node\",\n \"default\",\n ];\n if (compiler.options.resolve.byDependency) {\n for (const depType of Object.keys(compiler.options.resolve.byDependency)) {\n const depConfig = (\n compiler.options.resolve.byDependency as Record<string, { conditionNames?: string[] }>\n )[depType];\n if (depConfig?.conditionNames) {\n depConfig.conditionNames = depConfig.conditionNames.filter((c) => c !== \"development\");\n }\n }\n }\n compiler.options.resolve.fallback = {\n ...compiler.options.resolve.fallback,\n bufferutil: false,\n \"utf-8-validate\": false,\n };\n }\n\n private ensureTypeScriptLoader(compiler: Compiler) {\n if (!compiler.options.module) {\n compiler.options.module = { rules: [] } as any;\n }\n\n if (!compiler.options.module.rules) {\n compiler.options.module.rules = [];\n }\n\n const hasTsLoader = compiler.options.module.rules.some(\n (rule: any) =>\n typeof rule === \"object\" &&\n rule !== null &&\n \"test\" in rule &&\n rule.test instanceof RegExp &&\n rule.test.test(\".ts\"),\n );\n\n if (!hasTsLoader) {\n compiler.options.module.rules.push({\n test: /\\.tsx?$/,\n use: \"builtin:swc-loader\",\n exclude: /node_modules/,\n });\n }\n }\n\n private configureDevServer(compiler: Compiler, pluginInfo: any, devConfig: any, port: number) {\n if (!compiler.options.devServer) {\n return;\n }\n\n const context = compiler.options.context || process.cwd();\n const originalSetup = compiler.options.devServer.setupMiddlewares;\n\n compiler.options.devServer.port = port;\n compiler.options.devServer.static = path.join(context, \"dist\");\n compiler.options.devServer.hot = true;\n compiler.options.devServer.devMiddleware = { writeToDisk: true };\n compiler.options.devServer.headers = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, POST, PUT, DELETE, PATCH, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"X-Requested-With, content-type, Authorization\",\n };\n\n compiler.options.devServer.client = {\n logging: \"warn\",\n overlay: {\n warnings: false,\n errors: true,\n },\n };\n\n compiler.options.devServer.setupMiddlewares = (middlewares, devServer) => {\n setupPluginMiddleware(devServer, pluginInfo, devConfig, port);\n return originalSetup ? originalSetup(middlewares, devServer) : middlewares;\n };\n }\n}\n"],"mappings":";;;;;;;;;;AA2BA,IAAa,qBAAb,MAAgE;CAC9D,OAAO;CAEP,YAAY,AAAQ,UAAwC,EAAE,EAAE;EAA5C;;CAEpB,MAAM,UAAoB;AACxB,WAAS,MAAM,gBAAgB,IAAI,KAAK,OAAO,gBAAgB;GAC7D,MAAM,UAAW,SAA0C;GAC3D,MAAM,YAAY,SAAS,SAAS;GACpC,MAAM,QAAQ,SAAS,aAAa,kCAAkC;AAEtE,eAAY,MAAM,cAAc,WAAW;IAAE,MAAM,KAAK;IAAM;IAAO,EAAE,YAAY;IACjF,MAAM,UAAU,SAAS,QAAQ,WAAW,QAAQ,KAAK;IACzD,MAAM,aAAa,cAAc,QAAQ;IACzC,MAAM,mBAAmB,KAAK,QAAQ,oBAAoB;IAC1D,MAAM,mBAAmB,KAAK,QAAQ,oBAAoB;IAE1D,MAAM,qBAAqB,KAAK,KAAK,SAAS,SAAS,iBAAiB;IAExE,IAAI;IAEJ,MAAM,cAAc,OAAO,aAA6C;AACtE,SAAI,CAAC,GAAG,WAAW,SAAS,CAC1B,QAAO;AAGT,SAAI,CADU,GAAG,SAAS,SAChB,CAAC,QAAQ,CACjB,QAAO;AAET,SAAI;AACF,aAAO,MAAM,GAAG,SAAS,SAAS,UAAU,OAAO;aAC7C;AACN,aAAO;;;AAIX,oBAAiB,MAAM,YAAY,mBAAmB,IAAK;AAE3D,QAAI,CAAC,eAAe;KAClB,MAAM,aAAa,QAAQ,MAAM,IAAI,CAAC,KAAK;KAC3C,MAAM,aAAa,KAAK,KAAK,SAAS,SAAS,cAAc,IAAI,OAAO,iBAAiB;AAEzF,qBAAiB,MAAM,YAAY,WAAW,IAAK;AAEnD,SAAI,CAAC,eAAe;AAClB,cAAQ,KACN,mDAAmD,mBAA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