import { writeFile } from 'node:fs/promises' import path from 'node:path' import { createRequire } from 'node:module' import * as esbuild from 'esbuild' const require = createRequire(import.meta.url) const mobileRoot = path.resolve(import.meta.dirname, '..') const outputPath = path.join( mobileRoot, 'src', 'components', 'pr-sidebar', 'mermaid-page-engine.generated.ts' ) // Why: the page imports mermaid on demand, and `import('mermaid')` from inside the app bundle lands // 103 emitted scripts rather than one -- mermaid lazily imports each of its own diagram types, so // esbuild splits along those boundaries. All 103 sit inside the OTA generation the phone has // already downloaded, so the split buys nothing in transfer and spends 103 of the 256 manifest // assets the shell will load. Bundled here into one artifact, which the page imports on demand // exactly as it imported the package. // // Unlike the sibling that builds the WebView engine, this is not a string: it is the module the // page evaluates, so it is emitted as source and `mermaid-page-engine.ts` is what types it. async function main() { const { version } = require(require.resolve('mermaid/package.json')) const { outputFiles } = await esbuild.build({ absWorkingDir: mobileRoot, stdin: { contents: "export { default } from 'mermaid'\n", resolveDir: mobileRoot, loader: 'ts', sourcefile: 'mermaid-page-engine-entry.ts' }, bundle: true, format: 'esm', // The whole point: one file, so the app bundle emits one deferred chunk for it. splitting: false, minify: true, // The floor the shell's WebViews hold, the same pair the terminal engine is built for. target: ['chrome74', 'safari15'], write: false, charset: 'utf8', legalComments: 'none', logLevel: 'silent', nodePaths: [path.join(mobileRoot, 'node_modules')], define: { 'process.env.NODE_ENV': '"production"' } }) const bundle = Buffer.from(outputFiles[0].contents).toString('utf8') const source = [ '// Generated by scripts/build-mermaid-page-engine.mjs.', `// Package: mermaid@${version}, bundled as one ESM module for the page.`, '// Do not edit by hand; regenerate via pnpm postinstall.', '// @ts-nocheck -- minified vendor output; mermaid-page-engine.ts is where this is typed.', bundle, '' ].join('\n') await writeFile(outputPath, source) } await main()