From 042188cc7417d68f15e4a7f1f3cdc69047a268bd Mon Sep 17 00:00:00 2001 From: yiling Date: Fri, 5 Jun 2026 14:34:22 +0800 Subject: [PATCH] feat(publish): compile and package workers for npm and isolate workflow imports --- apps/agent/src/index.ts | 2 +- apps/transcode/src/index.ts | 2 +- .../workflow-core/src/bun-temporal-plugin.ts | 25 +- packages/workflow-core/src/workflow.ts | 2 + scripts/build-npm.ts | 260 +++++++++++++----- 5 files changed, 219 insertions(+), 72 deletions(-) diff --git a/apps/agent/src/index.ts b/apps/agent/src/index.ts index c5be725e..fada3875 100644 --- a/apps/agent/src/index.ts +++ b/apps/agent/src/index.ts @@ -14,7 +14,7 @@ async function run() { const options: { workflowBundle?: unknown; workflowsPath?: string } = {} if (process.env.NODE_ENV === 'production') { // @ts-ignore: Bun temporal plugin macro - const { default: workflowBundle } = await import('./workflows:::workflow') + const { default: workflowBundle } = await import('./workflows.ts:::workflow') options.workflowBundle = workflowBundle } else { options.workflowsPath = new URL('./workflows.ts', import.meta.url).pathname diff --git a/apps/transcode/src/index.ts b/apps/transcode/src/index.ts index 63a093c1..5dba543c 100644 --- a/apps/transcode/src/index.ts +++ b/apps/transcode/src/index.ts @@ -13,7 +13,7 @@ async function run() { const options: { workflowBundle?: unknown; workflowsPath?: string } = {} if (process.env.NODE_ENV === 'production') { // @ts-ignore: Bun temporal plugin macro - const { default: workflowBundle } = await import('./workflows:::workflow') + const { default: workflowBundle } = await import('./workflows.ts:::workflow') options.workflowBundle = workflowBundle } else { options.workflowsPath = new URL('./workflows.ts', import.meta.url).pathname diff --git a/packages/workflow-core/src/bun-temporal-plugin.ts b/packages/workflow-core/src/bun-temporal-plugin.ts index 161b5c52..2cec9cc2 100644 --- a/packages/workflow-core/src/bun-temporal-plugin.ts +++ b/packages/workflow-core/src/bun-temporal-plugin.ts @@ -33,9 +33,32 @@ export function temporalWorkflow(options: TemporalWorkflowPluginOptions = {}): B build.onLoad({ filter: /.*/, namespace: 'temporal-workflow' }, async (args) => { const workflowsPath = args.path + // The bundleOptions contains raw parameters for Temporal bundleWorkflowCode which uses Webpack. + // We cast options.bundleOptions to any to check for webpackConfigHook. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const originalHook = (options.bundleOptions as any)?.webpackConfigHook + const bundleOptions = { + ...options.bundleOptions, + // Webpack config is untyped inside Temporal's webpackConfigHook callback. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + webpackConfigHook: (config: any) => { + config.resolve = config.resolve || {} + config.resolve.alias = { + ...config.resolve.alias, + '@shumai/workflow-core': + require.resolve('@shumai/workflow-core/src/workflow-utils.ts'), + } + console.log('Webpack config aliases:', config.resolve.alias) + if (originalHook) { + return originalHook(config) + } + return config + }, + } + const bundle = await bundleWorkflowCode({ workflowsPath, - ...options.bundleOptions, + ...bundleOptions, }) return { diff --git a/packages/workflow-core/src/workflow.ts b/packages/workflow-core/src/workflow.ts index 1a64b3a8..24881516 100644 --- a/packages/workflow-core/src/workflow.ts +++ b/packages/workflow-core/src/workflow.ts @@ -110,6 +110,7 @@ export class WorkflowService { '@temporalio/workflow': path.dirname( require.resolve('@temporalio/workflow/package.json'), ), + '@shumai/workflow-core': require.resolve('./workflow-utils'), } return config }, @@ -130,6 +131,7 @@ export class WorkflowService { '@temporalio/workflow': path.dirname( require.resolve('@temporalio/workflow/package.json'), ), + '@shumai/workflow-core': require.resolve('./workflow-utils'), } return config }, diff --git a/scripts/build-npm.ts b/scripts/build-npm.ts index 8cb8adf8..4e4c75bd 100644 --- a/scripts/build-npm.ts +++ b/scripts/build-npm.ts @@ -4,91 +4,124 @@ import path from 'node:path' import tailwindPlugin from 'bun-plugin-tailwind' import { temporalWorkflow } from '../packages/workflow-core/src/bun-temporal-plugin' -console.log('\nšŸš€ Starting NPM packaging build process...\n') +console.log('\nšŸš€ Starting NPM packaging build process for all applications...\n') -const outdir = path.join(process.cwd(), 'dist') +const rootDir = process.cwd() +const distDir = path.join(rootDir, 'dist') // 1. Clean previous build -if (existsSync(outdir)) { - console.log(`šŸ—‘ļø Cleaning previous build at ${outdir}`) - await rm(outdir, { recursive: true, force: true }) +if (existsSync(distDir)) { + console.log(`šŸ—‘ļø Cleaning previous build at ${distDir}`) + await rm(distDir, { recursive: true, force: true }) } -await mkdir(outdir, { recursive: true }) +await mkdir(distDir, { recursive: true }) -// 2. Build & Compile to standalone executable -console.log('šŸ“¦ Compiling to standalone binary...') -const result = await Bun.build({ - entrypoints: ['./apps/web/src/index.ts'], - root: '.', - target: 'bun', - outdir: outdir, - minify: true, - compile: { - autoloadPackageJson: true, - }, +const rootPackageJson = JSON.parse(await Bun.file('package.json').text()) +const version = rootPackageJson.version || '0.1.0' + +const commonExternal = [ + '@prisma/client', + '@prisma/adapter-pg', + 'pg', + 'sharp', + 'pino', + 'pino-pretty', + '@temporalio/activity', + '@temporalio/client', + '@temporalio/worker', + '@temporalio/workflow', + 'prisma', +] + +// Function to compile a single application +async function compileApp({ + name, + entrypoint, + outdir, + binaryName, + plugins = [], + external = commonExternal, +}: { + name: string + entrypoint: string + outdir: string + binaryName: string + // eslint-disable-next-line @typescript-eslint/no-explicit-any + plugins?: any[] + external?: string[] +}) { + console.log(`\nšŸ“¦ Building ${name}...`) + await mkdir(outdir, { recursive: true }) + + const result = await Bun.build({ + entrypoints: [entrypoint], + root: '.', + target: 'bun', + outdir: outdir, + minify: true, + compile: { + autoloadPackageJson: true, + }, + plugins, + external, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + publicPath: '/', + }) + + if (!result.success) { + console.error(`āŒ Binary compilation failed for ${name}!`) + for (const log of result.logs) { + console.error(log) + } + process.exit(1) + } + + // Rename generated binary (usually Bun names it 'src' or the folder name of the entrypoint) + // For './apps/web/src/index.ts', './apps/agent/src/index.ts', './apps/transcode/src/index.ts', the parent is 'src' + const generatedFile = path.join(outdir, 'src') + const finalFile = path.join(outdir, binaryName) + + if (existsSync(generatedFile)) { + console.log(`āž”ļø Moving binary to final location: ${finalFile}`) + await cp(generatedFile, finalFile) + await rm(generatedFile) + } else { + console.error(`āŒ Could not find compiled binary at ${generatedFile}`) + process.exit(1) + } +} + +// 2. Build Main App (shumai) +const shumaiOutDir = path.join(distDir, 'shumai') +await compileApp({ + name: 'shumai', + entrypoint: './apps/web/src/index.ts', + outdir: shumaiOutDir, + binaryName: 'shumai', plugins: [ temporalWorkflow({ bundleOptions: {}, }), tailwindPlugin, ], - external: [ - '@prisma/client', - '@prisma/adapter-pg', - 'pg', - 'sharp', - 'pino', - 'pino-pretty', - '@temporalio/activity', - '@temporalio/client', - '@temporalio/worker', - '@temporalio/workflow', - 'prisma', - ], - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - publicPath: '/', }) -if (!result.success) { - console.error('āŒ Binary compilation failed!') - for (const log of result.logs) { - console.error(log) - } - process.exit(1) -} - -// 3. Rename generated binary to 'shumai' -// Entrypoint './apps/web/src/index.ts' with outdir 'dist' outputs to 'dist/src' (parent folder name of the entrypoint) -const generatedFile = path.join(outdir, 'src') -const finalFile = path.join(outdir, 'shumai') - -if (existsSync(generatedFile)) { - console.log(`āž”ļø Moving binary to final location: ${finalFile}`) - await cp(generatedFile, finalFile) - // Remove the generated source file - await rm(generatedFile) -} else { - console.error(`āŒ Could not find compiled binary at ${generatedFile}`) - process.exit(1) -} - -// 4. Copy database schema and migrations -console.log('šŸ“‚ Copying database files...') -const dbDest = path.join(outdir, 'prisma') +// Copy database schema and migrations for main app +console.log('šŸ“‚ Copying database files for shumai...') +const dbDest = path.join(shumaiOutDir, 'prisma') await mkdir(dbDest, { recursive: true }) await cp('./packages/db/prisma/schema.prisma', path.join(dbDest, 'schema.prisma')) if (existsSync('./packages/db/prisma/migrations')) { await cp('./packages/db/prisma/migrations', path.join(dbDest, 'migrations'), { recursive: true }) } -// 5. Generate package.json -console.log('šŸ“„ Generating package.json...') -const rootPackageJson = JSON.parse(await Bun.file('package.json').text()) -const packageJsonContent = { +// Generate package.json for main app +console.log('šŸ“„ Generating package.json for shumai...') +const shumaiPackageJson = { name: 'shumai', - version: rootPackageJson.version || '0.1.0', + version, description: 'A fullstack AI-powered media workspace and workflow engine', type: 'module', bin: { @@ -109,11 +142,100 @@ const packageJsonContent = { prisma: '^7.7.0', }, } - await writeFile( - path.join(outdir, 'package.json'), - JSON.stringify(packageJsonContent, null, 2), + path.join(shumaiOutDir, 'package.json'), + JSON.stringify(shumaiPackageJson, null, 2), 'utf-8', ) -console.log('āœ… Build completed successfully!') +// 3. Build Agent App (shumai-agent) +const agentOutDir = path.join(distDir, 'shumai-agent') +await compileApp({ + name: 'shumai-agent', + entrypoint: './apps/agent/src/index.ts', + outdir: agentOutDir, + binaryName: 'shumai-agent', + plugins: [ + temporalWorkflow({ + bundleOptions: {}, + }), + ], +}) + +// Generate package.json for agent app +console.log('šŸ“„ Generating package.json for shumai-agent...') +const agentPackageJson = { + name: 'shumai-agent', + version, + description: 'AI worker agent for the shumai media workspace', + type: 'module', + bin: { + 'shumai-agent': './shumai-agent', + }, + files: ['shumai-agent'], + dependencies: { + '@prisma/client': '^7.7.0', + '@prisma/adapter-pg': '^7.7.0', + pg: '^8.20.0', + sharp: '^0.34.5', + pino: '^10.3.1', + 'pino-pretty': '^13.1.3', + '@temporalio/activity': '^1.16.1', + '@temporalio/client': '^1.16.1', + '@temporalio/worker': '^1.16.1', + '@temporalio/workflow': '^1.16.1', + prisma: '^7.7.0', + }, +} +await writeFile( + path.join(agentOutDir, 'package.json'), + JSON.stringify(agentPackageJson, null, 2), + 'utf-8', +) + +// 4. Build Transcode App (shumai-transcode) +const transcodeOutDir = path.join(distDir, 'shumai-transcode') +await compileApp({ + name: 'shumai-transcode', + entrypoint: './apps/transcode/src/index.ts', + outdir: transcodeOutDir, + binaryName: 'shumai-transcode', + plugins: [ + temporalWorkflow({ + bundleOptions: {}, + }), + ], +}) + +// Generate package.json for transcode app +console.log('šŸ“„ Generating package.json for shumai-transcode...') +const transcodePackageJson = { + name: 'shumai-transcode', + version, + description: 'Media transcoding worker for the shumai media workspace', + type: 'module', + bin: { + 'shumai-transcode': './shumai-transcode', + }, + files: ['shumai-transcode'], + dependencies: { + '@prisma/client': '^7.7.0', + '@prisma/adapter-pg': '^7.7.0', + pg: '^8.20.0', + sharp: '^0.34.5', + pino: '^10.3.1', + 'pino-pretty': '^13.1.3', + '@temporalio/activity': '^1.16.1', + '@temporalio/client': '^1.16.1', + '@temporalio/worker': '^1.16.1', + '@temporalio/workflow': '^1.16.1', + prisma: '^7.7.0', + }, +} +await writeFile( + path.join(transcodeOutDir, 'package.json'), + JSON.stringify(transcodePackageJson, null, 2), + 'utf-8', +) + +console.log('\nāœ… All applications built and packaged successfully!')